How to execute two mysql queries as one in PHP/MYSQL? - php

I have two queries, as following:
SELECT SQL_CALC_FOUND_ROWS Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;
SELECT FOUND_ROWS();
I want to execute both these queries in a single attempt.
$result = mysql_query($query);
But then tell me how I will handle each tables set separately. Actually in ASP.NET we uses dataset which handles two queries as
ds.Tables[0];
ds.Tables[1]; .. etc
How can I do the same using PHP/MYSQL?

Update: Apparently possible by passing a flag to mysql_connect(). See Executing multiple SQL queries in one statement with PHP Nevertheless, any current reader should avoid using the mysql_-class of functions and prefer PDO.
You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it.
For the record, it can be done using mysqli and the mysqli_multi_query-function.

As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.
For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:
$stmt = $dbh->prepare("
select sql_calc_found_rows * from foo limit 1 ;
select found_rows()");
$stmt->execute();
do {
while ($row = $stmt->fetch()) {
print_r($row);
}
} while ($stmt->nextRowset());
However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.

You'll have to use the MySQLi extension if you don't want to execute a query twice:
if (mysqli_multi_query($link, $query))
{
$result1 = mysqli_store_result($link);
$result2 = null;
if (mysqli_more_results($link))
{
mysqli_next_result($link);
$result2 = mysqli_store_result($link);
}
// do something with both result sets.
if ($result1)
mysqli_free_result($result1);
if ($result2)
mysqli_free_result($result2);
}

Using SQL_CALC_FOUND_ROWS you can't.
The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement.
As someone noted in your earlier question, using SQL_CALC_FOUND_ROWS is frequently slower than just getting a count.
Perhaps you'd be best off doing this as as subquery:
SELECT
(select count(*) from my_table WHERE Name LIKE '%prashant%')
as total_rows,
Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;

You have to use MySQLi, below code works well
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>

Like this:
$result1 = mysql_query($query1);
$result2 = mysql_query($query2);
// do something with the 2 result sets...
if ($result1)
mysql_free_result($result1);
if ($result2)
mysql_free_result($result2);

It says on the PHP site that multiple queries are NOT permitted (EDIT: This is only true for the mysql extension. mysqli and PDO allow multiple queries)
. So you can't do it in PHP, BUT, why can't you just execute that query in another mysql_query call, (like Jon's example)? It should still give you the correct result if you use the same connection. Also, mysql_num_rows may help also.

Yes it is possible without using MySQLi extension.
Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.
Refer to the comments below Husni's post for more information.

Related

PHP MySQL syntax error in script but statement works when typed directly into MySQL [duplicate]

I have two queries, as following:
SELECT SQL_CALC_FOUND_ROWS Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;
SELECT FOUND_ROWS();
I want to execute both these queries in a single attempt.
$result = mysql_query($query);
But then tell me how I will handle each tables set separately. Actually in ASP.NET we uses dataset which handles two queries as
ds.Tables[0];
ds.Tables[1]; .. etc
How can I do the same using PHP/MYSQL?
Update: Apparently possible by passing a flag to mysql_connect(). See Executing multiple SQL queries in one statement with PHP Nevertheless, any current reader should avoid using the mysql_-class of functions and prefer PDO.
You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it.
For the record, it can be done using mysqli and the mysqli_multi_query-function.
As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.
For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:
$stmt = $dbh->prepare("
select sql_calc_found_rows * from foo limit 1 ;
select found_rows()");
$stmt->execute();
do {
while ($row = $stmt->fetch()) {
print_r($row);
}
} while ($stmt->nextRowset());
However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.
You'll have to use the MySQLi extension if you don't want to execute a query twice:
if (mysqli_multi_query($link, $query))
{
$result1 = mysqli_store_result($link);
$result2 = null;
if (mysqli_more_results($link))
{
mysqli_next_result($link);
$result2 = mysqli_store_result($link);
}
// do something with both result sets.
if ($result1)
mysqli_free_result($result1);
if ($result2)
mysqli_free_result($result2);
}
Using SQL_CALC_FOUND_ROWS you can't.
The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement.
As someone noted in your earlier question, using SQL_CALC_FOUND_ROWS is frequently slower than just getting a count.
Perhaps you'd be best off doing this as as subquery:
SELECT
(select count(*) from my_table WHERE Name LIKE '%prashant%')
as total_rows,
Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;
You have to use MySQLi, below code works well
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
Like this:
$result1 = mysql_query($query1);
$result2 = mysql_query($query2);
// do something with the 2 result sets...
if ($result1)
mysql_free_result($result1);
if ($result2)
mysql_free_result($result2);
It says on the PHP site that multiple queries are NOT permitted (EDIT: This is only true for the mysql extension. mysqli and PDO allow multiple queries)
. So you can't do it in PHP, BUT, why can't you just execute that query in another mysql_query call, (like Jon's example)? It should still give you the correct result if you use the same connection. Also, mysql_num_rows may help also.
Yes it is possible without using MySQLi extension.
Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.
Refer to the comments below Husni's post for more information.

Query work in MySQL workbench but not in PHP [duplicate]

I have two queries, as following:
SELECT SQL_CALC_FOUND_ROWS Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;
SELECT FOUND_ROWS();
I want to execute both these queries in a single attempt.
$result = mysql_query($query);
But then tell me how I will handle each tables set separately. Actually in ASP.NET we uses dataset which handles two queries as
ds.Tables[0];
ds.Tables[1]; .. etc
How can I do the same using PHP/MYSQL?
Update: Apparently possible by passing a flag to mysql_connect(). See Executing multiple SQL queries in one statement with PHP Nevertheless, any current reader should avoid using the mysql_-class of functions and prefer PDO.
You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it.
For the record, it can be done using mysqli and the mysqli_multi_query-function.
As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.
For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:
$stmt = $dbh->prepare("
select sql_calc_found_rows * from foo limit 1 ;
select found_rows()");
$stmt->execute();
do {
while ($row = $stmt->fetch()) {
print_r($row);
}
} while ($stmt->nextRowset());
However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.
You'll have to use the MySQLi extension if you don't want to execute a query twice:
if (mysqli_multi_query($link, $query))
{
$result1 = mysqli_store_result($link);
$result2 = null;
if (mysqli_more_results($link))
{
mysqli_next_result($link);
$result2 = mysqli_store_result($link);
}
// do something with both result sets.
if ($result1)
mysqli_free_result($result1);
if ($result2)
mysqli_free_result($result2);
}
Using SQL_CALC_FOUND_ROWS you can't.
The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement.
As someone noted in your earlier question, using SQL_CALC_FOUND_ROWS is frequently slower than just getting a count.
Perhaps you'd be best off doing this as as subquery:
SELECT
(select count(*) from my_table WHERE Name LIKE '%prashant%')
as total_rows,
Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;
You have to use MySQLi, below code works well
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
Like this:
$result1 = mysql_query($query1);
$result2 = mysql_query($query2);
// do something with the 2 result sets...
if ($result1)
mysql_free_result($result1);
if ($result2)
mysql_free_result($result2);
It says on the PHP site that multiple queries are NOT permitted (EDIT: This is only true for the mysql extension. mysqli and PDO allow multiple queries)
. So you can't do it in PHP, BUT, why can't you just execute that query in another mysql_query call, (like Jon's example)? It should still give you the correct result if you use the same connection. Also, mysql_num_rows may help also.
Yes it is possible without using MySQLi extension.
Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.
Refer to the comments below Husni's post for more information.

Multiple SQL INSERT and UPDATE [duplicate]

I have two queries, as following:
SELECT SQL_CALC_FOUND_ROWS Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;
SELECT FOUND_ROWS();
I want to execute both these queries in a single attempt.
$result = mysql_query($query);
But then tell me how I will handle each tables set separately. Actually in ASP.NET we uses dataset which handles two queries as
ds.Tables[0];
ds.Tables[1]; .. etc
How can I do the same using PHP/MYSQL?
Update: Apparently possible by passing a flag to mysql_connect(). See Executing multiple SQL queries in one statement with PHP Nevertheless, any current reader should avoid using the mysql_-class of functions and prefer PDO.
You can't do that using the regular mysql-api in PHP. Just execute two queries. The second one will be so fast that it won't matter. This is a typical example of micro optimization. Don't worry about it.
For the record, it can be done using mysqli and the mysqli_multi_query-function.
As others have answered, the mysqli API can execute multi-queries with the msyqli_multi_query() function.
For what it's worth, PDO supports multi-query by default, and you can iterate over the multiple result sets of your multiple queries:
$stmt = $dbh->prepare("
select sql_calc_found_rows * from foo limit 1 ;
select found_rows()");
$stmt->execute();
do {
while ($row = $stmt->fetch()) {
print_r($row);
}
} while ($stmt->nextRowset());
However, multi-query is pretty widely considered a bad idea for security reasons. If you aren't careful about how you construct your query strings, you can actually get the exact type of SQL injection vulnerability shown in the classic "Little Bobby Tables" XKCD cartoon. When using an API that restrict you to single-query, that can't happen.
You'll have to use the MySQLi extension if you don't want to execute a query twice:
if (mysqli_multi_query($link, $query))
{
$result1 = mysqli_store_result($link);
$result2 = null;
if (mysqli_more_results($link))
{
mysqli_next_result($link);
$result2 = mysqli_store_result($link);
}
// do something with both result sets.
if ($result1)
mysqli_free_result($result1);
if ($result2)
mysqli_free_result($result2);
}
Using SQL_CALC_FOUND_ROWS you can't.
The row count available through FOUND_ROWS() is transient and not intended to be available past the statement following the SELECT SQL_CALC_FOUND_ROWS statement.
As someone noted in your earlier question, using SQL_CALC_FOUND_ROWS is frequently slower than just getting a count.
Perhaps you'd be best off doing this as as subquery:
SELECT
(select count(*) from my_table WHERE Name LIKE '%prashant%')
as total_rows,
Id, Name FROM my_table WHERE Name LIKE '%prashant%' LIMIT 0, 10;
You have to use MySQLi, below code works well
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
Like this:
$result1 = mysql_query($query1);
$result2 = mysql_query($query2);
// do something with the 2 result sets...
if ($result1)
mysql_free_result($result1);
if ($result2)
mysql_free_result($result2);
It says on the PHP site that multiple queries are NOT permitted (EDIT: This is only true for the mysql extension. mysqli and PDO allow multiple queries)
. So you can't do it in PHP, BUT, why can't you just execute that query in another mysql_query call, (like Jon's example)? It should still give you the correct result if you use the same connection. Also, mysql_num_rows may help also.
Yes it is possible without using MySQLi extension.
Simply use CLIENT_MULTI_STATEMENTS in mysql_connect's 5th argument.
Refer to the comments below Husni's post for more information.

Execute multiple MySQL queries

I have 2 sql queries to execute, but I want it to execute all or if error in one query then dont execute any. I'm using php. I used to use try and catch in .NET but I'm new to php.
Below is the code which i was trying to do:
function Registration($UserFirstname,$UserLastname){
$sql="INSERT INTO table1 (fieldname1,fieldname2) VALUES ('$UserFirstname','$UserLastname')";
$res=mysql_query($sql) or die(mysql_error());
$sql="INSERT INTO table2 (fieldname1,fieldname2) VALUES ('$UserFirstname','$UserLastname')";
$res=mysql_query($sql) or die(mysql_error());}
The problem you're probably facing with try...catch is that PHP has two different error handling mechanisms: error reporting and exceptions. You cannot catch exceptions unless the underlying code throws them and good old mysql_query() will trigger warnings rather than throwing exceptions. There're several workarounds but, if you are interested in writing good object-oriented code, I suggest you switch to PDO.
In any case, if you want to stick to good old MySQL library, your code should basically work:
$res=mysql_query($sql) or die(mysql_error());
The explanation:
mysql_query() returns FALSE if the query fails (e.g., you get a duplicate key)
The right side of the or expression will only execute if the left side is FALSE
die() aborts the script, thus preventing the next queries to be executed
However, I presume that you don't want to abort in the middle of nowhere. If we add some missing bits (such as proper SQL generation and code indentation) we get this:
function Registration($UserFirstname,$UserLastname){
$sql = sprintf("INSERT INTO table1 (fieldname1,fieldname2) VALUES ('%s','%s')";
mysql_real_escape_string($UserFirstname),
mysql_real_escape_string($UserLastname)
);
$res = mysql_query($sql);
if( !$res ){
return FALSE;
}
$sql = sprintf("INSERT INTO table2 (fieldname1,fieldname2) VALUES ('%s','%s')";
mysql_real_escape_string($UserFirstname),
mysql_real_escape_string($UserLastname)
);
$res = mysql_query($sql);
if( !$res ){
return FALSE;
}
return TRUE;
}
About transactions
Please note that you still need to use transactions if there's a chance that the second query fails. Transactions are not particularly difficult to use, the only requirements are:
Define the involved tables as InnoDB
Run a START TRANSACTION query on top of the function
Run a COMMIT query at the end of the function
You need to be using transactions. These allow you to wrap a set of queries in a block that says "Either all these queries execute successfully or none of them do". This means that no matter what happens in the transaction block, you can be sure that the integrity of your database has been maintained.
NOTE: Transactions don't work with MyISAM tables, you have to use InnoDB tables.
mysql_query ('BEGIN TRANSACTION;', $db);
mysql_query ("INSERT INTO sometable (some, columns) VALUES ($some, $values)", $db);
if ($errMsg = mysql_error ($db))
{
mysql_query ('ROLLBACK;', $db);
die ($errMsg);
}
mysql_query ("INSERT INTO someothertable (some, other, columns) VALUES ($some, $other, $values)", $db);
if ($errMsg = mysql_error ($db))
{
mysql_query ('ROLLBACK;', $db);
die ($errMsg);
}
mysql_query ('COMMIT', $db);
You can try to use mysqli_multi_query
Or you can change your DB schema to InnoDB..
For executing two queries as one, you have to use mysql extension, my below code works well
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>

separate statements in single MYSQL query

How do I separate statements in a single MYSQL query?
Is it a semicolon?
I don't think it matters but I am writing the statements to be invoked by PHP functions
Edit: the problem is that I didn't seem to understand the UPDATE syntax, that you can execute multiple fields with one UPDATE statement
Using the mysqli_ functions (docs), you can pass multiple queries in the same string using mysqli_multi_query (docs)
Example from the docs:
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT CURRENT_USER();";
$query .= 'UPDATE City SET name = "Boston" WHERE id = 5';
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
If you're using one PHP call to get data from or send data to the database, it won't work. The MySQL PHP drivers support execution of a query string, not a script. If you want to execute multiple commands with one call, check out stored procedures.
http://dev.mysql.com/doc/refman/5.0/en/stored-routines.html
I think you're trying to do this?
<?php
$query = "SELECT name, subject, message FROM contact;select name from contact;";
$result = mysql_query($query);
?>
It won't work because PHP doesn't know what query you are looking to execute. You can do the following though, but most likely you knew that:
<?php
$query = "SELECT name, subject, message FROM contact";
$query2 = "SELECT name, message FROM contact;select name from contact;";
$result = mysql_query($query);
$result2 = mysql_query($query2);
?>
Hope this helps,
Jeffrey Kevin Pry

Categories