php MySQL lastInsertID - php

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.

Related

php mysqli_multi_query() stops inserting after first query

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."')";

How will I get mysqli last insert id

How will i get the last insert id in mysql following code?
All variable are set.
Insertion works!
$Restconnection = mysqli_connect("host","user","passwd","db ");
$query3 = mysqli_query($Rconnection, $strSQL3);
$stmt = $conn->prepare("INSERT INTO table (name, email, password) VALUES(?,?,?)");
$stmt->bind_param("sss", $name, $email, $password);
$stmt->execute();
$last_id = $conn->insert_id;
echo "Last inserted ID is: " . $last_id;
print mysqli_insert_id($Restconnection);
http://php.net/manual/de/mysqli.insert-id.php
Use mysqli_insert_id($connection)
Use the following:
$last_insert_id = mysqli_insert_id($Restconnection);

How to avoid Query doubles INSERT into database?

Problem:
I have made a simple form that uses PHP to pass information to my database via a INSERT query. However, every time I run it, it tries to put the information in twice. How can I avoid this?
Explanation:
I first insert the answers, into my answers table, save the AnswerID as a variable. Then do the save with my question table and lastly I use the two saved variables containing the ID's into my question_answers table.
My code:
if (isset($_POST['textinput1']) && !empty($_POST['textinput1'])) {
$text1 = mysqli_real_escape_string($conn, $_POST['textinput1']);
$text2 = mysqli_real_escape_string($conn, $_POST['textinput2']);
$q_text = mysqli_real_escape_string($conn, $_POST['textarea']);
$stmt = $conn->prepare("INSERT INTO answers (Answer1Text, Answer2Text) VALUES (?, ?)");
$stmt->bind_param('ss', $text1, $text2);
$stmt->execute();
$answerid = $stmt->insert_id;
$stmt = $conn->prepare("INSERT INTO question (QuestionText) VALUES (?)");
$stmt->bind_param('s', $q_text);
$stmt->execute();
$questionid = $stmt->insert_id;
if ($stmt->execute()) {
$stmt = $conn->prepare("INSERT INTO question_answers (AnswerID, QuestionID) VALUES (?, ?)");
$stmt->bind_param('ss', $answerid, $questionid);
$stmt->execute();
echo "<h2>Dit spørgsmål er nu lagt op på siden!</h2>";
echo "<h3>Tusinde tak for din interesse for SMIL - Skodfri Århus.</h3>";
}
else
{
echo "ERROR: Could not able to execute . " . mysqli_error($conn);
}
}
// close connection
mysqli_close($conn);
?>
My tables of importance:
question: QuestionID(PK), QuestionText
answers: AnswerID(PK), Answer1Text, Answer2Text
question_answers: QuestionAnswerID(PK), QuestionID(FK), AnswerID(FK)
Ps. I prefer not to use composite unique constraint as a solution.
Also a side-question, should $stmt->insert_id variables be mysqli_real_escape_string?
Your problem is that you have executed the second query TWICE
if (isset($_POST['textinput1']) && !empty($_POST['textinput1'])) {
$text1 = mysqli_real_escape_string($conn, $_POST['textinput1']);
$text2 = mysqli_real_escape_string($conn, $_POST['textinput2']);
$q_text = mysqli_real_escape_string($conn, $_POST['textarea']);
$stmt = $conn->prepare("INSERT INTO answers (Answer1Text, Answer2Text) VALUES (?, ?)");
$stmt->bind_param('ss', $text1, $text2);
$stmt->execute();
$answerid = $stmt->insert_id;
$stmt = $conn->prepare("INSERT INTO question (QuestionText) VALUES (?)");
$stmt->bind_param('s', $q_text);
$stmt->execute();
$questionid = $stmt->insert_id;
// THIS IS THE SECOND EXECUTION OF QUERY 2
if ($stmt->execute()) {
$stmt = $conn->prepare("INSERT INTO question_answers (AnswerID, QuestionID) VALUES (?, ?)");
$stmt->bind_param('ss', $answerid, $questionid);
$stmt->execute();
echo "<h2>Dit spørgsmål er nu lagt op på siden!</h2>";
echo "<h3>Tusinde tak for din interesse for SMIL - Skodfri Århus.</h3>";
}
else
{
echo "ERROR: Could not able to execute . " . mysqli_error($conn);
}
}
// close connection
mysqli_close($conn);
?>
Instead try this as the IF test
//if ($stmt->execute()) {
if ( isset($answerid,$questionid) ) {
if ($stmt->execute()) {
this runs one of your statements a second time. You should assign the return value to a variable if you need it for something later.

mysqli_num_rows not working in MySQLi with PHP

I would like to check if there already exists a record before inserting a new one. But it doesn't work so far, here is the script:
<?php
session_start();
$uname = $_SESSION['username'];
$friend = $_GET["newfriend"];
$db = new mysqli("localhost", "...", "....", "...");
if($db->connect_errno > 0){
die("Unable to connect to database: " . $db->connect_error);
}
$checkexist = $db->query("SELECT * FROM friends WHERE (username_own='$uname', username='$friend')");
//create a prepared statement
$stmt = $db->prepare("INSERT INTO friends (`username_own`, `username`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $friend);
if ($checkexist->mysqli_num_rows == 0) {
//run the query to insert the row
$stmt->execute();
}
Try something like this:
<?php
/* Check if user exists */
$query = "SELECT count(1) FROM friends WHERE username_own=? AND username=?";
if($stmt = $db->prepare($query)){
$stmt->bind_param('ss', $uname, $friend);
$stmt->execute();
$stmt->bind_result($count_rows);
$stmt->fetch();
$stmt->close();
}else die("Failed to prepare");
/* If user doesn't exists, insert */
if($count_row == 0){
$query = "INSERT INTO friends (`username_own`, `username`) VALUES (?,?)";
if($stmt = $db->prepare($query)){
$stmt->bind_param('ss', $uname, $friend);
$stmt->execute();
$stmt->close();
}else die("Failed to prepare!");
}
Try this:
//create a prepared statement
$stmt = $db->prepare("INSERT INTO friends (`username_own`, `username`) VALUES (?,?)");
//bind the username and message
$stmt->bind_param('ss', $uname, $friend);
if ($checkexist->mysqli_num_rows == 0 || $checkexist->mysqli_num_rows <> 0) {
//run the query to insert the row
$stmt->execute();
}
$checkexist->mysqli_num_rows is wrong. It's just
$checkexist->num_rows
or you can use
mysqli_num_rows($checkexist)
Hope this helps.
Replace most of your code with a simple INSERT IGNORE ... or INSERT ... ON DUPLICATE KEY UPDATE ....
The latter lets you change columns if the record already exists (based on any PRIMARY or UNIQUE key(s)).

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

Categories