Select last insert id - php

I am inserting a record and i want to use the id of the last record inserted.
This is what i have tried:
$sql = 'INSERT INTO customer
(first_name, last_name, email, password,
date_created, dob, gender, customer_type)
VALUES(:first_name, :last_name, :email, :password,
:date_created, :dob, :gender, :customer_type)'
. ' SELECT LAST_INSERT_ID()' ;
I am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT LAST_INSERT_ID()'.
Can anyone show me where is my mistake?
Thanks!

Check out mysql_insert_id()
mysql_query($sql);
$id = mysql_insert_id();
When that function is run after you've executed your INSERT statement in a mysql_query() command its result will be the ID of the row that was just created.

You can do another query:
$last_id = "SELECT LAST_INSERT_ID()";
Or try to add ; in your query:
INSERT INTO customer
(first_name,
last_name,
email,
password,
date_created,
dob,
gender,
customer_type)
VALUES(:first_name,
:last_name,
:email,
:password,
:date_created,
:dob,
:gender,
:customer_type)<b>;</b>' . ' SELECT LAST_INSERT_ID()';

Related

Insert new data only if it does not exist

Why is this not working? I am trying to insert new data only if it does not meet with my requirements.
$stm= "INSERT INTO `orders` (userid, username, quantity, time, image, uprice, tprice)
VALUES
(:userid, :username, :quantity, :timee, :image, :uprice, :tprice)
WHERE NOT EXISTS (select username from orders where username=:username and image=:image)";
Instead of INSERT .... VALUES which does not allow a WHERE clause, use INSERT .... SELECT:
$stm= "INSERT INTO `orders` (userid, username, quantity, time, image, uprice, tprice)
SELECT :userid, :username, :quantity, :timee, :image, :uprice, :tprice
WHERE NOT EXISTS (select username from orders where username=:username and image=:image)";

LAST_INSERT_ID Mysql is not working

I have the follow query
INSERT
INTO
profile(
fullname,
email,
cpfcnpj,
identity,
phone,
cellphoneone,
cellphonetwo,
birthday,
cep,
address,
)
VALUES(
: fullname, : email, : cpfcnpj, : identity, : phone, : cellphoneone, : cellphonetwo, : birthday, : cep, : address
);
SELECT
LAST_INSERT_ID() AS lid;
PHP Code
$insertProfile = $database->driver()->prepare("
INSERT INTO wordprofile (fullname, email, cpfcnpj, identity, phone, cellphoneone, cellphonetwo, birthday, cep, address, city, state, reference, number, pay, contract) VALUES (:fullname, :email, :cpfcnpj, :identity, :phone, :cellphoneone, :cellphonetwo, :birthday, :cep, :address, :city, :state, :reference, :number, :pay, :contract); SELECT LAST_INSERT_ID() as lid;"
);
$insertProfile->bindValue(":fullname", $arg["name"]." ". $arg["lastname"]);
$insertProfile->bindValue(":email", $arg["email"]);
$insertProfile->bindValue(":cpfcnpj", $arg["cpfcnpj"]);
$insertProfile->bindValue(":identity", $arg["rg"]);
$insertProfile->bindValue(":phone", $tel);
$insertProfile->bindValue(":cellphoneone", $arg["cel1"]);
$insertProfile->bindValue(":cellphonetwo", $cel2);
$insertProfile->bindValue(":birthday", $birthday);
$insertProfile->bindValue(":cep", $arg["zip"]);
$insertProfile->bindValue(":address", $arg["address"]);
$insertProfile->execute();
$lastid = $insertProfile->fetch()[0];
echo $lastid; //nothing, if change to var_dump returns false
It works properly when i run into phpmyadmin or mysql prompt. However that same query returns false in PHP; that insert works, only SELECT LAST_INSERT_ID() AS lid; does not returns.
It doesn't work actually because PDO doesn't support several queries executed in one statement.
You have to make another execute with a separated query or use the method lastInsertId() as mentioned in the comments by Frederic.

update two tables with one query in mysql PHPMyadmin?

I have two tables, user_info and Friend_info. I want to do that when user update his record in user_info then it should also b update in friend_info where friend_id=user_id. I have tried this
UPDATE user_info (name, user_email, Gender, DOB, contact, address) WHERE user_id='$user_id',
friends_info(name, user_email, Gender, DOB, contact, address) WHERE friend_id='$user_id'
values('$name', '$user_email', '$Gender', '$DOB', '$contact', '$address');
But its not working . Any other solution please. It'll be appreciated.
I know this question is too late to ask now a days but its my problem because i am confused after doing so many search and no query is working in my case.
Your question is not clear. So are you testing something like you want query in phpmyadmin. if not then you might need to do in as a transaction. but if its a test or such try this:
UPDATE user_info (name, user_email, Gender, DOB, contact, address)
values('$name', '$user_email', '$Gender', '$DOB', '$contact', '$address')
WHERE user_id='$user_id';
UPDATE friends_info(name, user_email, Gender, DOB, contact, address)
values('$name', '$user_email', '$Gender', '$DOB', '$contact', '$address')
WHERE friend_id='$user_id';
So this is two query which then they are gonna execute together. But now in PHP
check these:
https://stackoverflow.com/a/802474/2226796
http://se2.php.net/manual/en/mysqli.multi-query.php
PHP + MySQL transactions examples
You can join the two tables in your statement using user_id as the joining key.
UPDATE user_info ui
INNER JOIN friends_info fi
ON ui.user_id = fi.user_id
SET ui.name = $name,
SET ui.user_email = $email,
SET ui.Gender = $Gender,
SET ui.DOB = $DOB,
SET ui.contact = $contact,
SET ui.address = $address,
-- set friends_info
SET fi.name = $name,
SET fi.user_email = $email,
SET fi.Gender = $Gender,
SET fi.DOB = $DOB,
SET fi.contact = $contact,
SET fi.address = $address
WHERE ui.user_id = $user_id;

PDO insert statement not posting

I dont get any errors, but when I refresh my database nothing seems to be going through. The connection credentials are definitely correct.
$query = $pdo->prepare('INSERT INTO direct_transfer (fname, lname, add, city, post, country, email, nummag, donate) VALUES (:fname, :lname, :add, :city, :post, :country, :email, :nummag, :donate)');
$query->execute(array(':fname'=>$fname,
':lname'=>$lname,
':add'=>$add,
':city'=>$city,
':post'=>$post,
':country'=>$country,
':email'=>$email,
':nummag'=>$nummag,
':donate'=>$donate));
When you use reserved words in mysql, you need to escape them in backticks:
... (fname, lname, `add`, city, post, country, email, nummag, donate) ...
You should also add error handling so that PDO tells you right away what is wrong.
You can tell PDO to throw exceptions by adding this after you connect to the database:
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
You can also set the error handling mode when you open the connection, see the manual.
Without ':' in the array.
$query = $pdo->prepare('INSERT INTO `direct_transfer` (`fname`, `lname`, `add`, `city`, `post`, `country`, `email`, `nummag`, `donate`) VALUES (:fname, :lname, :add, :city, :post, :country, :email, :nummag, :donate)');
$query->execute(array('fname'=>$fname,
'lname'=>$lname,
'add'=>$add,
'city'=>$city,
'post'=>$post,
'country'=>$country,
'email'=>$email,
'nummag'=>$nummag,
'donate'=>$donate));

Insert into Multiple Tables using PHP with LAST_INSERT_ID()

Below is the code that I've tried but I can't seem to make the right tweaks to get the script to run properly.
$sql = 'INSERT INTO clients (first_name, last_name, email) VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')
INSERT INTO client_data (client_id, phone, zip, note) VALUES(LAST_INSERT_ID(), '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';
mysql_query($sql) or die (mysql_error());
Any help is much appreciated.
You cannot execute two sql statements with mysql_query();
Use something like this:
$sql = 'INSERT INTO clients (first_name, last_name, email) VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')';
mysql_query($sql);
$clientId = mysql_insert_id();
$sql = 'INSERT INTO client_data (client_id, phone, zip, note) VALUES('.$clientId.', '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';
mysql_query($sql) or die (mysql_error());
But please read up on SQL injections and how to prevent them.
Just make 2 queries:
$sql_insert_clients = "INSERT INTO clients (first_name, last_name, email) VALUES(".$_POST['first_name'].", ".$_POST['last_name'].", ".$_POST['email'].")";
mysql_query($sql_insert_clients) or die (mysql_error());
$sql_insert_client_data = "INSERT INTO client_data (client_id, phone, zip, note) VALUES(".mysql_insert_id().", ".$_POST['phone'].", ".$_POST['zip'].", ".$_POST['message'].")";
mysql_query($sql_insert_client_data) or die (mysql_error());
You should break it up into two separate mysql_query calls and use the mysql_insert_id function:
$firstName = mysql_real_escape_string($_POST["first_name"]);
$lastName = mysql_real_escape_string($_POST["last_name"]);
$email = mysql_real_escape_string($_POST["email"]);
$phone = mysql_real_escape_string($_POST["phone"]);
$zip = mysql_real_escape_string($_POST["zip"]);
$message = mysql_real_escape_string($_POST["message"]);
mysql_query("INSERT INTO clients (first_name, last_name, email) VALUES ('{$firstName}', '{$lastName}', '{$email}')") or die(mysql_error());
mysql_query("INSERT INTO client_data (client_id, phone, zip, note) VALUES ('". mysql_insert_id() ."', '{$phone}', '{$zip}', '{$message}')") or die(mysql_error());
Your just missing the semi-colon to split the Insert's
$sql = 'INSERT INTO clients (first_name, last_name, email)
VALUES('.$_POST['first_name'].', '.$_POST['last_name'].', '.$_POST['email'].')'."; ".' INSERT INTO client_data (client_id, phone, zip, note) VALUES(LAST_INSERT_ID(), '.$_POST['phone'].', '.$_POST['zip'].', '.$_POST['message'].')';
mysqli_multi_query($sql) or die (mysql_error());
the SQL query it should be running (with dummy content) is
INSERT INTO clients (first_name, last_name, email) VALUES('test', 'surname', email); INSERT INTO client_data (client_id, phone, zip, note) VALUES(LAST_INSERT_ID(), 'phone', 'zip', 'message');

Categories