i'm working on php and i want insert something in my sql data-base and get the row's inserted primary key in the same time so i've done something like this to insert
$SQL = "INSERT INTO `saisie` (`sid`, `reference`) VALUES (NULL,?)";
$set = $db->prepare($SQL);
$result = $set->execute(array($refCode));
but i don't know what to do to get the sid of that inserted row
you could use this to get the last inserted ID
$id = mysqli_insert_id($db); or
$id = $db->mysqli_insert_id(); or
$id = $db->lastInsertId();
Related
I have a query which I would like to INSERT some data into my table however, if there is already data inside of a particular field checkPoint, then run an UPDATE. After a lot of research on here, users have suggested using ON DUPLICATE KEY.
This query works however as apposed to updating an already existing row, it inserts a new one, with a new primary key, please can someone explain where I have gone wrong, or what I've missed out.
<?php
$idUsers = $_SESSION['id'];
$ModuleID = 5;
$checkPoint = 999;
$query= "INSERT INTO `userTakingModule` (`userTakingModuleID`, `idUsers`, `ModuleID`, `checkPoint`) VALUES (NULL, $idUsers, $ModuleID, $checkPoint) ON DUPLICATE KEY UPDATE `idUsers` = VALUES ($idUsers), `ModuleID` = VALUES ($ModuleID), `checkPoint` = VALUES ($checkPoint) ";
$result = $conn -> query($query);
?>
Screenshot of my database layout: the table called userTakingModule in the middle is where the query is applied to.
This is what is happening at the moment as I need to include the Primary Key of userTakingModuleID into the query somehow. (I almost need to say, look for where there is an already existing entry of the same idUser and ModuleID?)
The important part of using INSERT...ON DUPLICATE KEY UPDATE is telling MySQL what the key is, so it can look for duplicates. You said:
I almost need to say, look for where there is an already existing entry of the same idUser and ModuleID
And that's exactly right. You need to create a UNIQUE index on those two columns like so:
ALTER TABLE userTakingModule ADD UNIQUE INDEX(idUser, ModuleID);
Now, conflicts will trigger the update functionality. You should just remove the userTakingModuleID column from your query altogether, it will be given a value automatically as needed. You're also mis-using the VALUES function; you should pass it a column name, and it will resolve to the value that would have been inserted into that column without a conflict. So you can use either the VALUES function, or the variable itself.
And speaking of variables, I would be remiss if I didn't point out how insecure and dangerous it is to insert variables directly into queries. You should always use prepared statements. You don't provide enough code to know which database API you're using, but for PDO it would look like this:
$idUsers = $_SESSION['id'];
$ModuleID = 5;
$checkPoint = 999;
$query= "INSERT INTO userTakingModule (idUsers, ModuleID, checkPoint) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE idUsers = VALUES (idUsers), ModuleID = VALUES (ModuleID), checkPoint = VALUES (checkPoint)";
$stmt = $conn->prepare($query);
$stmt->execute([$idUsers, $ModuleID, $checkPoint]);
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
And for mysqli something like this (though I'm not too familiar with it)
$idUsers = $_SESSION['id'];
$ModuleID = 5;
$checkPoint = 999;
$query= "INSERT INTO userTakingModule (idUsers, ModuleID, checkPoint) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE idUsers = VALUES (idUsers), ModuleID = VALUES (ModuleID), checkPoint = VALUES (checkPoint)";
$stmt = $conn->prepare($query);
$stmt->bind_param("iii", $idUsers, $ModuleID, $checkPoint);
$stmt->execute();
$result = $stmt->get_result();
I'm sorry about my PHP skills, but I'm just not figuring out how to do this simple task which is INSERT a new row and save its ID into a variable.
Here's what I got:
// mysql inserting a new row
$sql = "INSERT INTO `order` (orderTitle, orderDescription, orderPrice,userID, categoryID)
VALUES('$title', '$description','$price','$userID','$category');";
$sql .= "SELECT LAST_INSERT_ID();";
$result = mysqli_multi_query($con,$sql);
$result_get_id= mysqli_next_result($con);
$row = mysqli_fetch_row($result_get_id);
$order_id = $row[0]; // <-- how to get this value??
I realized row[0] doesn't work, which is why I would like to know how to extract the LAST_INSERT_ID() value correctly.
A couple of things here...
Don't use mysqli_multi_query - it's unnecessary in your example. Use mysqli_query on the INSERT only. No need to query last insert id in SQL.
To get the last insert id, call mysqli_insert_id directly after your INSERT query. You can assign this to a variable, such as $order_id = mysqli_insert_id();
The database class you're using has built in functions for this e.g. mysqli_insert_id(), or for PDO $db->lastInsertId().
$mysqli->query("INSERT INTO order ... ");
printf ("Primary key of new record: %d.\n", $mysqli->insert_id);
http://php.net/manual/en/mysqli.insert-id.php
I'm very new to PHP, trying to figure things out.
I have the following php code:
$read_more = '[read more]';
$sql = "INSERT INTO database (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
The code is returning "http://www.example.com/index.php?id=0". Note that the "id" parameter is returning "0". My goal is to make it return the latest ID from the database, which is set to auto increment.
I've tried many things but nothing worked for me so far. Thanks!
EDIT: After hours of trial and error, this is how I was able to solve this problem:
//After connecting to the database
$sql = "INSERT INTO table (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
$result = mysqli_query($conn, $sql);
$id = mysqli_insert_id($conn);
Now the latest id is saved into a variable that I can use.
Try something like this instead. Check the documentation here.
// insert a datarow, primary key is auto_increment
// value is a unique key
$query = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query );
echo 'LAST_INSERT_ID: ',
mysql_query( "SELECT LAST_INSERT_ID()" ),
'<br>mysql_insert_id: ',
mysql_insert_id();
I have a code
$hasil = "INSERT INTO pendaftaran VALUES ('$no_ai','$tgl_daftar','$kode_dokter','$kode_pasien','$petugas_jaga','$bayar','$status_ambil','$catatan')";
$sql = mysql_query($hasil);
foreach($_POST['cek'] as $selected){
foreach($_POST['cek'] as $selek){
$res = mysql_query("SELECT kode_cek FROM master_cek where kode_item='$selected'");
while($koko=mysql_fetch_array($res)){
print_r($koko);
$result = "INSERT INTO detail_daftar VALUES ('',$no_ai','$res','0','','','$selected')";
$sql = mysql_query($result);
print_r($result);
}
}
}
The Result is..
Resource id #5 INSERT INTO detail_daftar VALUES ('',20150206015','Resource id #5','0','','','1011')Resource id #5INSERT INTO detail_daftar VALUES ('',20150206015','Resource id #5','0','','','1011')Resource id #5INSERT INTO detail_daftar VALUES ('',20150206015','Resource id #5','0','','','1011')
I am very confused with the resource id. Please help me thank you :)
It because when query is executed using PHP MySql driver it gives you resource id from where you need to fetch actual result.
If you need to get last insert id then you will have to make one more function call
print_r(mysql_insert_id());
foreach($_POST['cek'] as $selected){
foreach($_POST['cek'] as $selek){
$res = mysql_query("SELECT kode_cek FROM master_cek where kode_item='$selected'");
while($koko=mysql_fetch_array($res)){
print_r($koko);
$result = "INSERT INTO detail_daftar VALUES ('',$no_ai','$koko['kode_cek']','0','','','$selected')";
$sql = mysql_query($result);
print_r($result);
}
}
}
You are trying to insert $res change that to $koko['kode_cek']
Insert query doesn't return array. To get inserted id of executed query you have to call last inserted id function which will return you Id of last inserted record in DB.
Below function will help to get ID of inserted record.
`mysql_insert_id();`
This has sorta been an on going problem for me, after I insert into a table in my db I grab the ID that was just generated using $user_id_number = mysqli_insert_id($dbc);
I need to take that value and insert it into the table I just inserted into but into a different column, this is my code
if (mysqli_num_rows($data) == 0) {
// The username is unique, so insert the data into the database
$query1 = "INSERT INTO user_register (user_email, user_password, register_date_time) VALUES ('$user_email', SHA('$user_password1'), NOW())";
mysqli_query($dbc, $query1);
//Grab the primary id key that was just created
$user_id_number = mysqli_insert_id($dbc);
//store Id key in variable for new directory name
$directory_name = 'user_id_'.$user_id_number;
//use id key to name directory
mkdir($directory_name);
//Add the new directory name in user_register table
$query2 = "UPDATE `user_register` SET `client_folder`= [$directory_name] WHERE user_id = $user_id_number";
mysqli_query($dbc, $query2);
It does the first insert, created the directory but does not go on to update the directory name into the table?!!? I have also tried insert and get the same result...any ideas?
ps...I am trying to create a new directory that is named with info from the primary id then can be called later so I can put a new directory in that directory
Since $directory name is a string you will need to surround with quotes
client_folder = '$directory_name' WHERE user_id = $user_id_number";
//^here //^and here
$query2 = "UPDATE user_register SET client_folder= [$directory_name*]* WHERE user_id = $user_id_number";
Remove the "[" and "]"
The update query:
$query2 = "UPDATE `user_register` SET `client_folder`= '$directory_name' WHERE user_id = $user_id_number";