How do I get the ID of an inserted row? - php

I have this following example query, which works - I CAN insert values into my MySQL table, which also includes an unique id column. I want to get the id from the inserted row, after I execute the query. However what I get is 0 every time ($gotId=0).
What am I doing wrong?
$stmt = $conn->prepare("INSERT INTO ....... ");
$stmt-> bind_param("ss", ....);
$stmt->execute();
$gotId = $conn->insert_id;
Full query:
$conn = $db->connect();
$stmt = $conn->prepare("INSERT INTO table(value1, value2) VALUES(?, ?)");
$stmt-> bind_param("ss", $value1, $value2);
$stmt->execute();
$gotId = $conn->insert_id;

After calling the execute() method on the PreparedStatement, the id of the insert row will be in the insert_id attribute Only read it.
$stmt->execute();
$gotId = $stmt->insert_id;
Taken from here

$query = "INSERT INTO .......";
$mysqli->query($query);
printf ("New Record has id %d.\n", $mysqli->insert_id);
More Info

Related

mysql prepared statments insert issue

I am having a weird problem with a insert statment. What's happening is that if I insert into only one column, it works but anything greater than 1 column doesn't get inserted and there are no errors displayed
This works
$db = mysqli new('localhost','root','','db');
$stmt = $db->prepare("insert into test (id) values(?)");
echo $db->error;
$stmt->bind_param("s",$id);
$stmt->execute();
But not this:
$id = 1;
$name = "test";
$stmt = $db->prepare("insert into test (id,name) values(?,?)");
echo $db->error;
$stmt->bind_param("ss",$id, $name);
$stmt->execute();
Does anyone have a clue? Not sure if this is helpful but some of the columns don't have a value under collation tab and others have latin1_swedish_ci in the table
Try to bind parameters separately, Like below:
$stmt = $db->prepare("insert into test (id,name) values(:id, :name)");
echo $db->error;
$stmt->bind_param(":id", $id);
$stmt->bind_param(":name", $name);
$stmt->execute();

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);

Why is this PHP while query not working?

I have this simple pre-sort database input thing, I've created this before, what I'm screwing up is the while aspect.
There are two different tables: a table that keeps track of keyword frequencies and a table for the entries themselves paired with the keyword.
What I'm doing is saving something by a keyword, I check if the keyword exists, if it does, I increment the count of that keyword and then proceed to add the entry to the entry database, if not I create a new entry of that keyword in the keyword table and set the count as 1, then add the entry to the entry database.
$query = "SELECT COUNT(*) FROM key WHERE key=?";
if($stmt = $link->prepare($query)){
$stmt->bind_param('s',$key);
$stmt->execute();
while ($row = $stmt->fetch_row()){
$count = $row[0];
}
// count comes out here
// echo $count;
if($count==0){
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// insert new key
$stmt = mysqli_prepare($link, "INSERT INTO key VALUES (?,?,?)");
$stmt->bind_param('isi',$id,$key,$numtimes);
$stmt->execute();
} else {
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// update key count
$stmt = mysqli_prepare($link, "UPDATE key SET numtimes=key+1 WHERE key=$key");
$stmt->bind_param('s',$key);
$stmt->execute();
}
}
<?php
$query = "SELECT COUNT(*) FROM key WHERE key=?";
if($stmt = $link->prepare($query)){
$stmt->bind_param('s', $key);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_row()){
$count = $row[0];
}
$stmt->close();
// count comes out here
// echo $count;
if($count == 0){
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss', $id, $poster, $key, $entry, $date);
$stmt->execute();
// insert new key
$stmt = mysqli_prepare($link, "INSERT INTO key VALUES (?,?,?)");
$stmt->bind_param('isi',$id,$key,$numtimes);
$stmt->execute();
$stmt->close();
} else {
// insert new entry
$stmt = mysqli_prepare($link, "INSERT INTO entry VALUES (?,?,?,?,?)");
$stmt->bind_param('issss',$id,$poster,$key,$entry,$date);
$stmt->execute();
// update key count
$stmt = mysqli_prepare($link, "UPDATE key SET numtimes=key+1 WHERE key=$key");
$stmt->bind_param('s',$key);
$stmt->execute();
$stmt->close();
}
}
?>
This should do the trick for you, you can't use fetch_row() directly on $stmt, that was your mistake.
There are two issues
first
while ($row = $stmt->fetch_row()){
$count = $row[0];
}
should be replaced by simply
$count = $stmt-rowCount()
You actually don't need the 'keys' table. Consider your DB schema again. The keys table is superfluous. The 'entry' table will suffice just update the entry table and you are good. All information can be obtained by querying the entry table rightly

Multiple prepared statements into many to many relationship table using last id

[Updated code from suggestions]
Currently I have two tables in my database. The second table is a junction table for multiple categories from each unique id from the first table. Nothing too special.
Need to accomplish:
I'd like to use two prepared statements where specifically the second statement gets the ID from the first and loops through. Here's what I've tried:
//set autocommit to off
$conn->autocommit(FALSE);
//first table
$stmt1 = $conn->prepare("INSERT INTO birds (db_category, db_class) VALUES (?, ?)");
$stmt1->bind_param('ss',$_POST['db_category'],$_POST['db_class']);
$stmt1->execute();
//get the inserted ID
$lastID = $stmt1->insert_id;
$stmt1->close();
//second table (many to many)
$stmt2 = $conn->prepare("INSERT INTO birdsBiome (birds_id, biomes_id) VALUES (?, ?)");
$arrayValue = $_POST['biomeCheck'];
foreach ($arrayValue as $arrayInsert) {
$stmt2->bind_param('ii', $lastID, $arrayInsert);
$stmt2->execute();
}
$stmt2->close();
//commit both statements
$conn->commit();
$conn->close();
You can access the last insert id as a property of the mysqli object:
$lastID = $conn->insert_id;
Or alternatively you don't have to store $lastID at all if you access it within your SQL:
$stmt2 = $conn->prepare("INSERT INTO birdsBiome (birds_id, biomes_id)
VALUES (LAST_INSERT_ID(), ?)");
By the way, in your code example above you didn't execute $stmt1, so there will be no last insert id anyway.

MySQL row inserted but not saved?

I am inserting a row into a MySQL table from PHP and running a query right after the insert to get the key value of the row that was just inserted like so:
$stmt = $this->db->prepare("INSERT INTO user(vFirstName, vLastName, vEmail, vPassword, iSkilllevelid, vTournaments, vDays, dAddedDate, eStatus) VALUES (?,?,?,?,4,'Pick-Up','Saturday',NOW(),'Active')");
$stmt->bind_param("ssss", $firstName, $lastName, $email, $pwd);
$stmt->execute();
$stmt->close();
$stmt = $this->db->prepare('SELECT iUserId FROM user WHERE vEmail=?');
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($iUserId);
while ($stmt->fetch()) {
break;
}
After this code executes, $iUserId has the correct auto incremented key value (1143 for instance), but when I actually look at the database table, the row with that key (1143) does not exist. How is that possible??
Instead of selecting from the table after insertion, you should use mysqli::$insert_id:
$stmt = $this->db->prepare('
INSERT INTO user
(vFirstName, vLastName, vEmail, vPassword, iSkilllevelid,
vTournaments, vDays, dAddedDate, eStatus)
VALUES
(?,?,?,?,4,"Pick-Up","Saturday",NOW(),"Active")
');
$stmt->bind_param('ssss', $firstName, $lastName, $email, $pwd);
$stmt->execute();
$iUserId = $this->db->insert_id;
$stmt->close();
As to why the inserted data is not appearing from other connections, it seems likely that your transaction has not been committed:
$this->db->commit();

Categories