php mysqli_multi_query() stops inserting after first query - php

I'm trying to insert multiple rows into the same table using a mysqli_multi_query function, but it only executes the first query. I have tried adding the values to the end of the first query separated by a comma as well, but nothing seems to work. Any suggestions?
I've switched to prepared statements but still only the first result is inserted. Am I missing something?
$DBConnect = mysqli_connect("localhost", "root", "", "getpressed");
if ($DBConnect->connect_error) {
die("Connection failed: " . $DBConnect->connect_error);
}
$stmt = $DBConnect->prepare("INSERT INTO orderdetails (orderID, productID, quantity) VALUES (?, ?, ?)");
$stmt->bind_param("iii", $orderID, $productID, $quantity);
$orderID = $orderID;
$productID = 1;
$quantity = $sportShirtQuantity;
$stmt->execute();
$orderID = $orderID;
$productID = 2;
$quantity = $sportCoatQuantity;
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$DBConnect->close();

I had a primary key index on orderID that wouldn't allow me to insert multiple rows with the same orderID. I'm an idiot. Thank you all for your help. It does work much better with prepared statements as suggested by tadman.

I changed your code a bit
$mysqli = new mysqli("localhost", "root", "", "getpressed");
if ($mysqli->connect_errno) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql = "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 1, '".$sportShirtQuantity."');";
$sql .= "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 2, '".$sportCoatQuantity."');";
if ($mysqli->multi_query($sql))) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
}
do {
if ($res = $mysqli->store_result()) {
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->free();
}
} while ($mysqli->more_results() && $mysqli->next_result());
I also highly recommend you to use PDO prepared statements in future.

Remove the semicolon off of the last statement. The documentation notes that the semicolon for this method is used to concatenate statements, not end them.
Read the documentation here: Link
$sql = "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 1, '".$sportShirtQuantity."');";
$sql .= "INSERT INTO orderdetails (orderID, productID, quantity) VALUES ('".$orderID."', 2, '".$sportCoatQuantity."')";

Related

PHP/mySQL: INSERT INTO is not posting the correct values

I try to insert some values from a form into my database with this code:
<?php
$link = mysqli_connect("myHost", "myUsername", "myPW", "myDB");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$name1 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn1']);
$name2 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn2']);
$name3 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn3']);
$name4 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn4']);
$name5 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn5']);
$name6 = mysqli_real_escape_string($link, $_REQUEST['plannercolumn6']);
// attempt insert query execution
$sql = "INSERT INTO anmeldungen (FR_PM) VALUES ('$name1')";
$sql = "INSERT INTO anmeldungen (SA_AM) VALUES ('$name2')";
$sql = "INSERT INTO anmeldungen (SA_PM) VALUES ('$name3')";
$sql = "INSERT INTO anmeldungen (SO_AM) VALUES ('$name4')";
$sql = "INSERT INTO anmeldungen (SO_PM) VALUES ('$name5')";
$sql = "INSERT INTO anmeldungen (MO_AM) VALUES ('$name6')";
if(mysqli_query($link, $sql)){
echo "Name ", $name1, " erfolgreich eingetragen. Wir freuen uns auf dich!";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
When I submit the form, it's creating a new row, but it's not inserting any values in all of the columns, but the column MO_AM. Is there a fault in my PHP?
Your query should look like:
$sql = "INSERT INTO anmeldungen
(FR_PM,SA_AM,SA_PM,SO_AM,SO_PM,MO_AM)
VALUES ('$name1','$name2','$name3','$name3','$name4','$name5','$name6')";
Are you sure that the $name variables have values?
Your SQL Query should be:
$sql = "INSERT INTO `anmeldungen`(`FR_PM`,`SA_AM`,`SA_PM`,`SO_AM`,`SO_PM`,`MO_AM`)
VALUES ('$name1','$name2','$name3','$name4','$name5','$name6')";
Though you shouldn't be using $variable as the insert you should look to binding these to prevent SQL Injections.
What you did just overwrite the query.You can insert multiple values into the same table.
Change your query:-
EDIT:
If you use multiple lines for the query it should look like this.
Also When you append the variable.
$sql = 'INSERT INTO anmeldungen (FR_PM,SA_AM,SA_PM,...)'
.' VALUES ('.$name1.','.$name2.','. .... .)'
;

How to get the last inserted id in PHP

Here I am trying to get the inserted id from MySQL database in the table I have product_id. After insert I want to get the latest inserted product_id and store it in array ['newid'][]
The insert query is going on pretty good, but I am not able to get the product_id in to the array. when I print the array I am getting NULL value.
$link = mysqli_connect(db_host,db_user,db_password,db_name);
if (condition) {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category,product_publish_status) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category','$approve')";
} else {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category')";
}
if(mysqli_query($link, $sqlin)){
$newisid = mysqli_insert_id($link);
$_SESSION['newid'][] = $newisid;
How can I solve this?
php.net : $mysqli->insert_id
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCity LIKE City");
$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
Try using mysql_insert_id() to get previously inserted id.
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);//previously insert id here.
} else {
//error
}
See this and this
EDIT
You can also use LAST_INSERT_ID() for this. Check official mysql doc
Try this:
$link = mysqli_connect(db_host,db_user,db_password,db_name);
if (condition) {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category,product_publish_status) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category','$approve')";
} else {
$sqlin = "INSERT INTO product_list (product_name, product_category, product_price,product_description,product_sharing_basis,product_co_owners,walden_product_price,product_referrence_URL,product_proposed_user_id,product_image_url,product_refurbish_factor,product_insurance_factor,product_life,product_size_category) VALUES ('$product_name', '$product_category', '$product_price', '$product_description', '$share_basis', '$co_owners', '$walden_product_price', '$pro_url', '$proposed_by','files/uploaded_images/".$_FILES['file']['name']."', '$refurbishment_factor', '$insurance_factor', '$product_life', '$size_category')";
}
if($link->query($sqlin)){
$newisid = $link->insert_id;
$_SESSION['newid'][] = $newisid;
}
Reference: http://php.net/manual/en/mysqli.insert-id.php

php MySQL lastInsertID

does anybody know why i get return value of 0 with this code:
/* check connection */
if (mysqli_connect_errno()) {
error_log("Connect failed: " . mysqli_connect_error());
echo '{"success":0,"error_message":"' . mysqli_connect_error() . '"}';
} else {
$stmt = $mysqli->prepare("INSERT INTO teams (name, token) VALUES (?, ?)");
$stmt->bind_param('ss', $team, $token);
/* execute prepared statement */
$stmt->execute();
if ($stmt->error) {error_log("Error: " . $stmt->error); }
$success = $stmt->affected_rows;
//Get the last insert ID of the insert Team
$lastInsertID = $stmt->insert_id;
//Insert into the Mapping Table
$stmt = $mysqli->prepare("INSERT INTO usersTeamsMap (users_idUser, teams_idTeam) VALUES (?, ?)");
$stmt->bind_param('ii', $userID , $lastInsertID );
/* execute prepared statement */
$stmt->execute();
//Get the last insert ID of the insert Team
$lastInsertID = $stmt->insert_id;
echo "ID: " . $lastInsertID;
The last echo always returns 0. The first " $lastInsertID = $stmt->insert_id;" of the first Insert into query works fine.
Thanks in advance.
EDIT:
Thanks for all answers. Now i know why the service didnt work. My mapping table did not have an AutoIncrement field.
insert_id is an attribute of the mysqli object, not of the statement! It is connection specific.
So it should be $mysqli->insert_id.

how to insert in to database using prepared statments in php

hello i am a java developer but new to php here i am trying to insert data in to the database using prepared statements as mentioned in here http://www.php.net/manual/en/pdo.prepared-statements.php but i am getting an error may i know what sort of error is this and any help to resolve this.
Error: Fatal error: Call to undefined method mysqli_stmt::bindParam() in G:****\xampp\htdocs****\registrationControl.php on line 17
<?php
$con = new mysqli("127.0.0.1", "root", "", "ksbka");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['username_first']);
$username_email = mysqli_real_escape_string($con, $_POST['username_email']);
$username_tele = mysqli_real_escape_string($con, $_POST['username_tele']);
echo $firstname."#####".$username_email;
$query="INSERT INTO instructorregistration (Id, Name, email, telephone) VALUES (?, ?, ?, ?)";
$pst = $con->prepare($query);
$pst->bindParam(1, "");
$pst->bindParam(2, $firstname);
$pst->bindParam(3, $username_email);
$pst->bindParam(4, $username_tele);
$pst->execute();
if (!mysqli_query($con,$pst)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
?>
I think if you want to use bindParam() method, the value should be an instance of PDOStatement .
The doc you see as bellow:
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (:name, :value)");
$stmt->bindParam(':name', $name);
$dbh is a PDO instance, I think, NOT mysqli instance. Because there is no mysqli::bindParam().
To solve this problem, you can:
use PDO class instead of Mysqli
create the query as the simplest way:
$query="INSERT INTO instructorregistration (Id, Name, email, telephone) VALUES (NULL, $firstname, $username_email, $username_tele)";
you have to use the mysqli methods, when you use mysqli
$stmt = $con->prepare($query);
$stmt->bind_param(1, "");
...
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
/* explicit close recommended */
$stmt->close();
/* Non-prepared statement */
$res = $mysqli->query("SELECT id FROM test");
var_dump($res->fetch_all());
edit: added some code from the official documentation

PHP process page does not work

Hi guys my process page does not work, my code is
<?php
$id = $_POST['item_id'];
$qty = $_POST['item_qty'];
$name = $_POST['item_name'];
$con = mysqli_connect ("localhost", "name", "password", "db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "INSERT INTO Temp (id, qty, name)
VALUES
('$_POST[id]', '$_POST[qty]', '$_POST[name]')";
if (!mysqli_query($con, $sql))
{
die('Error: ' . mysqli_error());
}
header('Location: http://url.com/');
mysqli_close($con);
?>
Should be all correct, just copy from w3school,
The problem is, the db only get 0,
ie. my $id is 4, $qty is 12, $name is "Hello", after the process page, the table only get two 0s in id and qty, name is void.
The values should be processed to this process page successfully, bc I have tried
echo $id, $qty, $name;
All are the same as I typed in before.
Could anyone help me? thanks :-)
this line:
INSERT INTO Temp (id, qty, name) VALUES ('$_POST[id]', '$_POST[qty]', '$_POST[name]')";
should be:
INSERT INTO Temp (id, qty, name) VALUES ('$id', '$qty', '$name')";
If the form is from your previous question, you dont need:
$id = $_POST['item_id'];
$qty = $_POST['item_qty'];
$name = $_POST['item_name'];
I agree it looks like you left out item_. You might want to sanitize your data first.
$id=mysqli_real_escape_string($_POST['item_id']);
$qty=mysqli_real_escape_string($_POST['item_qty']);
$name=mysqli_real_escape_string($_POST['item_name']);
$sql = "INSERT INTO Temp (id, qty, name)
VALUES ('$id', '$qty', '$name')";

Categories