I have following code for inserting data into database using PDO.
It inserts data into database but not return last inserted in ID.
here userid is primary key
try {
$dbh = new PDO('mysql:host=localhost;dbname=crud_demo', "username", "password");
$sqlQuery = "INSERT INTO users(userid,first_name,last_name,email,password)
VALUES(:userid,:first_name,:last_name,:email,:password)";
$statement = $dbh->prepare($sqlQuery);
$bind = array(
":userid" => "bhavik",
":first_name" => "Bhavik",
":last_name" => "Patel",
":email" => "bhavitk#live.in",
":password" => "1234567"
);
$statement->execute($bind);
echo $dbh->lastInsertId();
} catch (PDOException $e) {
echo $e->getMessage();
}
$dbh->lastInsertId(); always return 0 whatever i insert value for userid
lastInsertId() only returns IDs automatically generated in an AUTO_INCREMENT column. Your PRIMARY KEY is apparently a string (or at least you're inserting a string in it). Since you're inserting a known value, you don't actually need to find out the inserted ID — you've specified it yourself.
The userid doesn't have an auto_increment attribute in your database, so lastInsertId() will never return anything useful.
You can only lastInsertId() if your field is:
the primary key
not null
an integer type (int, bigint, etc.)
auto_increment
first you need to check insert query.
if its run proper then use mysql function like mysql_insert_id().
if this function is run property then may be possible to mistake in your $dbh->lastInsertId()
this function.
Related
In my code I insert a row in my MySQL table, if it does not exist. Since the query requires an unique index, I am just inserting $id, which is just a static value of 1 (line #8).
public function prepare($author, $arr) {
$conn = new mysqli($this->servername, $this->username, $this->password, $this->db_name);
foreach ($arr as $value) {
$stmt = $conn->prepare("INSERT IGNORE INTO kh_comments(id, author,abstract) VALUES (?, ?, ?)");
$id = 1; // Just a static value
$stmt->bind_param("dss", $id, $author, $value['id']);
$stmt->execute();
$stmt->close();
$conn->close();
}
}
I would now like to use a dynamic value instead of 1. The variable $idshould be smart enough to figure out which ID is affected. Or if there is another way to do this, I appreciate any suggestions!
In MySQL you can define auto increment fields using the AUTO_INCREMENT attribute in a create table or alter table command:
CREATE TABLE animals (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
During the insertion you just do not assign any value to that column and MySQL will automatically assign its value for you:
INSERT INTO animals (name) VALUES
('dog'),('cat'),('penguin'),
('lax'),('whale'),('ostrich');
As the linked documentation says:
You can retrieve the most recent automatically generated AUTO_INCREMENT value with the LAST_INSERT_ID() SQL function or the mysql_insert_id() C API function. These functions are connection-specific, so their return values are not affected by another connection which is also performing inserts.
In mysqli use mysqli_insert_id() function to retrieve this value.
id has an AUTO_INCREMENT value. You don't have to put a value for it. I think this was your question.
This question already has answers here:
PDO get the last ID inserted
(3 answers)
Closed 9 months ago.
I want to insert a new row to a database using PDO in PHP, the primary key is auto-increment, so I am not inserting the value of the PK. This is the code:
public function insertQuestion($text){
try{
$sql = "INSERT INTO question(text) VALUES(:question)";
$stm = $this->prepare($sql);
$stm->execute(array(
':question' => $text,
));
$question = new Question();
$question->text = $text;
$question->id = -1; // How do I get the PK of the row just inserted?
}catch(PDOException $e){
if ($e->getCode() == 1062) return FALSE; // fails unique constraint
else echo $e->getMessage();
}
}
But, I need to store the PK of the new row inserted to the $question object, I have other attributes that are UNIQUE, so I could do a SELECT statement to find the PK, however, is there a better approach for doing it?
call lastInsertId of your PDO object.
$stmt->execute([':question' => $text]);
return $pdo->lastInsertId();
After just inserting the record in the database, write another query to fetch top record from the primary key column values in descending order.
e.g. select prim_key_id top 1 from table order by prim_key_id desc;
I am trying to insert a number of ids into a new table. The list of ids is taken from another table.
My Code:
$stmt = $con->prepare('DROP TABLE tblname;
CREATE TABLE tblname (
id BIGINT
);
INSERT INTO tblname (id)
SELECT tablename2.colname
FROM tablename2
WHERE (col1 = "value" AND col2 = "value")');
$stmt->execute();
I create and dump the table because its part of an update script.
(Is there a better way to do that than dump/create?)
The script needs the current list of ids and I am trying to get create a table with those ids. What happens is, whenever I run the code (using putty) it returns "0" and the table remains empty.
What did I do wrong?
Any general help/advice concerning php/mysql welcome too!
First, make sure PDO is set to throw exceptions if a query fails:
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Then, perhaps catch the exception (or let the exception halt the application) and see what is wrong.
I do believe your insert query is, erm, off:
INSERT INTO tblname (id)
SELECT tblname2.colname
FROM tablename2
WHERE col1 = "val"
Just seems ambiguous, and messy, even more: it seems unsafe. However, try this -equally messy- query:
INSERT INTO tblname (id) VALUES (
SELECT colname
FROM tblname2
WHERE col1 = "val"
);
Last but not least, make sure you're running PHP version 5.3+, because prior to that version, PDO did not support multiple queries.
My suggestion, though, is not to use multiple queries for the INSERT query. Instead, I'd use a transaction and separate the select and insert query. I'd also add a safety-net to the DROP TABLE and CREATE TABLE queries, too:
try
{
$con->beginTransaction();//DROP & CREATE:
if ($con->exec('DROP TABLE IF EXISTS tblname') === false)
{//query wasn't executed
$con->rollback();
exit($con->errInfo());//error
}
if ($con->exec('CREATE TABLE IF NOT EXISTS tblname(...);') === false)
{
$con->rollback();
exit($con->errInfo());
}
$con->commit();//alter tables.
$con->beginTransaction();//INSERT TRANSACTION
$stmt = $con->prepare('INSERT INTO tblname (id) VALUES (:id)');
$bind = array(
':id' => null
);
$select = $con->prepare(
'SELECT colname FROM tblname2 WHERE col1 = :val1 AND col2 = :val2'
);
$select->execute(
array(
':val1' => 'value1',
':val2' => 'value2'
)
);
while ($row = $select->fetch(PDO::FETCH_ASSOC))
{
$bind[':id'] = $row['colname'];
$stmt->execute($bind);//inserts row
$stmt->closeCursor();//optional
}
$con->commit();//save changes to db
}
catch (PDOException $e)
{
//rollback transaction
$con->rollback();
exit($e->getMessage());//show what went wrong, and exit.
}
You are missing a keyword here to INSERT the value into the table, which is VALUES.
The correct syntax will be
INSERT INTO tblname (id) VALUES
SELECT tablename2.colname
FROM tablename2
WHERE (col1 = 'value' AND col2 = 'value')
The values should be into SINGLE QUOTES, tried and test myself and these 2 work for me every time.!
I am inserting a name, number, and company into a DB.
My table is simply:
id(primary key)
name
slideView
company
I need to update this information if a name passed to it exists, if not create a new row with this data. I have looked at REPLACE INTO but I dont think that will work for me... as I dont touch the ID at all.
My code is:
insertData($name,$count,$company);
function insertData($name, $count, $company) {
#Try/Catch statement to connect to DB, and insert data
try {
#DB username/password
$usernameDB = '****';
$passwordDB = '****';
#Create new PHP Database Object with the address, username, and password as parameters
$pdo = new PDO('mysql:host=localhost;dbname=*****', $usernameDB, $passwordDB);
#Set pdo attributes to handle errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
#assign the sth variable (sth means statement handle) to insert the data
$sth = $pdo->prepare("REPLACE INTO ***** SET name = ?, slideView = ?, company = ?");
#Execute the insert
$sth->execute(array($name,$count,$company));
#Error if can't connect or insert
} catch(PDOException $e) {
echo 'Error: ' . $e->getMessage();
}#/try
}
I'm new to SQL and havnt found a good way to do this yet.
You might be better of using the insert ... on duplicate update syntax for this, although it will mean passing a few extra params but it can quash certain problems in the replace into syntax that seem to keep cropping up.
REPLACE INTO ***** SET name = ?, slideView = ?, company = ?
Could be written as:
insert into yourTableName (name, slideView, company)
values (:name, :slideView, :company)
on duplicate key update set
slideView=:$slideView2, company=:company2
and then the execute is done like this:
$sth->execute(array(':name' => $name, ':slideView' => $count,
':company' => $company, ':slideView2' => $count, ':company2' => $company));
The format above uses named paramaters (they are ever so much easier to read/debug) and will insert a new row into the database - or if the unique/primary key column name already has the value, then update the row with the remainder of the information.
You do have to use paramaters twice here (even though slideView and company will contain the same information) as no parameter can be used twice in a query.
REPLACE INTO should work just fine - it also checks for columns with UNIQUE constraints. So you would just need to mark your name column as unique so that REPLACE INTO will identify it as duplicate.
I haven't tried this particular use case, but the documentation seems to allow it.
I want to insert a new row in my table. I want the id to be generated right automatically and not asked from the user. The user only provides title and text. I wrote this code in PHP:
<?php
$hostname = "localhost";
$database = "mydb";
$username = "myuser";
$password = "mypsw";
$link = mysql_connect( $hostname , $username , $password ) or
die("Attention! Problem with the connection : " . mysql_error());
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_query("SET NAMES ‘utf8’",$link);
mysql_select_db("mydb", $link);
$lastid=mysql_insert_id();
$lastid=$lastid+1;
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
if (!mysql_query($sql,$link))
{
die('Error: ' . mysql_error());
}
mysql_close($link);
header("Location: announcement.php");
?>
Sadly when I test it on my website, I get this error:
Error: Duplicate entry '0' for key 'PRIMARY'
Is mysql_insert_id() not working? What is wrong?
Don't do this. mysql will happily create an auto_increment column for you:
CREATE TABLE x (
id int not null primary key auto_increment
^^^^^^^^^^^^^^---add this to your PK field
);
INSERT INTO x (id) VALUES (null); // creates id = 1
INSERT INTO x (id) VALUES (null); // creates id = 2
mysql_insert_id() only returns the last id created by the CURRENT connection. You haven't inserted any data yet when you first run it, so you get back nothing.
Your version is incredibly vulnerable to race conditions. There is NO guarantee that the last ID you retrieve with mysql_insert_id() will not ALSO get retrieved by another copy of the script running in parallel, and get sniped out from under this copy of the script.
The primary key column on announcements should be auto_increment. When you do mysql_insert_id() it retrieves the id from the last query executed from that connection.
Because the INSERT is the query you are currently performing, it errors.
Try
INSERT INTO announcements
(date_field, title, text)
VALUES (CURDATE(),'$_POST[title]','$_POST[text]')
Just replace 'date_field', 'title', and 'text' with the applicable column names.
Alternatively the following should also work, as a NULL value in the AutoIncrement value should be acceptable
INSERT INTO announcements VALUES (NULL,CURDATE(),'$_POST[title]','$_POST[text]')
As mentioned in the other suggestion posted, you should make sure that the primary key field of the announcements table is set to be auto_increment.
Just for completion, you would use mysql_insert_id() when you want to use the id for the row you just inserted, i.e. if you then want to select the row you just inserted you could do
'SELECT * FROM announcements WHERE id = '.mysql_insert_id()
The problem is that you are asking for last insert id and you didn't inserted anything.
Convert your ID field in db to be autoincrement if its not.
Insert into database your announcment
Then ask for id using mysql_insert_id to get it.
But I see that you are not using it only when inserting then you don't need that functionality anyhow. Just insert without ID like this
"insert into announcements (InsertDate, Title, Text) VALUES (CURDATE(), '$_POST[title]', '$_POST[text]')";
and you should really be careful with your queries when using values from $_POST or $_GET or any other user typed value. There is possibility to execute SQLInjection through your form fields, so I suggest you to use mysql escape command or use parameters.
I hope this helps.
Assuming your table is set up properly, with the id field as AUTO_INCREMENT, you just need to perform an INSERT where you do not specify a value for id. That means you must specify the names of the columns you are inserting. So this line:
$sql="INSERT INTO announcements VALUES ('$lastid',CURDATE(),'$_POST[title]','$_POST[text]')";
becomes this
$sql="INSERT INTO announcements (`date`,`title`,`text`) VALUES (CURDATE(),'$_POST[title]','$_POST[text]')";
I guessed what your column names might be. Obviously they need to match your table definition.
If you do this, then the mysql_insert_id() function will return the id of the row you just inserted. (That is, it gives you the value of the previous insert, not the next one.)
You probably want to add "auto increment" to the table when creating it.
This will add an id automatically when inserting something.
e.g.
CREATE TABLE announcements
(
id int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
some_date int(11),
title varchar(200),
text varchar(3000)
);
mysql_insert_id "Retrieves the ID generated for an AUTO_INCREMENT column by the previous query " - http://php.net/manual/en/function.mysql-insert-id.php