Why does mysql_insert_id() return 0? - php

When I run this code
$sql_select = "INSERT INTO `database`.`table`(Columns) VALUES (Values)... ";
$mysqlid = mysql_insert_id($sql_select->db);
echo ($mysqlid);
I get the error message
mysql_insert_id(): supplied argument is not a valid MySQL-Link
I have tried this variation;
$mysqlid = mysql_insert_id();
echo ($mysqlid);
but that returns a 0 which, according to the documentation, means an auto_increment field was not found. The only thing I can think of is that I am not calling the auto_increment column in the $sql_select, but there is an auto_increment column in there; will that affect the behavior of mysql_insert_id?

you need to actually run the query first:
$sql= "INSERT INTO `database`.`table`(Columns) VALUES (Values)...";
$result = mysql_query($sql);
and then after that:
$id = mysql_insert_id();
echo $id
Let me know if you have still problems.

That is because $sql_select->db is not a valid MySQL Link
What you are looking for is something like this:
$sql_select = "INSERT INTO `database`.`table`(Columns) VALUES (Values)...
$result = mysql_query($sql_select);
$mysqlid = mysql_insert_id($result->db);
$result is a valid MySQL resource.
Also don't forget to have created a mysql connection
NOTE: While I used code for the original MySQL driver it's use is discouraged. Instead you want to use MySQLi or PDO_MySQL

You need to run your query:
if($result = mysql_query($sql_select)){
$mysqlid = mysql_insert_id();
echo $mysqlid;
}
Cheers

your connection of mysqli is an object...so try this....
$mysqli = new mysqli("localhost", "user", "password", "dbname");
after inserting try this..
echo $mysqli->insert_id;

Related

getting last auto generated id using mysql_insert_id() in php

I am trying to get last auto incremented customer ID from customer table using mysql_insert_ID function and store it in a variable named lastid and try to send lastid variable using session on another page and printing it there it won't give any output or error
//---page1.php
// Start a session to be able to store SESSION variables.
session_start();
// Your connection to Database
$conn = new mysqli("localhost", "my_user", "my_password", "world");
// Your insert query
$insert_query = "INSERT INTO customers .....";
// Query the database
$conn->query( $insert_query );
// STORE Last_inserted_id into $lastid and $_SESSION
$_SESSION['lastid'] = $lastid = $conn->insert_id;
//---page2.php
// Start a session to be able to use SESSION variables in the new page.
session_start();
// Get value from $_SESSION
echo $_SESSION['lastid'];
Taken from documentation $insert_id and session_start()
PDO is the one way to do this if you want to do with PDO then here you can follow this:
After a successful query simply use lastInsertId method with your PDO instance :
$lastId = $pdo->lastInsertId(); //This variable will store last insert ID
For More details about lastInsertId() Method you may check this official Documentation PHP Last Insert Id
If you think that will be better to use mysqli for you Then
Just simply after a successful query do like this:
$lastId = $mysqli->insert_id; // this is how you will get last inserted id
You may follow this stackoverflow question: Follow This
Since you're familiar with mysql, use mysqli... in that case:
$sql = "SELECT max(id) as max FROM table";
From there:
$result = $conn->query($sql);
$row = $result->fetch_assoc();
$maxID = $row['max']
If you wish to stay in mysql_
$sql = "SELECT max(id) as max FROM table";
From there:
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$maxID = $row['max']

How to get last created ID

No matter what I try - I cant seem to pull the last created id of the query I inserted to mySql.
I read here about syntaxes that are deprecated and all sort of code that wont work.
I tried both functions (I use bigint) so I understand that this is how to go:
if (($result = $conn->query("SELECT LAST_INSERT_ID()")) === FALSE) {
die(mysql_error());
}
if ($result->fetch_assoc()) {
$id = $row[0];
echo $id;
}
but nothing!!
Can someone please just give me a full simple php code sample of how to do it?
You can use $result = $conn->insert_id; to know last inserted row
Try this to get the last insert Id,
echo mysql_insert_id();
Dont use mysql its depricated, instead use mysqli or PDO. To get last inserted record use mysqli_inserted_id(). The following shows the snipped how to use-
<?php
$link = mysqli_connect("localhost", "username", "password", "dbname") or die('Facing some problem connecting with database');
$query = "INSERT INTO `table_name` VALUES (v1, v2, v3...vn)";
mysqli_query($link, $query);
printf ("New Record with id %d inserted", mysqli_insert_id($link));

mysql_insert_id() always returns 0

I'm trying to retrieve the last id number inserted with mysql_insert_id() but always return 0, my id field is auto increment so I don't know why it returns 0 thanks. please help
include 'C:\xampp\htdocs\Student_evaluation\functions.php';
if(!loggedin())
{
header("Location: http://localhost/dev/userarea.php");
exit();
}
if(isset($_POST['submit']))
{
//get data
$name = $_POST['name'];
$f_lastname = $_POST['f_lastname'];
$second_lastname = $_POST['second_lastname'];
$student_number = $_POST['student_number'];
$semester_year = $_POST['semester_year'];
$course = $_POST['course'];
$section = $_POST['section'];
$grade = $_POST['grade'];
$student_perform = $_POST['student_perform'];
$comment_box = $_POST['comment_box'];
$sql = "INSERT INTO `students`(`name`, `first_lastname`, `second_lastname`, `numero_estudiante`, `semester`, `course`, `section`, `f_grade`, `students_perform`, `comments`)
VALUES ('$name','$f_lastname','$second_lastname','$student_number','$semester_year','$course','$section','$grade','$student_perform','$comment_box')";
$con = mysqli_connect("localhost","root","","rememberme");
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysql_insert_id();
}
You're using one library (mysqli) to perform the query, then another (mysql) to obtain the auto-increment ID. That can't work. Among other issues, you haven't even connected to the database with the second library!
Consistently use mysqli or, better yet, PDO, which will help you plug your blinding security flaw.
You should do something like this (using mysqli_insert_id):
$con = mysqli_connect("localhost","root","","rememberme");
$sql = "INSERT INTO ...";
$result = mysqli_query($con, $sql);
echo "ID of last inserted record is: " . mysqli_insert_id($con);
mysql_insert_id and mysqli_insert_id are both different and you are using mysqli so use mysqli_insert_id instead of mysql_insert_id and it's better to use mysqli instead of mysql.

Get id of last inserted row in PHP

I use PHP for server side scripting and mysql server for database.
If I use mysql_insert_id() then it gives "0" and use of LAST_INSERT_ID() causes error "object returned empty description".This error I see when I debug on client-side in objective-C.
My table's id column is auto generated. I dont' pass id explicitly.
Below is the PHP code :
// Connect to our database
$db = Frapi_Database::getInstance();
$sql = "INSERT INTO userTrip
(userId, fromLat, fromLon, fromLoc, fromPOI,
toLat, toLon, toLoc, toPOI,
tripFinished, isMatched, departureTime, createdAt)
values
(".$userId.",".$fromLat.",".$fromLon.", GeomFromText('POINT($fromLat $fromLon)')".",'".$fromPOI."',".$toLat.","
.$toLon.", GeomFromText('POINT($toLat $toLon)')".",'".$toPOI."',0,0,'".
$departureTime."','".date('Y-m-d H:i:s')."')";
$stmt = $db->prepare($sql);
if (!$stmt->execute())
throw new Frapi_Error('ERROR_INSERTING_RECORD');
$lastId = LAST_INSERT_ID();
$this->data['tripId'] = $lastId;
$db = null;
Frapi Database extends from PDO, so you would use this:
$lastId = $db->lastInsertId();
See also: PDO::lastInsertId()
Try this (if you use mysqli):
$db->insert_id;
Or (if you use PDO):
$db->lastInsertId();
are you looking for this ?
to get the last inserted id
mysql_insert_id();
mysql_insert_id
Try with
$id = mysql_insert_id();
it will work for you,try this link mysql_insert_id
and this
If your table have AUTO INCREMENT column like UserID,Emp_ID,.. then you can use this query to get last inserted record
SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name)
In PHP code:
$con = mysqli_connect('localhost', 'userid', 'password', 'database_name');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = "SELECT * FROM table_name where UserID=(select MAX(UserID)from table_name)";
$result = mysqli_query($con, $sql);
Then you can use fetched data as your requirement

Weird behavior PHP vs MySQL

This is the SQL:
TRUNCATE TABLE `dc_path`;
INSERT INTO dc_path (coords) VALUES('(40.64406436923055, -8.638539251709062)');
INSERT INTO dc_path (coords) VALUES('(40.62791121610622, -8.615193304443437)');
INSERT INTO dc_path (coords) VALUES('(40.62895347295352, -8.6625718444825)');
If I try to execute that query on phpmyadmin it works just fine, but through php it gives me this 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 'INSERT INTO dc_path (coords) VALUES('(40.64406436923055, -8.638539251709062)');I' at line 1
I tried many things and I can't work it out!
Thanks in advance.
Edit:
PHP
function insertPath($coords){
$conn = connectDB();
$coords = explode(";",$coords);
$sql = "";
$sql = "TRUNCATE TABLE `dc_path`; ";
for($i=0;$i<count($coords)-1;$i++){
$sql .= "INSERT INTO dc_path (coords) VALUES('".$coords[$i]."');";
}
echo $sql;
$query = mysql_query($sql, $conn) or die(mysql_error());
closeDB($conn);
return true;
}
the $coords variable contains something like these values:
(40.638854101691635, -8.6515855163575);(40.629474595277166, -8.63235944213875);
You cannot perform several queries in one mysql_query() call.
So split that string to 4 separated queries (without ; in the end) and everything will work
Don't use the old mysql_connect API, use mysqli - which supports multiple statements in one.
Read more about the different PHP - mySQL apis here: http://www.php.net/manual/en/mysqlinfo.api.choosing.php
There it says that the old mysql API is not recommended for new projects, and that long term deprecation has been announced.
What function are you using to run this? If you're using mysql_query then you can only do one query at a time, however you can merge the insert statements into one like
INSERT INTO dc_path (coords) VALUES
('(40.64406436923055, -8.638539251709062)'),
('(40.62791121610622, -8.615193304443437)'),
('(40.62895347295352, -8.6625718444825)');
function insertPath($coords){
$conn = connectDB();
$coords = explode(";",$coords);
mysql_query("TRUNCATE TABLE `dc_path`", $conn);
for($i=0;$i<count($coords)-1;$i++){
mysql_query("INSERT INTO dc_path (coords) VALUES('".$coords[$i]."')", $conn);
}
closeDB($conn);
return true;
}
You cannot query more than one statement using mysql_query().
Query like this
for($i=0;$i<count($coords)-1;$i++){
$sql = "INSERT INTO dc_path (coords) VALUES('".$coords[$i]."');";
$query = mysql_query($sql, $conn) or die(mysql_error());
}

Categories