How do i get the last ID's from the inserted data? - php

I have an option to send multiple rows into an table, i'm using an foreach to do that:
if (is_array($add['jobname'])) {
$insert = "INSERT INTO job_offers (job_category, status) VALUES ";
foreach ($add['job_name'] as $key => $value) {
$insertedval[] = "
('" . safe($add['job_category'][$key]) . "',
'" . safe($add['status'][$key]) . "')";
}
}
$insert .= implode($insertedval, ",");
$last_id = db_query($insert, '+id?'); //gets the last generated ID, its a function that i created, and working great.
The problem is that i want to get the last ID, and i'm getting, but i'm inserting multiple rows into the database, and i want to get the ID's from all the inserted values, because they are being sent at the same time.
I can't put the $last_id variable inside the foreach loop, what do i do?
ps: i'm using auto increment

Can you try something like this?
$db = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
$db->beginTransaction();
$stmt = $db->prepare('INSERT INTO job_offers (job_category, status) VALUES (?, ?)');
$insertedIds = array();
foreach ($add['job_name'] as $key => $value) {
$stmt->execute($add['job_category'][$key], $add['status'][$key]));
$id = $db->lastInsertId();
array_push($insertedIds, $id);
}
$db->commit();
the ids should be in the insertedIds.

You can't.
Only by saving the the last index id before the inserted data, and than do it again after and select all the ids between that range.
SELECT ID FROM job_offers ID BETWEEN last-before-insert AND last-after-insert

You don't need a custom function to get the last insert id , there is already one built into both php mysqli and php PDO extensions .
As far I know , the last insert id is session aware , meaning you will get the last insert from the current insert requests only .
Get last inset id using PHP PDO
$pdo->lastInsertId();
Get last insert id using mysqli
$mysqli->insert_id;
$pdo and $mysqli are the connection variables

Related

PHP insert multiple array into MySQL database

I have add/remove input box using jQuery for add video link and add into database like this:
<input name="video[]" class="" value="" />
<input name="video[]" class="" value="" />
I check and filter empty value than insert not empty value into my database like this:
$id = mysql_insert_id();
foreach(array_filter($_POST['video']) as $video_url) {
if (!empty($video_url)) {
$value['video_data'] = serialize((array(
array_filter($_POST['video'])
)));
SQL::insert("INSERT INTO " . NEWS_FILES . " (url, id,type) VALUES (?, ?, ?)", $value['video_data'], $id, "video");
}
}
Now, in database I see two row for id:
BUT, I need to insert one row for each id.
How do can I fix this ?
edit:
$id = mysql_insert_id();
Have you marked the id field in the database table as Auto Increment or not?
Because as per the current code, the $id is not updated anywhere. So it assumes the default value and inserts.
I would suggest to initialize $id before starting the foreach loop and then doing an increment after the SQL statement is executed
SQL::insert("INSERT INTO " . NEWS_FILES . " (url, id,type) VALUES (?, ?, ?)", $value['video_data'], $id, "video");
$i++;
You must create array values by php
$ar = new array();
$ar[]= null;
You submit form data multipart load
insert command by mysqldata
"Insert data into table db "
" for numbers all rows";
If you dont have auto increment of id, you can use
$id = "select max(id) from " .NEWS_FILES ; // execute sql and get maxid
than in your foreach add at a top $id++;

How to grab an auto incremented variable and insert it into an insert query

I am trying to do a couple of php insert queries into a relational database, but I am running into a bit of an issue. In order for this relation to work I need to grab the autoincremented value from the first query and then insert it into the second query so the relation between the two exists.
I have this:
$query2 = "INSERT into words values ('' ,'$name') ";
-- The first value listed as '' is the auto-incremented primary key --
$query3 = "INSERT into synonyms values ('' , '', $alias') ";
-- The first value listed is the auto incremented pk, the second value needs to be the fk or the pk from the first query, but I don't know how to place it there. --
Is there a way to do this? Any help would be appreciated.
Here an SQL Fiddle to help y'all out:
http://sqlfiddle.com/#!2/47d42
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO words(word) values ('word1')");
$last_id = mysql_insert_id();
mysql_query("INSERT INTO words(synonym_id,synonym) values ($last_id, "synonym1)");
?>
Reference: http://php.net/manual/en/function.mysql-insert-id.php
. . You should consider using PDO in most recent PHP versions for its modern features, such as prepared statements, so that you don't need to worry about SQL Injection or broken escaping functions.
. . Using transactions is also advisable if the follow up queries are mandatory for the record to be useful. Using transactions keeps your database clear of the garbage of any failed second or third queries.
. . Also, you can omit the Auto-Increment field when running the Insert Query if you list the other fields after the table name. I think it's a much more common pattern, like INSERT INTO table (field1, field2) VALUES ("value1", "value2"). I used it in the example below:
$pdo = new PDO('mysql:host=localhost;dbname=database', 'user', 'pass');
$pdo->beginTransaction();
try {
$prepared = $dbh->prepare('INSERT INTO words (fieldName) values (?)');
$prepared->execute(array($name));
$fID = $pdo->lastInsertId();
$prepared = $dbo->prepare('INSERT INTO synonyms (fieldName) Values (?, ?)';
$prepared->execute(array($fID, $alias));
$dbo->commit();
} catch(PDOExecption $e) {
$dbo->rollback();
print 'Error: '. $e->getMessage();
}
. . Note that this will not work with MSSQL as it doesn't support "lastInsertId".
. . Amplexos.
not sure if you're using MySQL native functions or not. If so the answer is to use mysql_last_id(). These functions are deprecated and are not adivsable to use.
EXAMPLE:
//escape your indata
$brand= mysql_real_escape_string($_POST['brand']);
$sql = "INSERT INTO cars(brand) VALUES('{$brand}')";
mysql_query($sql);
//find last id from query above
$id = mysql_last_id();
Try PDO instead:
PDO::lastInsertId
EXAMPLE:
$brand= $_POST['brand'];
$sql = "INSERT INTO cars(brand) VALUES (:brand)";
$query = $conn->prepare($sql);
$query ->execute(array(':brand'=>$brand));
$id = $conn->lastInsertId();
http://www.php.net/manual/en/book.pdo.php

Pull Column Data with PDO

Okay I have been able to pull a random account and pull one account as long as I predefine it but now im curious as to how to pull a account based on the Account Number
So basicly if the account number matches pull all the data for that row.
$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db'] ['dbname'], $config['db']['username'], $config['db']['password']);
$AccountNumber = "uwoi1002"
$query = $db->query("SELECT `content`.`ProfilePic` FROM `content`");
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$Hello = $row['ProfilePic'];
echo '<html><img src="http://www.MYDOMAIN.COM/Content/';
echo $Hello;
echo '"></html>';
}
?>
So what this is doing is returning everyones profile pics on one page Not quite what I want
I have it where in a feild on my mysql data base it has a unique Id for each account I would like it to randomly pic one of those then return all the data for that row
FirstName
LastName
Gender
City
State
FacebookUrl
BirthMonth
BirthDay
BirthYear
AccountNumber - This is the one I want to pull based on
ProfilePic
ProfilePicCaption
So basically pick a random row and pull all the data instead of displaying all the data for one column
Thank you any and all help is awesome and at least now im using secure code
It sounds like you jsut need a WHERE clause...
// the ?, called a placeholder will have the value substituted for it
$stmt = $db->prepare("SELECT `content`.`ProfilePic` FROM `content` WHERE id = ?");
// an array of values for the placeholders in the query
$stmt->execute(array(2));
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))) {
// do stuff with data
}
Alternatively if you can use named placeholders which i would recommend if you have a query with lots of parameters:
// the :id, called a placeholder will have the value substituted for it
$stmt = $db->prepare("SELECT `content`.`ProfilePic` FROM `content` WHERE id = :id");
// an array of values for the placeholders in the query
$stmt->execute(array(':id' => 2));

Grab the last insert id from one table to put into another table

probably a simple one for you developers out there
I have this code to insert an order_id and order_name into the 'orders' table:
<?php
// start the session handler
require_once('dbfunction.php');
//connect to database
$conn = DB();
require_once('header.php');
//should we process the order?
if (isset($_POST['process'])) {
$order_name = $_POST['order_name'];
//create initial order
$stmt = $conn2->prepare("INSERT INTO orders (order_name) VALUES (?)");
//bind the parameters
$stmt->bind_param('s', $order_name);
// Execute query
$stmt->execute();
I now want to insert the order items into the order_items table and I cant seem to keep that same ID that was created when inserting into the 'orders' table and add it to the 'order_items' table along with the order_items. Here is my code:
//this gets the most recent auto incremented ID from the database - this is the order_id we have just created
$order_id = mysql_insert_id();
//loop over all of our order items and add to the database
foreach ($_SESSION['order'] as $item) {
$prod_id = $item['prod_id'];
$quantity = $item['quantity'];
$prod_type = $item['prod_type'];
$stmt = $conn2->prepare("INSERT INTO order_items (order_id, prod_id, quantity, prod_type) VALUES (?, ?, ?, ?)");
//bind the parameters
$stmt->bind_param('iiis', $order_id, $prod_id, $quantity, $prod_type);
// Execute query
$stmt->execute();
}
echo "<p class='black'>Order Processed</p>";
I would guess it's because whatever database library you are using is doing something to invalidate the mysql_insert_id (assuming it's even using the mysql functions). I'd suggest you look into the library to find out what method they suggest you use instead.
SQL Server has ##IDENTITY
It looks like mySQL has LAST_INSERT_ID();
My guess is you are using mySQL. If not, then please let me know the version so I can update

PHP/MySQL insert row then get 'id'

The 'id' field of my table auto increases when I insert a row. I want to insert a row and then get that ID.
I would do it just as I said it, but is there a way I can do it without worrying about the time between inserting the row and getting the id?
I know I can query the database for the row that matches the information that was entered, but there is a high change there will be duplicates, with the only difference being the id.
$link = mysqli_connect('127.0.0.1', 'my_user', 'my_pass', 'my_db');
mysqli_query($link, "INSERT INTO mytable (1, 2, 3, 'blah')");
$id = mysqli_insert_id($link);
See mysqli_insert_id().
Whatever you do, don't insert and then do a "SELECT MAX(id) FROM mytable". Like you say, it's a race condition and there's no need. mysqli_insert_id() already has this functionality.
Another way would be to run both queries in one go, and using MySQL's LAST_INSERT_ID() method, where both tables get modified at once (and PHP does not need any ID), like:
mysqli_query($link, "INSERT INTO my_user_table ...;
INSERT INTO my_other_table (`user_id`) VALUES (LAST_INSERT_ID())");
Note that Each connection keeps track of ID separately (so, conflicts are prevented already).
The MySQL function LAST_INSERT_ID() does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id() does the same as calling SELECT LAST_INSERT_ID() with mysql_query().
As to PHP's website, mysql_insert_id is now deprecated and we must use either PDO or MySQLi (See #Luke's answer for MySQLi). To do this with PDO, proceed as following:
$db = new PDO('mysql:dbname=database;host=localhost', 'user', 'pass');
$statement = $db->prepare('INSERT INTO people(name, city) VALUES(:name, :city)');
$statement->execute([':name' => 'Bob', ':city' => 'Montreal']);
echo $db->lastInsertId();
As #NaturalBornCamper said, mysql_insert_id is now deprecated and should not be used. The options are now to use either PDO or mysqli. NaturalBornCamper explained PDO in his answer, so I'll show how to do it with MySQLi (MySQL Improved) using mysqli_insert_id.
// First, connect to your database with the usual info...
$db = new mysqli($hostname, $username, $password, $databaseName);
// Let's assume we have a table called 'people' which has a column
// called 'people_id' which is the PK and is auto-incremented...
$db->query("INSERT INTO people (people_name) VALUES ('Mr. X')");
// We've now entered in a new row, which has automatically been
// given a new people_id. We can get it simply with:
$lastInsertedPeopleId = $db->insert_id;
// OR
$lastInsertedPeopleId = mysqli_insert_id($db);
Check out the PHP documentation for more examples: http://php.net/manual/en/mysqli.insert-id.php
I just want to add a small detail concerning lastInsertId();
When entering more than one row at the time, it does not return the last Id, but the first Id of the collection of last inserts.
Consider the following example
$sql = 'INSERT INTO my_table (varNumb,userid) VALUES
(1, :userid),
(2, :userid)';
$sql->addNewNames = $db->prepare($sql);
addNewNames->execute(array(':userid' => $userid));
echo $db->lastInsertId();
What happens here is that I push in my_table two new rows. The id of the table is auto-increment. Here, for the same user, I add two rows with a different varNumb.
The echoed value at the end will be equal to the id of the row where varNumb=1, which means not the id of the last row, but the id of the first row that was added in the last request.
An example.
$query_new = "INSERT INTO students(courseid, coursename) VALUES ('', ?)";
$query_new = $databaseConnection->prepare($query_new);
$query_new->bind_param('s', $_POST['coursename']);
$query_new->execute();
$course_id = $query_new->insert_id;
$query_new->close();
The code line $course_id = $query_new->insert_id; will display the ID of the last inserted row.
Hope this helps.
Try like this you can get the answer:
<?php
$con=mysqli_connect("localhost","root","","new");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO new values('nameuser','2015-09-12')");
// Print auto-generated id
echo "New record has id: " . mysqli_insert_id($con);
mysqli_close($con);
?>
Have a look at following links:
http://www.w3schools.com/php/func_mysqli_insert_id.asp
http://php.net/manual/en/function.mysql-insert-id.php
Also please have a note that this extension was deprecated in PHP 5.5 and removed in PHP 7.0
I found an answer in the above link http://php.net/manual/en/function.mysql-insert-id.php
The answer is:
mysql_query("INSERT INTO tablename (columnname) values ('$value')");
echo $Id=mysql_insert_id();
Try this... it worked for me!
$sql = "INSERT INTO tablename (row_name) VALUES('$row_value')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
$msg1 = "New record created successfully. Last inserted ID is: " . $last_id;
} else {
$msg_error = "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Another possible answer will be:
When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.
By this method, you don't have to worry about the id, it'll be made automatically.
For example (taken from w3schools )
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)
Hope this will be helpful for someone.
Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

Categories