Asked  7 Months ago    Answers:  5   Viewed   21 times

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!

 Answers

71

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.

Wednesday, March 31, 2021
 
Grzegorz
answered 7 Months ago
60

try

$id = $tablemodel->insert($data);  
echo $id;
Wednesday, March 31, 2021
 
Lance
answered 7 Months ago
71

you can't print the result from mysqli_query, it is mysqli_resource and for dumping the error you need to change mysql_error() to mysqli_error()

$username = "bob";
$db = mysqli_connect("localhost", "username", "password", "user_data");
$sql1 = "select id from user_information where username='$username'";
$result = mysqli_query($db, $sql1) or die(mysqli_error());
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { 
    echo $row['id'].'<br>'; 
} 
Saturday, May 29, 2021
 
pamelus
answered 5 Months ago
67

You could store the last insert id in a variable :

INSERT INTO table1 (title,userid) VALUES ('test', 1); 
SET @last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO table2 (parentid,otherid,userid) VALUES (@last_id_in_table1, 4, 1);    

Or get the max id frm table1

INSERT INTO table1 (title,userid) VALUES ('test', 1); 
INSERT INTO table2 (parentid,otherid,userid) VALUES (LAST_INSERT_ID(), 4, 1); 
SELECT MAX(id) FROM table1;   
Tuesday, June 1, 2021
 
JackTheKnife
answered 5 Months ago
39

yo need create the user "pma" in mysql or change this lines(user and password for mysql):

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma'; 
$cfg['Servers'][$i]['controlpass'] = '';

Linux: /etc/phpmyadmin/config.inc.php

Tuesday, July 13, 2021
 
ShadowZzz
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :