I have a SQL statement
select a.username
from friendships f1
inner join friendships f2 on (f1.user = f2.friend and f1.friend = f2.user)
inner join users a ON (a.user_id = f1.friend) where f1.user = '24'
I excuted this query on phpmyadmin and it's OK.
But I don't knoe how to do this query in Zend
$select = $this->_db_table->select()
->setIntegrityCheck(false)
->from(array('f1' => 'friendships'), array('u.*'))
->joinInner(array('f2' => 'friendships'),
array('f1.user = f2.friend', 'f1.friend = f2.user'))
->joinInner(array('u' => 'users'), array('u.user_id = f1.friend'))
->where('f1.user = ?', $user_id);
I use this code but it doesn't work, any ideas?
What version of ZF are you using ? Here is how you would do it in ZF 1.12:
$this->_db_table->getAdapter()->select()
->from("friendships as f1")
->joinInner("friendships as f2", "f1.user = f2.friend AND f1.friend = f2.user")
->joinInner("users as a", "a.user_id = f1.friend", array("a.username"))
->where("f1.user = ?", $user_id)
->query()
->fetchAll(); // use ->fetch() if you only want to retrieve one record
Read more on in the manual:
What exactly doesn't work? Are you getting a PHP/Zend error or a SQL error?
You can use $select->assemble() to examine the prepared query and compare it against your expectation:
echo $select->assemble();
Related
How to write below mysql query using zend syntax?
UPDATE core_user_transaction as t
JOIN core_user_transaction_therapy AS cuts ON cuts.tid=t.tid
JOIN therapy_booking AS tb ON cuts.conf_id = tb.conf_id
JOIN therapy_service_fees AS fees ON cuts.fee_id=fees.id
JOIN therapy_service_taxes AS tst ON fees.service_id=tst.service_id
JOIN core_tax AS ct ON ct.tax_id = tst.tax_id
SET t.tax=ROUND(t.fee*(ct.tax_value/100),2),
t.amount = (ROUND(t.fee*(ct.tax_value/100),2)+t.fee)
WHERE tb.datetime >= '2015-10-01 00:00:00'
AND t.state = 'PENDING'
AND t.status ='ACTIVE'
Try this:
$adapter = new Zend\Db\Adapter\Adapter($driverConfig);
$sql = "YOUR_QUERY";
$statement = $adapter->query($sql);
$statement->execute();
Also please refer Zend\Db\Adapter
There is no possible with the 'update()' method provided by the Zend Db Adapter.
You can however, run the query manually using the adapter. Something like:
// $adapter is an instance of Zend_Db_Adapter
$adapter->query(YOUR QUERY HERE);
Given a query :
SELECT t1.c1, t2.c1 FROM t1,t2;
How to write it in Zend framework without using joins ?
Try the below join query in zend framework,
$sql = $this->tableGateway->getSql()->select();
$sql->join('table2', "table1.column1 = table2.column1", array(column1,column2), 'inner');
Assuming you have a common field (we'll call it c2), you can do something approximating a JOIN without actually doing a JOIN.
// we'll assume $adapter is an instance of Zend_Db_Adapter_Mysqli
$cols = $adapter->fetchAll(
'
SELECT
t1.c1 AS t1c1,
t2.c1 AS t2c1
FROM t1, t2
WHERE t1.c2 = t2.c2
'
);
Using Zend_Db_Select you can do it this way
$rows = $adapter->select()
->from('t1', array('t1c1' => 'c1'))
->from('t2', array('t2c1' => 'c1'))
->where('t1.c2 = t2.c2')
->query()->fetchAll();
I am new to PHP PDO and converting some regular MySQL queries to work with PDO.
The query below when tested in phpMyAdmin works great when the assigned values replaced the current placeholders in the SQL statement. But when I configure it to work as it is now with PDO, it does not produce any results or errors. Can someone please tell me or show me what is it that I am doing wrong?
Someone told me that I cannot pass parameters as references in the array.
And if correct, what is the best way for creating a solution and by using only the user ID passed through to the variable $uid. Thanks.
<p>// For testing</p>
<pre>$uid = 1;</pre>
<p> </p>
<pre>$array = array(
':uId' => ''.$uid.'',
':aId' => 'u.user_id',
':gID' => 'a.group_id',
':eID' => 'a.entry_id',
':pID' => 'a.permit_id'
);</pre>
// create the sql for qd_user_usam table
$sql = "SELECT u.user_id, a.acl_id, g.group_name, e.entry_level, p.permit_level
FROM qd_users as u, qd_users_acl as a, qd_users_group as g, qd_users_entry as e, qd_users_permission as p
WHERE u.user_id = :uID
AND a.acl_id = :aID
AND g.group_id = :gID
AND e.entry_id = :eID
AND p.permit_id = :pID";
<p>try
{</p>
<p>// Build the database PDOStatement</p>
<pre>$_stmt = $this->_dbConn->prepare($sql);</pre>
<pre>$_stmt->execute($array);</pre>
<pre>}
catch(PDOException $e)
{</pre>
<pre>$this->_errorMessage .= 'Error processing user login access. <br /> Line #'.__LINE__ .' '.$e ;</pre>
<pre>die($this->_errorMessage);
}</pre>
<pre>$results = $_stmt->fetchAll(PDO::FETCH_ASSOC);</pre>
<pre>return $results;</pre>
<pre>$results = null;</pre>
<pre>$this->_dbConn = null;</pre>
You take prepared statements wrong.
Thy have to be used not to represent whatever value in the query, but dynamically added data only.
While a.group_id is a column name and have to be written as is, without prepared statements.
// For testing
$uid = 1;
// create the sql for qd_user_usam table
$sql = "SELECT u.user_id, a.acl_id, g.group_name, e.entry_level, p.permit_level
FROM qd_users as u, qd_users_acl as a, qd_users_group as
g, qd_users_entry as e, qd_users_permission as p
WHERE u.user_id = ?
AND a.acl_id = u.user_id
AND g.group_id = a.group_id
AND e.entry_id = a.entry_id
AND p.permit_id = a.permit_id";
$_stmt = $this->_dbConn->prepare($sql);
$_stmt->execute(array($uid));
The problem is that you're trying to write your JOINs implicitly by binding the joined columns as parameters, which would not work. The parameters can not reference another column; they are seen as strings in this case. If you rewrite the query like this it should fix the JOIN problem:
SELECT u.user_id, a.acl_id, g.group_name, e.entry_level, p.permit_level
FROM qd_users AS u
JOIN qd_users_acl AS a ON (u.user_id = a.acl_id)
JOIN qd_users_group AS g ON (g.group_id = a.group_id)
JOIN qd_users_entry AS e ON (e.entry_id = a.entry_id)
JOIN qd_users_permission AS p ON (p.permit_id = a.permit_id)
WHERE u.user_id = :uID
I have this query:
SELECT
groups.name
categories.name,
categories.label
FROM
groups
JOIN
categories
ON
(categories.group1 = groups.id
OR
categories.group2 = groups.id)
AND
groups.label = :section
AND
categories.active = 1
Now, this is my JOIN using Zend_Db_Select but it gives me array error
$select->from($dao, array('groups.name', 'categories.name', 'categories.label'))
->join(array('categories', 'categories.group1 = groups.id OR categories.group2 = groups.id'))
->where('groups.label = ?', $group)
->where('categories.active = 1');
My error:
Exception information:
Message: Select query cannot join with
another table
Does anyone know what I did wrong?
UPDATE / SOLUTION:
I've found the solution thanx to Eran. I just post the solution here in case anyone else is stuck on a problem like this one. The solution is:
$db = Zend_Registry::get('db');
$dao = new Default_Model_Db_CategoryDao('db');
$select = $dao->select();
$select->setIntegrityCheck(false)
->from(array('c' => 'categories'), array('name', 'label'))
->join(array('g' => 'groups'), 'c.group1 = g.id OR c.group2 = g.id', 'g.label')
->where('g.label = ?', $group)
->where('c.active = 1');
return $dao->fetchAll($select);
You are using a Zend_Db_Table_Select object. Those by default have integrity check enabled and cannot select data that is outside of their table.
You can turn it off by adding -> setIntegrityCheck(false) to the select object before querying with it.
You can read more about it in the manual under Select API -> Advanced usage
Apologies for all this code, anyhow Im re-working a query into the Zend query way of working, this is what I have so far:
$db = Zend_Registry::get ( "db" );
$stmt = $db->query('
SELECT recipe_pictures.picture_id, recipe_pictures.picture_filename, course.course_name, cuisines.name, recipes.id, recipes.Title, recipes.Method, recipes.author, recipes.SmallDesc, recipes.user_id, recipes.cuisine, recipes.course, recipes.Created_at, recipes.vegetarian, recipes.Acknowledgements, recipes.Time, recipes.Amount, recipes.view_count, recipes.recent_ips, guardian_writers.G_item, guardian_writers.G_type
FROM recipes
LEFT JOIN course ON recipes.course = course.course_id
LEFT JOIN recipe_pictures ON recipes.id = recipe_pictures.recipe_id
LEFT JOIN cuisines ON recipes.cuisine = cuisines.id
LEFT JOIN guardian_writers ON recipes.author = guardian_writers.G_author
WHERE recipes.id = ?', $id);
$stmt->setFetchMode(Zend_Db::FETCH_ASSOC);
$recipes = $stmt->fetchAll();
return $recipes;
That one above works, trying to get the Zend version properly, my effort is below.
$db = Zend_Registry::get ( "db" );
$select = $db->select()
->from(array('r' => 'recipes'))
->join(array('c' => 'course'),
'r.course = c.course_id')
->join(array('rp' => 'recipe_pictures'),
'r.id = rp.recipe_id')
->join(array('cui' => 'cuisines'),
'r.cuisine = cui.id')
->join(array('gw' => 'guardian_writers'),
'r.author = gw.G_author')
->where(' id = ? ', $id);
$recipes = $db->fetchRow($select);
return $recipes;
If anyone can spot an error Id be very grateful, thanks
Use joinLeft instead of join to produce left joins.
To fetch specific columns from a table, rather than all (*) use this:
->from(array('r' => 'recipes'), array('id', 'title', 'method'))
or
->joinLeft(array('rp' => 'recipe_pictures'),
'r.id = rp.recipe_id',
array('picture_id', 'picture_filename')
)
To fetch no columns from a table, pass an empty array as the third parameter.
The join method provides an sql INNER JOIN. If you want to get a LEFT JOIN you should use joinLeft.