Two mysqli queries

Two mysqli queries



Is it possible to have two mysqli_queries like so?:


mysqli_query($dblink, "INSERT INTO images (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName')") or die(mysql_error());
mysqli_query($dblink, "INSERT INTO images_history (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name, day, month, year) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName', '$day', '$month', '$year')") or die(mysql_error());



Basically I want to update two tables in my DB. Is there a better way to do this?






possible to run 2 queries, well of course it is.

– user557846
Jun 7 '12 at 0:25






You say it is possible but the above is not working. It is only inserting into images but not into images_history.

– PartisanEntity
Jun 7 '12 at 0:34






well maybe you should check the particular query for issues, its nothing to do with any other query.

– user557846
Jun 7 '12 at 0:36






@PartisanEntity You should change mysql_error() to mysqli_error() since the two are different and mysql_error() will not give you any message back when a mysqli query fails.

– drew010
Jun 7 '12 at 0:55


mysql_error()


mysqli_error()


mysql_error()


mysqli




2 Answers
2



It is possible with mysqli_multi_query().



Example:


<?php

$mysqli = new mysqli($host, $user, $password, $database);

// create string of queries separated by ;
$query = "INSERT INTO images (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName');";
$query .= "INSERT INTO images_history (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name, day, month, year) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName', '$day', '$month', '$year');";

// execute query - $result is false if the first query failed
$result = mysqli_multi_query($mysqli, $query);

if ($result)
do
// grab the result of the next query
if (($result = mysqli_store_result($mysqli)) === false && mysqli_error($mysqli) != '')
echo "Query failed: " . mysqli_error($mysqli);

while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
else
echo "First query failed..." . mysqli_error($mysqli);



The key is that you must use mysqli_multi_query if you want to execute more than one query in a single call. For security reasons, mysqli_query will not execute multiple queries to prevent SQL injections.


mysqli_multi_query


mysqli_query



Also keep in mind the behavior of mysqli_store_result. It returns FALSE if the query has no result set (which INSERT queries do not) so you must also check mysqli_error to see that it returns an empty string meaning the INSERT was successful.


mysqli_store_result


FALSE


INSERT


mysqli_error


INSERT



See:
mysqli_multi_query
mysqli_more_results
mysqli_next_result
mysqli_store_result






Perfect thanks so much, this is exactly the direction I would like to tak this.

– PartisanEntity
Jun 7 '12 at 0:57






I khow this is old, but to whoever still using mysqli_multi_query, as @dre010 explain: For security reasons, mysqli_query will not execute multiple queries to prevent SQL injections. So i think you should consider to separate your query into several individual query and use the prepared statement

– David
Nov 22 '15 at 2:35







I'm confused about this. I'm trying to adapt this so that I can say, 'if a string is found by searching the first table, return the results. If it is not found by searching the first table, and it is not found by searching the second table, then insert it into the second table.' So run the first SELECT statement, but only run the second if the first returns no results. Is there a way to differentiate between which SELECT statement you wish to use within the mysqli_multi_query?

– Joshua Flood
Jun 27 '16 at 13:06






@DjDaihatsu I would say don't over complicate the code and just write the two selects as separate queries and not use multi_select. Depending on your table structures or select lists, the way to differentiate would be to look at what rows were returned in the result and you'll know which statement it came from but that adds extra unnecessary logic that can be avoided if you just make two separate calls to mysqli_query.

– drew010
Jun 27 '16 at 15:31






Thanks @drew010 ! So it is acceptable to run multiple separate select statements on different tables within a database before closing a connection? I must have made another error somewhere in my code as I'm having trouble returning results from the second table (in the same database).

– Joshua Flood
Jun 28 '16 at 9:43



Once and for all! Use this function to get results of unlimited number of queries anywhere in your script.



Function:



You simply pass the output of the multi query to the function and it returns all results and errors found in each query.


function loop_multi($result)
//use the global variable $conn in this function
global $conn;
//an array to store results and return at the end
$returned = array("result"=>array(),"error"=>array());
//if first query doesn't return errors
if ($result)
//store results of first query in the $returned array
$returned["result"][0] = mysqli_store_result($conn);
//set a variable to loop and assign following results to the $returned array properly
$count = 0;
// start doing and keep trying until the while condition below is not met
do
//increase the loop count by one
$count++;
//go to the next result
mysqli_next_result($conn);
//get mysqli stored result for this query
$result = mysqli_store_result($conn);
//if this query in the loop doesn't return errors
if($result)
//store results of this query in the $returned array
$returned["result"][$count] = $result;
//if this query in the loop returns errors
else
//store errors of this query in the $returned array
$returned["error"][$count] = mysqli_error($conn);


// stop if this is false
while (mysqli_more_results($conn));
else
//if first query returns errors
$returned["error"][0] = mysqli_error($conn);

//return the $returned array
return $returned;



Usage:


$query = "INSERT INTO table1 (attribute1) VALUES ('value1');";
$query .= "INSERT INTO table2 (attribute2) VALUES ('value2');";
$query .= "SELECT * FROM table3;";

//execute query
$result = mysqli_multi_query($conn, $query);
//pass $result to the loop_multi function
$output = loop_multi($result);



Output



$output includes 2 arrays "result" and "error" ordered by query. For example, if you need to check if any errors have happened when executing the third query and fetch its result, you can do:


if(isset($output['error'][2]) && $output['error'][2] !== "")
echo $output['error'][2];
else
while($row = $output['result'][2]->fetch_assoc())
print_r($row);




Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)