Zend 2: How do I execute multiple SQL queries using Zend\Db\Adapter? - zend-framework

Im executing this query:
$query = "
Select * From table1 Where id = 1;
Select * From table2 Where name = 'test';
";
With \Zend\Db\Adapter\Adapter:
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
How can I access the second result?
$rawResult->next() only returns values from first query.

Use two different queries.
/*
* First Query
*/
$query = "
Select * From table1 Where id = 1
";
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
/*
* Second Query
*/
$query = "
Select * From table2 Where name = 'test'
";
$stmt = $this->dbAdapter->query($query);
$rawResult = $stmt->execute();
I don't believe it works the way you had it to where two queries in a row are sent this way.
To avoid code duplication you can wrap the duplicated code into a method.
$rawResult1 = $this->getResults("Select * From table1 Where id = 1");
$rawResult2 = $this->getResults("Select * From table2 Where name = 'test'");
function getResults(string $query)
{
$stmt = $this->dbAdapter->query($query);
return $stmt->execute();
}

Related

How to print mongodb or mongoose query like mysql?

Is there anything similar in mongodb? If we are using dynamic variables and print the query then it should print the query with the values in it like shown below.
int name = 'john';
int age = 23;
// how we do it in PHP
$query = 'select * from students where name='"name"' and age='"age"';
echo $query;
// result
select * from students where name='john' and age='23';
// how we do it in codeigniter
echo $this->db->last_query();
// result
select * from students where name='john' and age='23';

sqli sum of a column codes not working

I am trying to sum of a column of database table by the following cods, but it's not working:
$sqli = "SELECT sum(total_salary) AS totSalary FROM allsalary WHERE month_session = '$month_name' and org_session = '$org_name' and desig_session = '$desig_name' ORDER BY ID ASC ";
$stmt = $mysqli->prepare($sqli);
$stmt->execute();
$stmt->store_result();
$totl = $stmt->fetch();
$total_salary = $totl['totSalary'];
echo $total_salary;
But I could fetch the table correctly.
Now I want to sum the column named 'total_salary', I need a suggestion.....
You are missing two essential functions here, bind_param() and bind_result()
$sql = "SELECT sum(total_salary) FROM allsalary WHERE month_session = ?
and org_session = ? and desig_session = ? ORDER BY ID ASC";
$stmt = $mysqli->prepare($sql);
$sttmt->bind_paran("sss",$month_name,$org_name,$desig_name);
$stmt->execute();
$stmt->bind_result($total_salary);
$stmt->fetch();
echo $total_salary;

How to execute union query in zf2 where i m using tablegateway?

How to execute the following query
select * from table1 union select * from table2
in zend-framework2 where i am using tablegateway? In the documentation of zf2,they didn't give any details about union query.
Try -
$select1 = new Select('table1');
[.... rest of the code ....]
$select2 = new Select('table2');
[.... rest of the code ....]
$select1->combine($select2); //This will create the required SQL union statement.
To get count of the two tables you have to use a bit of SQL rather then tableGateway -
$sql = new Sql($this->tableGateway->adapter);
$select_string = $sql->getSqlStringForSqlObject($select1);
$sql_string = 'SELECT * FROM (' . $select_string . ') AS select_union';
$statement = $this->tableGateway->adapter->createStatement($sql_string);
$resultSet = $statement->execute();
$total_records = count($resultSet);
$resultSet gives data.
$total_records gives total no. of records.

Parametrized query inside mysqli class

I am using Mertol Kasanan's class for running parametrized queries -
http://liveplanet.googlecode.com/svn-history/r132/trunk/db/DB.php
I am very satisfied with the script except for some issues that I don't seem to put my finger on.
As it states in the brief tutorial in the class's description the method for running the query is:
$result = $db->query('SELECT * FROM `users` WHERE id = ? AND user_type = ? LIMIT ?',$id,$user_type,$limit);
Can anybody figure out how to run a query without defining any parameter as it seems that
$result = $db->query('SELECT * FROM `users` WHERE id = 'y' ");
neither
$result = $db->query('SELECT * FROM `users` WHERE id = 'y' ", '');
do not do the trick as it returns a binding error;
A workaround would be
$result = $db->query('SELECT * FROM `users` WHERE 1 = ? AND id = 'y' ", 1);
Is there a neater way to run my query?
I don't need parameters as the query gets it's values from a safe source inside a class.
Edit:
Let's say I have this:
if($HC == 'C'){
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat != 'D' GROUP BY pic LIMIT ?";
$query = $this->dbs->query($sql,$this->user,$this->user_head,4);
$results = $this->dbs->numRows($query);
if($results < 3){
$sql = "SELECT * FROM `photo` WHERE `user` = ?i AND `pic` != ?s ORDER BY id ASC LIMIT ?";
$query = $this->dbs->query($sql, $this->user,$this->user_head,4);
}
}else{
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat = ?s ORDER BY RAND() LIMIT ?";
$query = $this->dbs->query($sql,$this->user,$this->user_head,$HC,4);
$results = $this->dbs->numRows($query);
}
Now, in order to get the data from the right query I can either define $data->getAll under each query - but that would mean repeating my code or I could try extracting the data from the last defined $query result - which I do not know how to do.
I know that there may be a better way of doing this but I am trying to improve my coding style as I think the safemysql class would need some improvements even if that would mean a bit more documentation.
I could try using $db->getAll instead of $db->query but, as far as I know, I cannot use numRows on GetAll.
As a matter of fact, this class is totally unusable. And the problem you mentioned is a least one.
It seems that someone who wrote it, never used this class in a real life project.
So, if you want a class which works and works way better, go for SafeMysql, as it will do exactly what you want:
$data = $db->getAll("SELECT * FROM `users` WHERE status = 'y'");
(note that you've got your data already, without any further code)
Nevertheless, you have to understand that the following statement of yours
I don't need parameters as the query gets it's values from a safe source inside a class.
is wrong.
It's OK to use a hard-coded value as you wrote it, but if you were intended to use a "safe" variable - it ought to be added via placeholder. Otherwise your query remains error-prone and unsafe.
So, it have to be
$id = 1; // "safe" variable
$data = $db->getRow("SELECT * FROM `users` WHERE id = ?i", $id);
To answer edited question. Not sure if it's what you need, but here is the code. It wu
if($HC == 'C')
{
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat != 'D' GROUP BY pic LIMIT ?";
$data = $this->dbs->getAll($sql,$this->user,$this->user_head,4);
if (count($data) < 3) {
$sql = "SELECT * FROM `photo` WHERE `user` = ?i AND `pic` != ?s ORDER BY id ASC LIMIT ?";
$data = $this->dbs->query($sql, $this->user,$this->user_head,4);
}
} else {
$sql = "SELECT * FROM `photo_c` WHERE `user` = ?i AND `pic` != ?s AND cat = ?s ORDER BY RAND() LIMIT ?";
$data = $this->dbs->query($sql,$this->user,$this->user_head,$HC,4);
}

Zend_DB_Select : why are all fields returned?

public function getWorksheetData($id) {
/** create the following query using select object:
SELECT wc.label, wd.notes FROM worksheet_data wd
LEFT JOIN worksheet_columns wc ON wd.column_id = wc.id;
*/
$id = (int) $id;
$select = $this->_db->select()
->from(array('wd'=>'worksheet_data'),
array('wc.label','wd.notes'))
->join(array('wc'=>'worksheet_columns','wd.column_id = wc.id'))
->where("wd.id = :worksheet_id");
$results = $this->_db->fetchAll($select, array('worksheet_id' => $id),Zend_Db::FETCH_ASSOC);
return array('results'=>$results);
}
Why does this query become:
SELECT wc.label, wd.notes, wc.* FROM worksheet_data AS wd INNER JOIN worksheet_columns AS wc WHERE (wd.id = :worksheet_id)
and return wc.*?
You need to put an empty array as the third argument to the join method, also the join condition should not be part of the first argument's array, but as the second argument instead (you'll notice that there is not join condition in your query). Join needs at least the first two arguments, this is the method signature:
join(table, join, [columns])
Applying that to your join method:
->join(array('wc'=>'worksheet_columns'),'wd.column_id = wc.id', array())
so:
$select = $this->_db->select()
->from(array('wd'=>'worksheet_data'),
array('wc.label','wd.notes'))
->join(array('wc'=>'worksheet_columns'),'wd.column_id = wc.id', array())
->where("wd.id = :worksheet_id");
gives the output:
SELECT `wc`.`label`, `wd`.`notes` FROM `worksheet_data` AS `wd` INNER JOIN `worksheet_columns` AS `wc` ON wd.column_id = wc.id WHERE (wd.id = :worksheet_id)
The manual says:
To select no columns from a table, use
an empty array for the list of
columns.