WHERE IN with Doctrine 2 DBAL - mysql

How to use a WHERE IN clause with Doctrine DBAL ?
The following query doesn't work, it search the name "Bob","Elvis","Bill" (as a string) :
$users = $dbc->fetchAssoc("SELECT * FROM users WHERE name IN(:users_names)", array(
'users_names' => '"Bob","Elvis","Bill"'
));
I tried with an array, it's the same problem.

Try this :
$searchParameters = array("Bob","Elvis","Bill");
$users = "SELECT * FROM users WHERE name IN (?1)";
$q = $em->createQuery($users)
->setParameter(1, $searchParameters);
$result = $q->execute();

Related

Symfony passing custom sql parameters in the query

I am trying to pass table name and column name from String to the sql query, but for some reason it doesnt work.
This is an example of what am trying to do from symfony 4.4 documentation :
This is how I am trying to do it :
$sql = "SELECT
:col,
COUNT(*) AS `cnt`
FROM
:tab
GROUP BY
:col
";
$stmt = $conn->prepare($sql);
$stmt->execute([ 'col' => $col , 'tab' => $tab ]);
return $stmt->fetchAllAssociative();
output :
meanwhile, it works like this :
$sql = "SELECT
typeCl,
COUNT(*) AS `cnt`
FROM
client
GROUP BY
typeCl
";
$stmt = $conn->prepare($sql);
$stmt->execute([ 'col' => $col , 'tab' => $tab ]);
return $stmt->fetchAllAssociative();
And I still want to make my table and column parametrable .. is there anyway to do that ??
(It is not about my String values I used dump and die and make sure nothign wrong with that)
This is how i made it work :
$sql = "SELECT ".$col.",
COUNT(*) AS `cnt`
FROM
".$tab."
GROUP BY
".$col."
";
$stmt = $conn->prepare($sql);
$stmt->execute([ 'col' => $col , 'tab' => $tab ]);
return $stmt->fetchAllAssociative();

Laravel Get Record ID from Update Query

For this update query, I'm trying to get the id after I run it.
$results = DB::table('testDB123.users')
->where('fbID', '=', $x['id'])
->update([
'updated_at' => $x['currDate'],
'fbFirstName' => $x['firstName'],
'fbLastName' => $x['lastName']
]
);
Tried this with no luck $results->id
Is there anything similar to insertGetId for update queries?
$id = DB::table($table1)->insertGetId([...])
update() method doesn't return an object, so you have two options:
Option 1
Use updateOrCreate():
$user = User::updateOrCreate(['fbID' => $x['id']], $dataArray);
$id = $user->id;
Option 2
Get an object and update it:
$user = User::where('fbID', '=', $x['id'])->first();
$user->update($dataArray);
$id = $user->id;

Symfony 1.4 select query with selected columns is not working

I want to run following query in symfony doctrine.
SELECT p.id AS id FROM skiChaletPrice p WHERE ski_chalet_id = ? AND month = ?
I wrote my doctrine query as following.
$q = Doctrine_Query::create()
->select('p.id AS id')
->from('skiChaletPrice p')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from);
$result = $q->fetchOne();
if ($result->count() > 0) {
return $result->toArray();
} else {
return null;
}
But my result always include all columns in the table. What the issue? Please help me.
The issue is that fetchOne() will return a Doctrine object, which implicitly contains all the columns in the table. $result->toArray() is converting that doctrine object to an array, which is why you get all the columns.
If you only want a subset of column, don't hydrate an object, instead do something like this:
$q = Doctrine_Query::create()
->select('p.id AS id')
->from('skiChaletPrice p')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from);
$results = $q->execute(array(), Doctrine::HYDRATE_SCALAR);
See http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/data-hydrators.html
This is how I should do it:
$result = Doctrine_Query::create()
->select('id')
->from('skiChaletPrice')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from)
->limit(1)
->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
// result will be a single id or 0
return $result ?: 0;
// if you want array($id) or array() inseatd
// return (array) $result;

How to run raw SQL Query with Zend Framework 2

Is there a way to execute a SQL String as a query in Zend Framework 2?
I have a string like that:
$sql = "SELECT * FROM testTable WHERE myColumn = 5"
now I want to execute this string directly.
Just pass the sql string to your db adapter like this:
$resultSet = $adapter->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
And if you want to pass parameters:
$sql = "SELECT * FROM testTable WHERE myColumn = ?";
$resultSet = $adapter->query($sql, array(5));
EDIT: Please note that the query method does not always returns a resultset. When its a resultset producing query(SELECT) it returns a \Zend\Db\ResultSet\ResultSet otherwise(INSERT, UPDATE, DELETE, ...) it will return a \Zend\Db\Adapter\Driver\ResultInterface.
And when you leave the second Parameter empty you will get a \Zend\Db\Adapter\Driver\StatementInterface which you can execute.
use Zend\Db\Sql\Sql;
use Zend\Db\Adapter\Adapter;
$dbAdapterConfig = array(
'driver' => 'Mysqli',
'database' => 'dbname',
'username' => 'dbusername',
'password' => 'dbuserpassword'
);
$dbAdapter = new Adapter($dbAdapterConfig);
$sql = new Sql($dbAdapter);
$select = $sql->select();
$select->from('testTable');
$select->where(array('myColumn' => 5));
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
S. docu: Zend\Db → Zend\Db\Sql
If you are using tableGateway, you can run your raw SQL query using this statement,
$this->tableGateway->getAdapter()->driver->getConnection()->execute($sql);
where $sql pertains to your raw query. This can be useful for queries that do not have native ZF2 counterpart like TRUNCATE / INSERT SELECT statements.
If you have EntityManager $em on your hands, you can do something like this:
$select = $em->getConnection()->executeQuery("
SELECT a.id, a.title, a.announcement, asvc.service_id, COUNT(*) AS cnt,
GROUP_CONCAT(asvc.service_id SEPARATOR \", \") AS svc_ids
FROM article AS a
JOIN articles_services AS asvc ON asvc.article_id = a.id
WHERE
asvc.service_id IN (
SELECT tsvc.service_id
FROM tender AS t
JOIN tenders_services AS tsvc ON tsvc.tender_id = t.id
WHERE t.id = :tenderId
)
GROUP BY a.id
ORDER BY cnt DESC, a.id DESC
LIMIT :articlesCount
", [
'articlesCount' => 5,
'tenderId' => $tenderId,
], [
'articlesCount' => \PDO::PARAM_INT,
]);
$result = $select->fetchAll(); // <-- here are array of wanted rows
I think this way to execute complex queries is best for Zend. But may be I'm not very smart in Zend still. Will glad to see if it helps to someone.

ZF2 how to rename name of field with join

Because my join includes a field named 'id' as well, I need to rename this field name during my sql so it won't override my id field name from the first selected tabel.
My query look likes as follow;
$select = new \Zend\Db\Sql\Select();
$select->from('websites');
$select->join(array('s' => 'websites_statistics'), 's.website_id = websites.id');
$select->where(array('websites.website' => $website));
$select->order('s.timestamp DESC')->limit(1);
$rowset = $this->tableGateway->selectWith($select);
$row = $rowset->current();
return $row;
So, 's' 'id' field should be renamed to something like 'stat_id'.
Thanks in advance!
Nick
$select = new \Zend\Db\Sql\Select();
$select->from('websites');
->join(array('s' => 'websites_statistics'), 's.website_id = websites.id',
array('stat_id' => 's.id')); // <-- here is the alias
->where(array('websites.website' => $website));
->order('s.timestamp DESC')
->limit(1);
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from(array('p' => 'sub_categories'), array('subcategory_id'=>'p.subcategory_id','subname'=>'p.name'))
->join(array('pa' => 'categories'), 'pa.category_id = p.category_id', array('catname'=>'pa.name'));
$result = $this->getAdapter()->fetchAll($select);
*
And also we can use this method
use Zend\Db\Sql\Expression;
->join(array('s' => 'websites_statistics'), 's.website_id = websites.id',
array('stat_id' => new Expression('s.id'))); // <-- here is the alias
This is best method If you have to use Mysql 'AS' on zf2
example : array('Month' => new Expression('DATE_FORMAT(`salesInvoiceIssuedDate`, "%m")'))