Getting row data of inserted row (Mysql, PHP, mysqli) - php

I need to get back the postid (auto-incrementing PK) of a row when i insert it.
I am currently using this to get it
//get postid to return
if($result = $db -> query('SELECT postid FROM posts WHERE title = \''.$title.'\' LIMIT 1')){
$row = $result->fetch_assoc();
$json['postid'] = $row['postid'];
$result->free();
where $title is the title name of the newly-inserted post.
Is there part of the mysqli class that will allow me to do this in one query?? Does $db -> query() return any information that will make this simpler and more secure?
I have tried looking through the mysqli documentation, but I could not find what i wanted. I'm sure it is there somewhere.
Multiple titles will screw this up, and although they are not allowed, you cant be too safe

Does your table have an AUTO_INCREMENT column? If so you can use mysql_insert_id() or mysqli->insert_id to get that value, and then use it to select the row. More info here.

insert_id
http://php.net/manual/en/mysqli.insert-id.php

Related

php mysql get id of last insert row giving error

i want to get the id of last inserted row and i m using mysql_insert_id() function. but giving issue
here is my code :
if($i == 0)
{
$query = "update events set e_did ='".$multi_event."' where eid = '".$display_id."'";
mysqli_query($con,$query);
file_put_contents('log.txt', mysql_insert_id(), FILE_APPEND);
}
else
{
$query = "INSERT INTO events (start_date, end_date, text, rec_type, event_pid, event_length, e_did) VALUES ('".$row['start_date']."','".$row['end_date']."','".$row['text']."','".$row['rec_type']."','".$row['event_pid']."','".$row['event_length']."','".$multi_event."')";
mysqli_query($con,$query);
file_put_contents('log.txt', 'A'.mysql_insert_id().'A', FILE_APPEND);
}
now both time i m getting same id. what is the issue. is i m doing wrong something somewhere ?
If you use the mysqli functions, you must use mysqli_insert_id. You can't mix ext/mysql and ext/mysqli.
Also, UPDATE does not generate a new auto-increment id. You should call mysqli_insert_id() after INSERT, but not UPDATE.
mysqli_insert_id() only returns an id for INSERT queries. An update query will NOT return an id, because by definition you must already have a row in the database for it be getting updated.
With UPDATE, you are editing records, not adding ones. So no new IDs are generated. You can only use mysql_insert_id on INSERT.
Note: mysql_* functions are deprecated and won't be supported in future versions. You should be using either mysqli_* or PDO.

If ID from db row matches id from PHP GET function, return x page

basically I want to display a row from my database when the id from a get id switch statement matches the id from said row in the database. I'm confusing myself here so let me explain further.
If the url is www.example.com/index.php?id=2
I want the row with the id of 2 to be displayed on the page.
Here is an example of what is in the database;
id = 2
name = john
id = 3
name = mark
So if the id in the URL is equal to 2, then display id 2 and name john.
But if the id in the URL is equal to 3, then display id 3 and name mark.
I'm using a get function to do this but I'm not sure how to basically get the two ids to compare themselves and get the respective row from the database.
I'm quite new to PHP as well, so small words please! :)
Revision 2.
Like I said above, I'm new to PHP so a lot of what has been posted is confusing me a lot. But when I'm trying out various bits of code, I'm getting the following;
Warning: mysqli_query() expects at least 2 parameters, 1 given ...
Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, null given
I've used each sample of code, but it seems like I'm mixing them now. Hmm.
You probably want something like this (database connection code and error handling not shown):
$id = intval($_GET['id']);
$result = mysqli_query("SELECT id, name FROM table WHERE id=$id");
$row = mysqli_fetch_assoc($result);
echo $row['id']." ".$row['name'];
About the posted code:
You never use $result.
Inside your switch, you are assigning $id to $_GET['id'], which results to using the include always, except when $_GET['id'] is 0.
You should pass the id value to your sql( by maintaining sql injection threat) and then you can get the values of the fetched by using fetch_assoc function of mysql(deprecated) or mysqli.
$id = $_GET['id'];
$result = mysqli_query($mysqli, "SELECT * FROM names where id='$id'");
$row = mysqli_fetch_array($result);
$row_id = $row['id'];
header("www.example.com/index.php?id=$row_id");
Warning! This is just a simple answer. There are many DANGERS of using this code as it is wide open for SQL injection attacks. Consider sanitation (eg. intval($_GET['id']). And header() function is used by assuming not header information is sent before this code (even space!).
You should use prepared statments. Here is an example using PDO
$stm = $pdo->prepare("SELECT name FROM table WHERE id=?");
$stm->execute(array($_GET['id']));
$name = $stm->fetchColumn();

Using Prepared Statement, how I return the id of the inserted row?

I want retrieve the id of a inserted row in the database, but I don't know how to do this.
I tried to return using the SQL clause RETURNING id, but not works.
How I can return the id after the insertion of a row?
After calling the execute() method on the Prepared Statement, the id of the insert row will be in the insert_id attribute.
$pstm->execute();
$pstm->insert_id;
$newid = mysqli_insert_id($mysqli_db);
$mysqli_db is your mysqli database connection. As far as I know it shouldn't matter on which way ou inserted the row (prepared statement or direct INSERT INTO). mysqli_insert_id() should return the id of the last inserted row using this db connection.
The alternative is to make another query like SELECT LAST_INSERT_ID();.
You need to use:
$stmt = $db->prepare("SQL Query");
$stmt->execute();
$id = $db->lastInsertId();

MYSQL: SQL query to get the value of autoincrement field

I have a table. The primary key is id and its auto incremented.
Now when I insert a new record, I need to get the id with which the record was updated.
How can I do that? If i use the query...
select max(id) from table_name
...after executing I can get the id. But can I be sure that its the id of the record that was just inserted? Because many people will be using the app at same time.
I am using php and mysql.
Can ayone provie me a sample code snippet in php with mysql?
If you want to find out what the newest ID from an auto increment column is, you just have to run the mysql_insert_id() function right after your insert query.
Like so:
//--connection already made to database
//--now run your INSERT query on the table
mysql_query("INSERT INTO table_name (foo_column) VALUES ('everlong')");
//-- right after that previous query, you run this
$newest_id = mysql_insert_id();
And now $newest_id will contain the ID of the latest row inserted.
Assuming you're using the MySQLi PHP extension, the command you want is mysqli_insert_id
In SQL you can do this
SELECT LAST_INSERT_ID()
In php you can call mysql_insert_id()
Using the same connection, run this query next:
SELECT LAST_INSERT_ID()
Your database driver may have a convenience function for that.
Read the docs.
you can use this to get the value of the next auto_increment value (given that you already connected to the server and selected the db;
$query = "SHOW TABLE STATUS LIKE 'tbl_name'";
$result = mysql_query($query);
$auto_incr_val = mysql_result($result, 0, 'Auto_increment');
echo $auto_incr_val;
This will give you the value that will be used next in the auto_increment column.
EDIT: I'm sorry.. That wasn't your question....
Here is example in PHP:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("YOUR QUERY HERE", $link);
$inserted_id = mysql_insert_id($link));
Query
show create table
contains information you need in last string

php mysql_insert_id(); not working

Hi guys I was hoping from some help here, please.
I have a INSERT query to a table, after this is done I am calling:
mysql_insert_id();
In order to send the last ID inserted into the table to the next page like this:
$insertGoTo = "confirm_booking.php?booking_ID=" .$_POST['booking_ID']. "";
Unfortunately it does not work, all I get is a zero.
The table I am inserting into has an auto increment number and values are inserted into it.
I have also tried SELECT MAX(id) FROM mytable. This dosn't work neither.
I know that this problem has been talked about already. I read all posts but nothing came useful.
Many thanks Francesco
You have to use the value returned by MySql_Insert_Id () when you generate your link:
// your query
$newId = MySql_Insert_Id ();
$insertGoTo = "confirm_booking.php?booking_ID=" . $newId;
It is possible that your table does not have any AUTO_INCREMENT field!
It could also happen because you have two or more mysql connections at the same time.
In this case you should use a link identifier.
$link = mysql_connect( ... );
mysql_select_db('mydb', $link);
mysql_query('INSERT mytable SET abc="123"', $link);
$inserted_id = mysql_insert_id($link);
Some key points from the PHP Manual:
The ID generated for an AUTO_INCREMENT
column by the previous query on
success, 0 if the previous query does
not generate an AUTO_INCREMENT value,
or FALSE if no MySQL connection was
established.
If not having an AUTO_INCREMENT field is not your problem, you might want to try storing the result of the mysql_query call and using that as an argument to the id function
$result = mysql_query("...");
$id = mysql_insert_id($result);
Had an issue using a query like this:
INSERT INTO members (username,password,email) VALUES (...)
reason being that the id (which is my primary key and Auto Increment field) is not part of the query.
Changing it to:
INSERT INTO members (id,username,password,email) VALUES ('',...)
using a an empty value '' will have MySQL use the Auto Increment value but also allow you to use it in your query so you can return the insert id
mysql_insert_id may return 0 or false if your insert fails right?
So if you have trouble with mysql_insert_id not retunring what you expect confirm that you don't have a unique constraint or some other problem with your sql that would cause the insert to fail. Using max is a terrible idea if you consider this.
Make sure to put mysql_insert_id()after the
mysql_query($sql, $con); //Execute the query
Above query responsible for execute your Insert INTO ... command.
After you can get the last ID inserted
I have also suffer from this problem. Finally I found that the problem occur in my connection to the database. You can use this following connection code to connect the database then you can easily use mysqli_insert_id().
$db_connect = mysqli_connect("localhost", "root", "", "social");
Then you can use mysqli_insert_id() as
$id = mysqli_insert_id($db_conx);
I hope this will help you. I you have any problem then leave your comment.
The mysqli_insert_id function has been deprecated. This may be your problem.
Instead, try $mysqli->insert_id. See the documentation for more info.

Categories