Create Multiple Campaign From MYSQL Query - google-ads-api

have a MYSQL database and I would like to add new campaign for each row I have in the MYSQL table.
The code below creates only one campaign, but I want to create multiple campaigns e.g. each row in the table should be used to create new campaign, please advise.
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
$sql = "SELECT * FROM table";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
// Create a campaign with required and optional settings.
$campaign = new Campaign();
$campaign->setName($row["name"]. uniqid());
$campaign->setAdvertisingChannelType(AdvertisingChannelType::SEARCH);
}

Related

PHP Spreadsheet: After saving data to a new worksheet, the data of the previous worksheets are deleted

I am creating a script to save CSV data into an excel document, but in different worksheets, I mean, every CSV doc will go into a new worksheet, but after saving data to a new worksheet the previous data that are in the other worksheets are deleted. This is my code
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
$spreadsheet = new Spreadsheet();
$spreadsheet2 = new Spreadsheet();
$reader = new PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load('test.xlsx');
$numSheets = $spreadsheet -> getSheetCount();
$reader2 = new PhpOffice\PhpSpreadsheet\Reader\Csv();
/* Set CSV parsing options */
$reader2->setDelimiter(',');
$reader2->setEnclosure('"');
$reader2->setSheetIndex($numSheets);
echo $numSheets;
/* Load a CSV file and save as a XLS */
$spreadsheet2 = $reader2->load('testcsv.csv');
$writer = new Xlsx($spreadsheet2);
$writer->save('test.xlsx');
$spreadsheet->disconnectWorksheets();
unset($spreadsheet);
?>
With this only the last worksheet have data
enter image description here
I want to emphasize that I have no errors but I am not achieving what I want to do
The problem is that you use
$numSheets = $spreadsheet -> getSheetCount();
but you must count your sheet numbers and add a new sheet in your file.
I would suggest you use a loop.
$numSheets = $spreadsheet -> getSheetCount();
foreach($csvs as $csv){
// Create a new worksheet called "My Data"
$myWorkSheet = new \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet($spreadsheet, 'My Data');
// Attach the "My Data" worksheet as the first worksheet in the Spreadsheet object
$spreadsheet->addSheet($myWorkSheet, $numSheets);
$numSheets++;
}
More information here

How to use WHERE for foreign key of a JOINed table in Doctrine?

I have a structure of three tables/entities: User (table users; columns id and name), Room (table roome; columns id and number), and RoomUser (user_room; columns id, user_id, room_id).
Now I want to retrieve all Rooms for a User with a given id. How to do this without to join Rooms?
$userId = 123;
// ...
$queryBuilder = $this->entityManager->createQueryBuilder();
$query = $queryBuilder->select('r')
->from(Room::class, 'r')
->join('r.RoomUsers', 'ru')
->where('ru.room_id = :userId') // room_id? ru.Room.id?
->setParameter('userId', $userId)
->getQuery();
$rooms = $query->getResult(Query::HYDRATE_OBJECT);
So in SQL it would be something like
SELECT *
FROM rooms
JOIN room_users ON room_users.room_id = rooms.id
WHERE user_id = 123;
How to implement this simple request with the QueryBuilder?
You can use MEMBER OF (docs) for that:
$query = $queryBuilder->select('r')
->from(Room::class, 'r')
->where(':user_id MEMBER OF r.users')
->setParameter('user_id', $userId)

How to get the last generated value for a custom PRIMARY KEY column in ZF2?

With Zend\Db\Adapter\Driver\ResultInterface#getGeneratedValue() Zend\Db provides a simple way to get the ID of the last INSERTed entry, e.g.:
$action = new Insert('my_table');
$action->values($data);
$sql = new Sql($this->dbAdapter);
$statement = $sql->prepareStatementForSqlObject($action);
$result = $statement->execute();
$newId = $result->getGeneratedValue();
But it seems only to work, if the PRIMARY KEY column calls "id". How to retrieve the generatedValue for a PRIMARY KEY defined on another column?
Preferably use Zend\Db\TableGateway\TableGateway offering the method getLastInsertValue().
use Zend\Db\TableGateway\TableGateway;
$myTable = new TableGateway('my_table', $this->dbAdapter);
$action = new Insert('my_table');
$action->values($data);
$myTable->insertWith($action);
$newId = $myTable->getLastInsertValue();
$this->dbAdapter->getDriver()->getLastGeneratedValue();

Creating relationships taking too long in Neo4j using Neo4php

I have been trying to create nodes and relations ships for our new module with neo4jphp [https://github.com/jadell/neo4jphp/wiki].
I am using cypher queries for the same.
Creating nodes with below query:
$queryNodes = "CREATE (n:User { props } ) ";
$query = new Everyman\Neo4j\Cypher\Query($client, $queryNodes, array('props' => $arrNodeProperties));
$result = $query->getResultSet();
Creating relationships with below query:
$queryRelations = "
MATCH (authUser: User { userid: 0001 }),(friend)
WHERE friend.userid IN ['" . implode("','",$relations) . "']
CREATE UNIQUE (authUser)-[r:KNOWS { connection: 'user_friend' }]->(friend)";
So far node creation works gr8.
But when i try to create Unique relationships for the nodes, it takes too long....
Note:
There is unique constraint userid for label User, hence node with label user is indexed by Neo4j on property userid.
CREATE CONSTRAINT ON (user:User) ASSERT user.userid IS UNIQUE
Questions:
Is there any other way we can achieve creating unique relationships.
Can i use index on relationships?? If Yes how can I achieve the same.
You might try use use MERGE instead of CREATE UNIQUE. Additionally use a Cypher parameter for the fried's list instead of concatenation on client side, see http://docs.neo4j.org/chunked/stable/cypher-parameters.html
Finally I worked it out with few changes...
Thanks #MichaelHunger for the help.
So here is how i did it...
Creating Unique Nodes using MERGE, FOREACH, ON CREATE SET and params:
$queryNodes = "
FOREACH (nodeData IN {nodeProperties}|
MERGE (n:User { userid: nodeData.userid })
ON CREATE SET
n.login = nodeData.login,
n.userid = nodeData.userid,
n.username = nodeData.username,
n.name = nodeData.name,
n.gender = nodeData.gender,
n.profile_pic = nodeData.profile_pic,
n.create_date = timestamp()
ON MATCH SET
n.update_date = timestamp()
)
";
$query = new Everyman\Neo4j\Cypher\Query($client, $queryNodes, array('nodeProperties' => $arrNodeProperties));
$result = $query->getResultSet();
Creating Unique Relationships with below query:
$queryRelations = "
MATCH (authUser: User { userid: {authUserid} }), (friend:User)
WHERE friend.userid IN {friendUserIds}
CREATE UNIQUE (authUser)-[r:KNOWS { connection: 'user_friend' }]->(friend)
";
$query = new Everyman\Neo4j\Cypher\Query($client, $queryRelations, array('friendUserIds' => $arrFriendUserId, 'authUserid' => $authUserid));
$result = $query->getResultSet();
Please comment if we can improve the same even further.

How to use having() in tableGateway in ZF2

How to use having() clause in ZF2?
There is almost no examples on the web how to prepare correct select object with having.
I have query like:
SELECT root_schema_id as `schema_id`
FROM `standard_specific_root_schemas`
WHERE `vehicle_id` IN (".implode(",",$vehiclesIds).")
GROUP BY `schema_id`, rootSubGroup_id HAVING count(*)=".$noOfVehicles
And I'm trying to run it in ZF2:
public function getVehicleWithinCommonRootSubgroupInSpecific($vehiclesIds)
{
$where = new Where();
$where->in('vehicle_id', $vehiclesIds);
$having = new Having('count(*) = '.count($vehiclesIds));
$rowset = $this->tableGateway->select(function (Select $select) use ($where, $having) {
$select
->where($where)
->having($having);
});
if (!$rowset) {
throw new \Exception("Could not find schemas for group $groupId");
}
return $rowset;
}
Of course that part in ZF2 is not finished yet as I wanted to check if it's working first.
I've tried few ways of providing params to having method but everything generates errors.
Help please, I'm desperate...
I cannot test your query, but can try and reproduce the query you need.
I adjusted the having to use ->expression() instead of a variable via the construct.
I also added the group statement.
To view the query I added a var_dump:
$where = new \Zend\Db\Sql\Where();
$where->in('vehicle_id', $vehiclesIds);
$having = new \Zend\Db\Sql\Having();
$having->expression('count(*) = ?', count($vehiclesIds));
$rowset = $this->tableGateway->select(function (\Zend\Db\Sql\Select $select) use ($where, $having) {
$select
->where($where)
->group(array('schema_id', 'rootSubGroup_id'))
->having($having);
var_dump( $select->getSqlString() );
});
Let me know if this helps.
To circumvent the error mentioned in the comments you would have to do something like below:
$sql = $this->tableGateway->getSql();
$select = $sql->select();
$where = new \Zend\Db\Sql\Where();
$where->in('vehicle_id', $vehiclesIds);
$having = new \Zend\Db\Sql\Having();
$having->expression('count(*) = ?', count($vehiclesIds));
$select
->where($where)
->group(array('schema_id', 'rootSubGroup_id'))
->having($having);
$preparedQuery = $sql->prepareStatementForSqlObject($select);
var_dump( $preparedQuery->getSql() );
However, if I'm right, the tableGateway does this for you so the error should go away once you start using the select to query the database.
Also, you can use the above to do that too, just replace this:
$preparedQuery = $sql->prepareStatementForSqlObject($select);
var_dump( $preparedQuery->getSql() );
With:
$this->tableGateway->selectWith($select);

Resources