简体   繁体   中英

How to combine two mySQL INSERT queries into one?

is there any way to combine two INSERT queries into one query ?

Thank you

    mysql_query("INSERT into `new_table` (`hash`,`first_visit`, `country`, `browser`) values ('$hash',CURDATE(), '$details->geoplugin_countryCode','$_SERVER[HTTP_USER_AGENT]')");
    mysql_query("INSERT into `behaviour` (`hash`,`page`,`url`,`entry`, `ref`) values ('$hash','$page','$url','$entry', '$ref')");

According to the documentation "mysql_query() sends a unique query (multiple queries are not supported) to the currently active database on the server that's associated with the specified link_identifier." So, no you can't combine those inserts.

But you could use multi_query and do something like this:

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$hash  = "foo" ; 
$page = "bar" ;
$url =  "baz" ;
$entry = "something" 
$ref  = "silly" ; 


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO newtable (hash, first_visit, country, browser)
VALUES ('$hash',CURDATE(), '$details>geoplugin_countryCode','$_SERVER[HTTP_USER_AGENT]');";
$sql .= "INSERT INTO behaviour (hash, page, url, entry, ref)
VALUES ( $hash, $page, $url, $entry, $ref);";

if ($conn->multi_query($sql) === TRUE) {
    echo "New records created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>
mysql_query("
    INSERT into `new_table` (`hash`,`first_visit`, `country`, `browser`) values ('$hash',CURDATE(), '$details->geoplugin_countryCode','$_SERVER[HTTP_USER_AGENT]');
    INSERT into `behaviour` (`hash`,`page`,`url`,`entry`, `ref`) values ('$hash','$page','$url','$entry', '$ref')
");

Just add ; after statement

Edit: Still 2 DB queries, but send in 1 request

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