Mysqli multi_query not executing all queries - php

I'm updating or inserting multiple rows in database tables using Mysqli and multi_query. They work fine when I use them on my local MAMP server but break down when I take them online. On the remote server only three of the four queries are performed...
Both environments have PHP and mysql version 5+ and include "PHP extension: mysqli". The only difference I see is the phpMyAdmin version. The remote server has 3.5.6, my local MAMP server has 4.2.5. Could this have an influence?
I'm of course changing passwords and all variables should be valid since they work locally.
I'm at a loss... Thanks!
$mysqli = new mysqli("localhost", "root", "root", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$sql = "INSERT INTO categories (id, name, descr) VALUES ('$id1', '$name1', '$descr1') ON DUPLICATE KEY UPDATE name='$name1', descr='$descr1';";
$sql.= "INSERT INTO categories (id, name, descr) VALUES ('$id2', '$name2', '$descr2') ON DUPLICATE KEY UPDATE name='$name2', descr='$descr2';";
$sql.= "INSERT INTO categories (id, name, descr) VALUES ('$id3', '$name3', '$descr3') ON DUPLICATE KEY UPDATE name='$name3', descr='$descr3';";
$sql.= "INSERT INTO categories (id, name, descr) VALUES ('$id4', '$name4', '$descr4') ON DUPLICATE KEY UPDATE name='$name4', descr='$descr4';";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}else{
echo("Succes.");
}
$mysqli->close()
UPDATE:
Replacing the queries with a single query does work but not very do-able in all scenarios and requires a lot of re-writing... Using hard-coded variables does not help.
$sql2 = "INSERT INTO categories (id, name, descr) VALUES ('$id1', '$name1', '$descr1'), ('$id2', '$name2', '$descr2'), ('$id3', '$name3', '$descr3'),('$id4', '$name4', '$descr4')
ON DUPLICATE KEY UPDATE name=VALUES(name), descr=VALUES(descr)";

Fixed the issue by using the 'Object oriented style' as shown on php.net. Still not sure why my previous approach only worked locally but okay, lets call it fixed.
/* 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();

Related

how to combine query for multiple able to save data

can it be combine into 1 query?
this is the query that im trying to combine? or is there a better way to relate these to table?
$insert_row = $mysqli->query("INSERT INTO orderlist
(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)
VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')");
$insert_row1 = $mysqli->query("INSERT INTO order
(BuyerName,BuyerEmail,TransactionID)
VALUES ('$buyerName','$buyerEmail','$transactionID')");
when i run these both only one query is functional, so what im trying to do is to make them both works.
im open to any suggestion
The reason why your second query isn't working is because of the use of order and not escaping it; it is a MySQL reserved word:
https://dev.mysql.com/doc/refman/5.5/en/keywords.html
Sidenote: ORDER is used when performing a SELECT... ORDER BY...
https://dev.mysql.com/doc/refman/5.0/en/select.html
Checking for errors would have shown you the syntax error such as:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax near 'order
http://php.net/manual/en/mysqli.error.php
Therefore, wrap it in ticks:
$insert_row1 = $mysqli->query("INSERT INTO `order` ...
or rename your table to something other than a reserved word, say orders for example.
If you wish to combine both queries, you can use multi_query()
http://php.net/manual/en/mysqli.quickstart.multiple-statement.php
Example from the manual:
<?php
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->query("DROP TABLE IF EXISTS test") || !$mysqli->query("CREATE TABLE test(id INT)")) {
echo "Table creation failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$sql = "SELECT COUNT(*) AS _num FROM test; ";
$sql.= "INSERT INTO test(id) VALUES (1); ";
$sql.= "SELECT COUNT(*) AS _num FROM test; ";
if (!$mysqli->multi_query($sql)) {
echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
?>
I also need to point out that your present code may be open to SQL injection since I do not know if you are escaping your data.
If not, then use prepared statements, or PDO with prepared statements, they're much safer.
try to add IF statement.
if ($insert_row = $mysqli->query("INSERT INTO orderlist(TransactionID,ItemName,ItemNumber, ItemAmount,ItemQTY)VALUES ('$transactionID','$itemname','$itemnumber', $ItemTotalPrice,'$itemqty')"));
{
$insert_row1 = $mysqli->query("INSERT INTO order (BuyerName,BuyerEmail,TransactionID) VALUES ('$buyerName','$buyerEmail','$transactionID')");
}

problems with processing my insert query in php

Hello i have a problem with my query ill keep getting errors from my query
this is my error;
Error: BEGIN; INSERT INTO our_work (id) VALUES ('6'); INSERT INTO
our_work_portf_img (portf_id, img_id) VALUES ('6', '7'); INSERT
INTO our_work_images (img_id, image) VALUES ('7', 'adawd.jpg');
COMMIT; You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 'INSERT INTO our_work (id) VALUES ('6'); INSERT INTO `our_wo'
at line 3
i've tried many things but i noticed one thing if i copy the $query string and i posted the query directly in mysql the problem will not accorded and it works just how i hoped it would.
Does anyone noticed the problem in my query cause im literal out of ideas.
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['submit_new_img'])){
$pjt_dtls = $_POST['project_details'];
$categories = $_POST['categories'];
$link = $_POST['link'];
$image_path = "adawd.jpg";//$_POST['file']; //$_POST['image'];
$row_id ='6';//++$num_rows['i'];
$image_id ='7'; //++$num_rows['ii'];
$sql = "
BEGIN;
INSERT INTO `our_work`
(`id`)
VALUES
('{$row_id}');
INSERT INTO `our_work_portf_img`
(`portf_id`, `img_id`)
VALUES
('{$row_id}', '{$image_id}');
INSERT INTO `our_work_images`
(`img_id`, `image`)
VALUES
('{$image_id}', '{$image_path}');
COMMIT;
";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
$conn->query($sql) does not work with multi-query like yours
you need to use multi_query instead
also here is nice comment:
Please note that there is no need for the semicolon after the last
query. That wasted more than hour of my time...

PHP Mysqli SELECT, INSERT and UPDATE from different databases

I am trying to select values from one DB. And insert and update the result into another. This is cronjob that needs to run everyday to replicate some data from one DB into another. I know I am missing steps / correct syntax, but I hope someone can help me out.
<?php
$con_1=mysqli_connect("host","user","pw","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$con_2=mysqli_connect("host","user","pw","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con_1,"SELECT id, name FROM table GROUP BY 1,2");
$mysqli->query($con_2, "INSERT INTO `table2`(`id`, `name`) VALUES ('".$result[1]."', ".$result[2].")
ON DUPLICATE KEY UPDATE name = ".$result[2]."");
}
mysqli_close($con_1);
mysqli_close($con_2);
?>
mysqli_query returns a query object, using $result[1] doesn't make sense, you need to fetch the rows in a loop:
while($row = $result->fetch_assoc()) {
// insert result in second database
}
For other access methods check the documentation.

Call Stored procedure (which returns two table) in php

I am working in a GUI tool development using php. There are STORED PROCEDURES already present in the database. Those stored procedures cannot be changed. (other tool dependency).
My Question: There is a procedure which returns two tables when called in mysql directly. (maybe 2 select statement inside it).
How can I use 'mysqli -- php' to display the data from two tables returned?
NOTE : Both table returned has same columns(name,id,status) in it
Make use of mysqli::use_result
$mysqli = new mysqli("localhost", "root", "password", "db_name");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ";
}
$query = "CALL sp_multiple results (?, ?)";
$stmt = $mysqli->prepare($query);
if (!$stmt) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
$stmt->bind_param("ss", $param1, $param2);
$stmt->execute();
/* get first result set */
if ($result1 = $mysqli->use_result()) {
//fetch data
$result1->close();
}
/* get second result set */
if ($result2 = $mysqli->use_result()) {
//fetch data
$result2->close();
}
$mysqli->close();

how to use insert values into database using php

$value2=$_POST['c_name'];
$value3=$_POST['c_vehicle_number'];
$value4=$_POST['c_phone'];
$value5=$_POST['c_email'];
these are the values stored in 1.php.
i want insert those values in 2.php.as below,
$sql="insert into customer_details(c_id,c_name,c_vehicle_number,c_phone,c_email) values ('','$value2','$value3','$value4','$value5')";
=====================================================
am using require('1.php');
which does not insert the values into the database.
what would be the soluton.?
In order to enter a values into the DB one must have a connection to the Database.
Create a connection to the relevant database.
Perform our desired query.
Example:
<?php
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO Persons (FirstName, LastName, Age)
VALUES
('$_POST[firstname]','$_POST[lastname]','$_POST[age]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
Explanation:
As you can see we first trying to retain a connection using mysqli_connect with the relevant DATABASE-ADDRESS, USERNAME, PASSWORDandDATABASE-NAME`
Than we're using mysqli_query to perform our query and we're passing it the connection we opened earlier + the query string we wish to perform.
More explanation could be found HERE
Important: This example isn't SQL-Injection protected, and it's highly important to you, to be protected against it. Read about it HERE
you can try this
$sql="INSERT into customer_details(c_id,c_name,c_vehicle_number,c_phone,c_email) VALUES ('".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."','".$_POST['value1']."')";
you worte :
('','$value2','$value3','$value4','$value5') you did mistake here
it can be write
('".$value2."','".$value3."','".$value4."','".$value5."')

Categories