简体   繁体   中英

How to fetch the result of a query in Zend

I need to get the avg score in a variable. I am using zend and I have tried two queries and none of them are working:

$avg_query = $db->query("SELECT sid, AVG(score) 
                         FROM markstable GROUP BY sid");

$avg_query = $db->query("SELECT sid, AVG(score) 
                         FROM markstable WHERE sid = '$sid'");

$avg_score = $db->fetchAll($avg_query);
echo $avg_score; gives nothing
echo $avg_score['$sid']; gives nothing

I need to store the avg_score in some other table.

You can use this to fetch avg grouped by sid.

$avg_score = $db->fetchAll("SELECT sid,AVG(score) FROM st GROUP BY sid");

foreach($avg_score as $row) {
    echo $row["sid"]."  ".$row["AVG(score)"];
}

In case of second query :

$avg_score = $db->fetchRow("SELECT sid,AVG(score) FROM st where sid=1");
echo $avg_score["AVG(score)"];

Try fetchPairs() instead of fetchAll()

Edit: Zend_Db does have a fetchPairs();

http://framework.zend.com/manual/1.12/en/zend.db.adapter.html#zend.db.adapter.select.fetchpairs

Also remove quotes from round the variable in the array index

echo $avg_score[$sid];

You mixed syntax in your attempt to query the DB.

The query() method builds and executes the desired query. Your first query should return the result, no need to provide any further code:

$avg_query = $db->query("SELECT sid, AVG(score) FROM markstable GROUP BY sid");
Zend_debug::dump($avg_query);//same as var_dump but already includes <pre> tags

your second query needs to include any bound values in an array as the second argument:

$avg_query = $db->query("SELECT sid, AVG(score) FROM markstable WHERE sid = ?", array($sid);
Zend_debug::dump($avg_query);//same as var_dump but already includes <pre> tags

you can also execute this query using a standard fetch method, just pass in the SQL as a string:

$avg_score = $db->fetchAll("SELECT sid, AVG(score) FROM markstable GROUP BY sid");
Zend_debug::dump($avg_score);//same as var_dump but already includes <pre> tags

when dealing with Zend_Db components you may as well get used to using placeholders in your queries ( ? ) as the old style syntax has been deprecated in many of the components.

This is probably not the best solution to what you're doing. It does however answer your question. There are a rather large number of ways to interact with a database in Zend Framework and using Zend_Db_Adapter components and methods are typically not the best way to accomplish the task.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM