How to execute multiple mysql queries together in PHP? - php

I want to a select query and an insert query that I want to do them together using function(mysql_query),but it's not working.
I'm tying to do somthing like this:
$sql="select * from texts; insert into date ('time') values ('2012');";
mysql_query($sql);
is there any way to do it?

mysql_query() sends a unique query (multiple queries are not supported) .
That's the default behaviour.However there is a bypass for this.
However the result code of the first query alone will be given as output of mysql_query() if you do this.
You just have to pass flag 65536 as mysql_connect's 5th parameter . the flag is defined in MySQL Client flags.
#define CLIENT_MULTI_STATEMENTS 65536 /* Enable/disable multi-stmt support */
#define CLIENT_MULTI_RESULTS 131072 /* Enable/disable multi-results */
So edit your mysql_connect() code to match this:
mysql_connect($host, $username, $password, false, 65536);
Warning:
You will get the result of mysql_query($query) for the first query only in the given $query . You can try concatenating 131072 with 65536 for getting multiple results.
This will not work on PHP < 4.3.0
This will not work if sql.safe_mode is set as 1 in php.ini
Another alternative will be to use mysqli instead of mysql library. It supports $mysqli->multi_query() and gives output within an array for each query.

MySQL don't allow passing more than one select query in single statement.

None of the mysql api can deal with several queries simultaneously, even mysql consol utility parses your input and executes one query after another and php's mysql_query doesn't. You just can write your own function doing it or just put all queries in an array and execute mysql_query for each element in a loop.

You can use mysqli_multi_query function but with PHP mysqli extension. (I recommend you to use mysqli instead of mysql extension of PHP because it includes much more features & facilities)

mysql_query() sends a unique query
see mysql_query
for multiple query you can see mysqli

mysql_query() doesn't support multiple queries execution in normal way.
use something like below.
<?php
$str="query1;query2;"; // say $str="select * from texts; insert into date ('time') values ('2012');";
$query = explode(';',$str);
// Run the queries
foreach($query as $index => $sql)
{
$result = mysql_query($sql);
// Perform an additional operations here
}
?>

Related

Error: Commands out of sync; you can't run this command now

I new there are lots of answer as well as accepted answers related to this question but none of them solve my problem. Still I am getting this error.
Procedures:
CREATE PROCEDURE getAllProducts()
BEGIN
SELECT * FROM products;
END //
CREATE PROCEDURE getAllCategories()
BEGIN
SELECT * FROM category;
END //
Connection & calling:
$link = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db($database, $link) or die(mysql_error());
$allProducts = mysql_query("CALL getAllProducts");
while($row = mysql_fetch_array($allProducts)) { }
$allCategory = mysql_query("CALL getAllCategories");
while($row = mysql_fetch_array($allCategory)) { }
I've even called mysql_free_result($allProducts) before executing the next query. But nothing happens.
mysql_get_client_info() return mysqlnd 5.0.5-dev - 081106 - $Revision: 1.3.2.27 $
I found that the problem only arises if I run two queries.
As the MySQL-Documentation for 'Commands out of sync' points out:
[...] It can also happen if you try to execute two queries that return data
without calling mysql_use_result() or mysql_store_result() in between.
The Documentation for mysql_use_result() says e.g.:
After invoking mysql_query() or mysql_real_query(), you must call
mysql_store_result() or mysql_use_result() for every statement that
successfully produces a result set (SELECT, SHOW, DESCRIBE, EXPLAIN,
CHECK TABLE, and so forth). You must also call mysql_free_result()
after you are done with the result set.
Basically you need to tell your client what it should do with the result.
Well, usually this error occurs because there are still results pending from the query. There are mysqli_store_result and mysqli_free_result functions available. Since you are using mysql and mysql extension does not have such functions, you can try closing the connection after executing the first procedure and establishing the connection again to execute next procedure. Though this is not the perfect solution, but it will work in your case.
mysql_close($connection);
$connection = mysql_connect("localhost","username","password");
You can also try
mysql_free_result($allProducts);
Stored procedures always return an extra result set with errors/warnings information. As such, your stored procedures return multiple result sets (the actual result set from your select query and the extra errors/warnings result set). Calling mysql_fetch_array in a loop you only saturate one of them, leaving the other still pending, causing the error you see.
I don't know how to fix it with vanilla mysql_ library, with mysqli_ you can issue mysqli_multi_query, and then only use the first result set. See the example in the docs.
It's not a fix per se, but if you insist on staying with mysql_* functions, and assuming that you actually want to work with more complicated stored procedures (i.e. that the ones you supplied are just a simplified example) - you can change the stored procedures code to write the resultset into a temporary table (e.g. tmp_getAllProducts) instead of returning it, and then SELECT from it in your PHP.
This is what worked for me a while back when I was stuck with mysql_* and couldn't upgrade...
This is a known limitation of the mysql extension. You must either not use more than one stored procedure per connection or upgrade to mysqli.
https://bugs.php.net/bug.php?id=39727

Why can't I bind a value to this parameter when using PDO? [duplicate]

This question already has answers here:
Getting raw SQL query string from PDO prepared statements
(16 answers)
Closed 6 years ago.
In PHP, when accessing MySQL database with PDO with parametrized query, how can you check the final query (after having replaced all tokens)?
Is there a way to check what gets really executed by the database?
So I think I'll finally answer my own question in order to have a full solution for the record. But have to thank Ben James and Kailash Badu which provided the clues for this.
Short Answer
As mentioned by Ben James: NO.
The full SQL query does not exist on the PHP side, because the query-with-tokens and the parameters are sent separately to the database.
Only on the database side the full query exists.
Even trying to create a function to replace tokens on the PHP side would not guarantee the replacement process is the same as the SQL one (tricky stuff like token-type, bindValue vs bindParam, ...)
Workaround
This is where I elaborate on Kailash Badu's answer.
By logging all SQL queries, we can see what is really run on the server.
With mySQL, this can be done by updating the my.cnf (or my.ini in my case with Wamp server), and adding a line like:
log=[REPLACE_BY_PATH]/[REPLACE_BY_FILE_NAME]
Just do not run this in production!!!
You might be able to use PDOStatement->debugDumpParams. See the PHP documentation .
Using prepared statements with parametrised values is not simply another way to dynamically create a string of SQL. You create a prepared statement at the database, and then send the parameter values alone.
So what is probably sent to the database will be a PREPARE ..., then SET ... and finally EXECUTE ....
You won't be able to get some SQL string like SELECT * FROM ..., even if it would produce equivalent results, because no such query was ever actually sent to the database.
I check Query Log to see the exact query that was executed as prepared statement.
I initially avoided turning on logging to monitor PDO because I thought that it would be a hassle but it is not hard at all. You don't need to reboot MySQL (after 5.1.9):
Execute this SQL in phpMyAdmin or any other environment where you may have high db privileges:
SET GLOBAL general_log = 'ON';
In a terminal, tail your log file. Mine was here:
>sudo tail -f /usr/local/mysql/data/myMacComputerName.log
You can search for your mysql files with this terminal command:
>ps auxww|grep [m]ysqld
I found that PDO escapes everything, so you can't write
$dynamicField = 'userName';
$sql = "SELECT * FROM `example` WHERE `:field` = :value";
$this->statement = $this->db->prepare($sql);
$this->statement->bindValue(':field', $dynamicField);
$this->statement->bindValue(':value', 'mick');
$this->statement->execute();
Because it creates:
SELECT * FROM `example` WHERE `'userName'` = 'mick' ;
Which did not create an error, just an empty result. Instead I needed to use
$sql = "SELECT * FROM `example` WHERE `$dynamicField` = :value";
to get
SELECT * FROM `example` WHERE `userName` = 'mick' ;
When you are done execute:
SET GLOBAL general_log = 'OFF';
or else your logs will get huge.
What I did to print that actual query is a bit complicated but it works :)
In method that assigns variables to my statement I have another variable that looks a bit like this:
$this->fullStmt = str_replace($column, '\'' . str_replace('\'', '\\\'', $param) . '\'', $this->fullStmt);
Where:
$column is my token
$param is the actual value being assigned to token
$this->fullStmt is my print only statement with replaced tokens
What it does is a simply replace tokens with values when the real PDO assignment happens.
I hope I did not confuse you and at least pointed you in right direction.
The easiest way it can be done is by reading mysql execution log file and you can do that in runtime.
There is a nice explanation here:
How to show the last queries executed on MySQL?
I don't believe you can, though I hope that someone will prove me wrong.
I know you can print the query and its toString method will show you the sql without the replacements. That can be handy if you're building complex query strings, but it doesn't give you the full query with values.
I think easiest way to see final query text when you use pdo is to make special error and look error message. I don't know how to do that, but when i make sql error in yii framework that use pdo i could see query text

How to know if MySQL returns 0

When I run this query `
SELECT id FROM bckoff WHERE left
= 3;
`
in phpmyAdmin, I get the correct response
MySQL returned an empty result set
(i.e. zero rows).
However, when I run the same query through my PHP code using mysql_query('the above query').. then I get "Resource ID#5" or "Resource ID#6" and so on..
How do I get the empty result set (or zero rows) in PHP ?
mysql_num_rows is the answer. This function returns the number of rows affected by a executed query.
$query = "SELECT id FROM bckoff WHERE left = 3";
$result = mysql_query($query);
echo mysql_num_rows($result);
When you execute mysql_query($query) it executes the query and puts it in a resource. This resource can be read by different mysql-functions (like mysql_num_rows). For a complete overview of all MySQL functions have a look at http://nl.php.net/manual/en/ref.mysql.php
Note: Extension used in above code is deprecated as of PHP 5.5.0, Use MySQLi or PDO_MySQL extension.
So instead of mysql_num_rows use mysqli_num_rows()
You can use mysql_num_rows function as:
$result = mysql_query("SELECT id FROM bckoff WHERE left = 3");
$num_rows = mysql_num_rows($result);
// $num_rows will be 0.
You need to use a mysql_fetch_* function to retrieve the results. Look here
Mysql Fetch Functions
There is a mysql_num_rows function that you can call on the $result returned by mysql_query("SELECT ...").
You might look into the MySQLi extension instead. It's a big improvement over the MySQL driver, and allows you to use prepared statements and bind parameters among other things, and I find it much more comfortable to use. You can look at the examples on the documentation page for num_rows.

In PHP with PDO, how to check the final SQL parametrized query? [duplicate]

This question already has answers here:
Getting raw SQL query string from PDO prepared statements
(16 answers)
Closed 6 years ago.
In PHP, when accessing MySQL database with PDO with parametrized query, how can you check the final query (after having replaced all tokens)?
Is there a way to check what gets really executed by the database?
So I think I'll finally answer my own question in order to have a full solution for the record. But have to thank Ben James and Kailash Badu which provided the clues for this.
Short Answer
As mentioned by Ben James: NO.
The full SQL query does not exist on the PHP side, because the query-with-tokens and the parameters are sent separately to the database.
Only on the database side the full query exists.
Even trying to create a function to replace tokens on the PHP side would not guarantee the replacement process is the same as the SQL one (tricky stuff like token-type, bindValue vs bindParam, ...)
Workaround
This is where I elaborate on Kailash Badu's answer.
By logging all SQL queries, we can see what is really run on the server.
With mySQL, this can be done by updating the my.cnf (or my.ini in my case with Wamp server), and adding a line like:
log=[REPLACE_BY_PATH]/[REPLACE_BY_FILE_NAME]
Just do not run this in production!!!
You might be able to use PDOStatement->debugDumpParams. See the PHP documentation .
Using prepared statements with parametrised values is not simply another way to dynamically create a string of SQL. You create a prepared statement at the database, and then send the parameter values alone.
So what is probably sent to the database will be a PREPARE ..., then SET ... and finally EXECUTE ....
You won't be able to get some SQL string like SELECT * FROM ..., even if it would produce equivalent results, because no such query was ever actually sent to the database.
I check Query Log to see the exact query that was executed as prepared statement.
I initially avoided turning on logging to monitor PDO because I thought that it would be a hassle but it is not hard at all. You don't need to reboot MySQL (after 5.1.9):
Execute this SQL in phpMyAdmin or any other environment where you may have high db privileges:
SET GLOBAL general_log = 'ON';
In a terminal, tail your log file. Mine was here:
>sudo tail -f /usr/local/mysql/data/myMacComputerName.log
You can search for your mysql files with this terminal command:
>ps auxww|grep [m]ysqld
I found that PDO escapes everything, so you can't write
$dynamicField = 'userName';
$sql = "SELECT * FROM `example` WHERE `:field` = :value";
$this->statement = $this->db->prepare($sql);
$this->statement->bindValue(':field', $dynamicField);
$this->statement->bindValue(':value', 'mick');
$this->statement->execute();
Because it creates:
SELECT * FROM `example` WHERE `'userName'` = 'mick' ;
Which did not create an error, just an empty result. Instead I needed to use
$sql = "SELECT * FROM `example` WHERE `$dynamicField` = :value";
to get
SELECT * FROM `example` WHERE `userName` = 'mick' ;
When you are done execute:
SET GLOBAL general_log = 'OFF';
or else your logs will get huge.
What I did to print that actual query is a bit complicated but it works :)
In method that assigns variables to my statement I have another variable that looks a bit like this:
$this->fullStmt = str_replace($column, '\'' . str_replace('\'', '\\\'', $param) . '\'', $this->fullStmt);
Where:
$column is my token
$param is the actual value being assigned to token
$this->fullStmt is my print only statement with replaced tokens
What it does is a simply replace tokens with values when the real PDO assignment happens.
I hope I did not confuse you and at least pointed you in right direction.
The easiest way it can be done is by reading mysql execution log file and you can do that in runtime.
There is a nice explanation here:
How to show the last queries executed on MySQL?
I don't believe you can, though I hope that someone will prove me wrong.
I know you can print the query and its toString method will show you the sql without the replacements. That can be handy if you're building complex query strings, but it doesn't give you the full query with values.
I think easiest way to see final query text when you use pdo is to make special error and look error message. I don't know how to do that, but when i make sql error in yii framework that use pdo i could see query text

How to execute SELECT and INSERT in single query with PHP/MYSQL?

I have a table user_name with 3 fields, id, Name, Email (id is auto_increment field). I want to execute the following query in PHP, but its not returning any result.
INSERT INTO user_name (Name, Email) VALUES ('Example', 'example#xyz.com');
SELECT LAST_INSERT_ID() AS 'userid';
When I am executing the above query in PHP as below then its not returning anything.
$_SQL="INSERT INTO user_name (Name,Email) VALUES ('Example', 'example#xyz.com');
SELECT LAST_INSERT_ID() AS 'userid';";
$result_last_id = #mysql_query($_SQL);
$rs_insert = mysql_fetch_array($result_last_id);
$new_userid = $rs_insert['userid'];
Can anyone please tell me how to execute both queries into one.
Give a look to the mysql_insert_id() function.
mysql_query($insertStatementOnly);
$new_userid = mysql_insert_id();
It appears you don't need to execute multiple queries, but I included how to do it below. What you want is the last inserted id, which you get from mysql_insert_id.
To execute multiple queries
From comments on documentation of mysql_query:
The documentation claims that "multiple queries are not supported".
However, multiple queries seem to be supported. You just have to pass flag 65536 as mysql_connect's 5 parameter (client_flags). This value is defined in /usr/include/mysql/mysql_com.h:
#define CLIENT_MULTI_STATEMENTS (1UL << 16) /* Enable/disable multi-stmt support */
Executed with multiple queries at once, the mysql_query function will return a result only for the first query. The other queries will be executed as well, but you won't have a result for them.
Alternatively, have a look at the mysqli library, which has a multi_query method.
Simple answer really: You just can't do it.
http://php.net/mysql_query
May I also suggest you avoid the error-suppression operator '#' in mysql_query as you may not be made aware of any mysql errors. At the very least do
mysql_query($sql) or die("error: " . mysql_error()) ;
If you are using the Zend Framework with a PDO defined MySQL database, you would just use:
$database=Zend_Db::factory('PDO_MySQL',Array('hostname'=>'localhost','username'=>'x','password'=>'y','dbname'=>'z');
$connectionHandle=$database->getConnection();
$rowsInserted=$connectionHandle->insert('database_name','INSERT INTO x (a,b) VALUES (c,d)');
if ($rowsInserted>0) {
$autoIncrementValue=$connectionHandle->lastInsertId();
}
Yes You can using Shell command <BR>
mysql -user -p -h database -e '
SQL STATEMENT 1;
SQL STATEMENT 2;
SQL STATEMENT 3;
.......;
'
Php / MYSQL Programmer
this might do what u want:
insert into table1 (Name,Emails) values ('qqq','www');
select max(id) as lastinserted from table1;

Categories