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.
Related
I'm building a simple bug tracking tool.
You can create new projects, when you create a project you have to fill in a form, that form posts to project.class.php (which is this code)
$name = $_POST['name'];
$descr = $_POST['description'];
$leader = $_POST['leader'];
$email = $_POST['email'];
$sql="INSERT INTO projects (name, description, leader, email, registration_date)
VALUES ('$name', '$descr', '$leader', '$email', NOW())";
$result = mysql_real_escape_string($sql);
$result = mysql_query($sql);
if($result){
header('Location: ../projectpage.php?id='.mysql_insert_id());
}
else {
echo "There is something wrong. Try again later.";
}
mysql_close();
(It's not yet sql injection prove, far from complete...)
Eventually you get redirected to the unique project page, which is linked to the id that is stored in the MySQL db. I want to show the name of that project on the page, but it always shows the name of the first project in the database.
(here I select the data from the MySQL db.)
$query = 'SELECT CONCAT(name)
AS name FROM projects';
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
(here I show the name of the project on my page, but it's always the name of the first project in the MySQL db)
<?php
if ($row = mysql_fetch_array ($result))
echo '<h5>' . $row['name'] . '</h5>';
?>
How can I show the name of the right project? The one that is linked with the id?
Do I have the use WHERE .... ?
Yes, You have to use the WHERE to specify which project You want to get. I'm also not sure why are You using CONCAT function when You want to get only one project.
Other important thing is that You have to use mysql_real_escape_string() function on parameters before You put them in the query string. And use apropriate functions for specific type of data You receive.
So Your statement for getting the project should look like this:
SELECT name FROM projects WHERE id = ' . intval($_GET['id'])
Also when before You use the mysql_fetch_assoc() function, check if there are any records in the result with
if(mysql_num_rows($result) > 0)
{
$project = mysql_fetch_assoc($result);
/* $project['name'] */
}
try this
// first get the id, if from the url use $_GET['id']
$id = "2";
$query = "SELECT `name` FROM `projects` WHERE `id`='".intval($id). "'";
$result = mysql_query(mysql_real_escape_string($query));
use mysql_fetch_row, here you'll not have to loop through each record, just returns single row
// if you want to fetch single record from db
// then use mysql_fetch_row()
$row = mysql_fetch_row($result);
if($row) {
echo '<h5>'.$row[0].'</h5>';
}
$row[0] indicates the first field mentioned in your select query, here its name
The might be of assistance:
Your are currently assing a query string parameter projectpage.php?id=
When you access the page the sql must pick up and filter on the query string parameter like this:
$query = 'SELECT CONCAT(name) AS name FROM projects WHERE projectid ='. $_GET["id"];
$result = mysql_real_escape_string($query);
$result = mysql_query ($query);
Also maybe move mysql_insert_id() to right after assigning the result just to be safe.
$result = mysql_query($sql);
$insertId = mysql_insert_id();
Then when you assign it to the querystring just use the parameter and also the
header('Location: ../projectpage.php?id='.$insertId);
$sql_comp5 ="INSERT INTO `tiquets` (`Id_Tiquet`) VALUES (NULL); SELECT LAST_INSERT_ID()";
$result8 = mysql_query($sql_comp5);
$flag_control=0;
while ($row = mysql_fetch_assoc($result8, MYSQL_BOTH))
{
$flag_control=$flag_control+1;
$id_t[$flag_control]=$row['LAST_INSERT_ID()'];
}
for ($buc = 1; $buc <=$flag_control; $buc++)
{
$id_tiquet=$id_t[$buc];
}
I am doing the correct? Or i'm wrong?
Very thanks!!
You can't do two queries use mysql_* functions. You need mysqli::multi_query() for that. To get the last insert ID using mysql_* use mysql_insert_id():
$sql_comp5 ="INSERT INTO `tiquets` (`Id_Tiquet`) VALUES (NULL);";
$result8 = mysql_query($sql_comp5);
$id = mysql_insert_id($result8);
Remove the second query - and use php's mysql_insert_id()
$sql_comp5 ="INSERT INTO tiquets (Id_Tiquet) VALUES (NULL)";
$result8 = mysql_query($sql_comp5);
$insertedId = mysql_insert_id();
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
I am trying to get last autoincrement id from INSERT/UPDATE query, i am trying this way, but its not working, it just echo id=0 every time.
PHP
require_once('conn.php');
$temp = 'temp';
$query = "INSERT INTO temp (temp) VALUES('$temp')";
$result = mysqli_query($conn, $query) or trigger_error(mysqli_error($conn), E_USER_ERROR);
$id = mysqli_insert_id($conn);
echo 'id = '.$id;
Please see and suggest any possible way to do this.
Try changing the query to.
INSERT INTO `temp` (`temp`) VALUES('$temp')
I have mysql table with following fields
id (which auto increments)
title,name,age,institution,iod
the fields like title,name,age,institution are entered in the form structure (html page) and by clicking submit button are stored in DB(mysql)
iod is the field is something like this 123/id (nothing but same id field but with '123/' prefix before)
now when the user enters title,name,age,institution these need to stored in DB including id and iod.
Now for executing the above i wrote the following the fields title,name,age,institution and id are successfully stored but iod is not stored.
Can you please show me the error i made here??
I wrote the following syntax for the code(part of the same code)
if ($_POST['title'] != '')
{
$value = $_POST['title'];
$value1 = $_POST['name'];
$value2 = $_POST['age'];
$value5 = $_POST['institution'];
$sql = "INSERT INTO parentid(title,name,age,institution) VALUES('$value','$value1','$value2','$value5')" ;
}
$sql1="SELECT * FROM parentid ORDER BY id DESC LIMIT 1";
$value6=$row['id'];
$value4= '123/' . $row['id'] ;
$sql2="UPDATE parentid SET iod='$value4' WHERE id = '$value6' ";
The problem is that you are not executing your queries, you just put the query in a string but then you donĀ“t do anything with it.
For the second query (simple sample code):
$sql1="SELECT * FROM parentid ORDER BY id DESC LIMIT 1";
$result = mysql_query($sql1);
if ($row = mysql_fetch_assoc($result))
{
$value6=$row['id'];
// etc., error handling not added
}
You didn't execute any of the queries? Also, you should escape the parameters...
if ( !empty( $_POST['title'] ) || !empty( $_POST['calc_url'] ) ) {
$value = mysql_real_escape_string( $_POST['title'] );
$value1 = mysql_real_escape_string( $_POST['name'] );
$value2 = mysql_real_escape_string( $_POST['age'] );
$value5 = mysql_real_escape_string( $_POST['institution'] );
$sql = "INSERT INTO parentid
(title,name,age,institution)
VALUES ('$value','$value1','$value2','$value5')" ;
mysql_query( $sql ) or die( mysql_error());
}
Also, you don't need a second select... Get the id by using mysql_insert_id function.
$value6 = mysql_insert_id();
$value4= '123/' . $value6 ;
And then update:
$sql2="UPDATE parentid SET iod='$value4' WHERE id = '$value6' ";
mysql_query( $sql2 );
I encorage you to use PDO or mysqli though...
Unless you've missed out chunks of code when copying/pasting into the question, there are a few problems.
Firstly, you're not actually executing the queries (I'm assuming that you are actually connecting to the database somewhere). After you assign a string to $sql, you can execute the query:
$result = mysql_query($sql);
Secondly, $row won't contain anything unless you get the data out of the dataset returned by the query:
$row = mysql_fetch_assoc($result);
Third, your if statement does not contain the UPDATE query, so that's going to execute whether or not $_POST['title'] is empty or not.
As others have mentioned, your queries are wide open to SQL injection attacks. At a minimum you will need to use mysql_real_escape_string around any inputs.
Finally, you can use mysql_insert_id to get the ID of the latest insert, instead of making another read.
Here's some attempt to rework your code (note that this is untested and could be much better):
if($_POST['title'] != '') {
//Connect to database here (or somewhere else if you already are)
$value = mysql_real_escape_string($_POST['title']);
$value1 = mysql_real_escape_string($_POST['name']);
$value2 = mysql_real_escape_string($_POST['age']);
$value5 = mysql_real_escape_string($_POST['institution']);
$sql = "INSERT INTO parentid(title,name,age,institution) VALUES('$value','$value1','$value2','$value5')";
$result = mysql_query($sql);
if($result) {
$value6 = mysql_insert_id($result);
$value4 = '123/' . $value6;
$sql2 = "UPDATE parentid SET iod='$value4' WHERE id = '$value6'";
mysql_query($sql2);
}
}
My guess is that you have a special character that needs escaping.
I'm assuming you already know you should escape all those strings before inserting them in the DB.
In PHP you have a mysql_real_escape_string function that you should use to escape each of those values.