How to select the last inserted ID on concatenated values - php

I'm trying to get the last inserted id of multiple inserted rows.
record_id is auto increment
$sql = "INSERT INTO records (record_id, user_id, status, x) values ";
$varray = array();
$rid = $row['record_id'];
$uid = $row['user_name'];
$status = $row['status'];
$x = $row['x'];
$varray[] = "('$rid', '$uid', '$status', '$x')";
$sql .= implode(',', $varray);
mysql_query($sql);
$sql2 = "INSERT INTO status_logs (id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES";
$varray2[] = "(' ', mysql_insert_id(), '$status', '$uid', '$x')";
$sql2 .= implode(',', $varray2);
mysql_query($sql2);
This is the result:
INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', INSERT INTO records (record_id, user_id, notes, x) values ('', '1237615', 'this is a note', 'active')
INSERT INTO status_logs (log_id, record_id, status_id, date, timestamp, notes, user_id, x) VALUES('', mysql_insert_id(), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active'), '1', '2013:05:16 00:00:01', '', this is a note'', '1237615', 'active')
There is no value for mysql_insert_id().

You're mixing php function mysql_insert_id() and SQL INSERT statement syntax.
Either use MySQL function LAST_INSERT_ID() in VALUES clause of INSERT statement
INSERT INTO records (user_id, notes, x) VALUES('1237615', 'this is a note', 'active');
INSERT INTO status_logs (record_id, status_id, date, timestamp, notes, user_id, x)
VALUES(LAST_INSERT_ID(), '1', ...);
^^^^^^^^^^^^^^^^^
or retrieve the last inserted id by making a separate call to mysql_insert_id() right after first mysql_query(). And then use that value when you as a parameter to your second query.
$sql = "INSERT INTO records (user_id, ...)
VALUES(...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
$last_id = mysql_insert_id();
// ^^^^^^^^^^^^^^^^^^
$sql2 = "INSERT INTO status_logs (record_id, ...)
VALUES $last_id, ...)";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error()); //TODO beter error handling
}
Note:
You don't need to specify auto_incremented column in column list. Just omit it.
Use at least some sort of error handling in your code
On a side note: Instead of interpolating query strings and leaving it wide open to sql-injections consider to use prepared statements with either mysqli_* or PDO.

Unless I mis-reading your code, you're calling the PHP function mysql_insert_id from within the SQL?
What you need to do is grab that into a PHP variable first, then use the variable in the SQL. Something like this:
// Run the first query
mysql_query($sql);
// Grab the newly created record_id
$recordid= mysql_insert_id();
Then in the second INSERTs just use:
$varray2[] = "(' ', $recordid, '$status', '$uid', '$x')";

Related

Get largest value from mySQL table and increase by one

I am looking to add a function that will get the largest number from a specific column in a table and add to it before doing an INSERT query. (I cant have it be auto increment as several entries need to have the same value this is controlled through an if statement) however it isnt doing this and isn't increasing it by 1 based off the highest value.
$max = "SELECT MAX(LocationID) FROM boss";
$result = mysqli_query($connection, $max);
$locID = $result+1;
$query = "INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty) VALUES ('0', '$boss', '$type', '$loc', '$locID', '$diff')";
You don't need to use two queries for this, you can do it in the INSERT query.
$query = "INSERT INTO boss (ID, Name, Type, Location, LocationID, Difficulty)
SELECT '0', '$boss', '$type', '$loc', MAX(locationID)+1, '$diff'
FROM boss";
You forgot to fetch the result
$max = "SELECT MAX(LocationID) as m FROM boss";
$result = mysqli_query($connection, $max);
$result = mysqli_fetch_array($result);
$locID = $result[0]+1;

writing fetch_assoc() array data to table

What is the proper way to reference the array components from fetch_assoc() so that they can be inserted into another table?
Here is my current code:
$sql_read = "SELECT id, data1, data2, date FROM `table1`";
$result = $mysqli->query($sql_read);
if ($result !== false) {
$rows = $result->fetch_all();
}
while ($row = $result->fetch_assoc()){
$sql_write = "INSERT INTO `table2`.`load_records` (`id`, `data1`,`data2`,`date`) VALUES ('.$row['id']', '.$row['data1']', '.$row['data2']', '.$row['date']', NULL);";
}
As suggested in my comment, first your select statement should be:
"SELECT id, data1, data2, date FROM `table1`";
Furthermore, the insert statement should be (see the use of concatenation of strings):
"INSERT INTO `table2`.`load_records` (`id`, `data1`,`data2`,`date`) VALUES ('".$row['id']."', '".$row['data1']."', '".$row['data2']."', '".$row['date']."', NULL);";
There are some errors in your script, as already pointed out.
But you might also be interested in the INSERT INTO ... SELECT variant of the INSERT syntax.
<?php
$query = '
INSERT INTO
table2
(`id`, `data1`,`data2`,`date`)
SELECT
`id`, `data1`,`data2`,`date`
FROM
table1
';
$result = $mysqli->query($query);
if ( !$result ) {
trigger_error('error: ' . $mysqli->error, E_USER_ERROR);
}
else {
echo $mysqli->affected_rows, ' rows have been transfered';
}
You have an extra field in the VALUES that is not referenced in the INTO and the concatenation of the row data is incorrect;
$sql_write = "INSERT INTO `table2`.`load_records`
(`id`, `data1`,`data2`,`date`)
VALUES ('.$row['id'].', '.$row['data1']', '.$row['data2']', '.$row['date']', NULL);";
should be:
$sql_write = "INSERT INTO `table2`.`load_records`
(`id`, `data1`,`data2`,`date`)
VALUES ('".$row['id']."', '".$row['data1']."', '".$row['data2']."', '".$row['date']."');";
Or you need to update the INTO to include an extra column that accepts NULL
See also:
The PHP reference on mysqli_result::fetch_assoc

Can't get mysql_insert_id() method to grab value I need

I'm trying to grab SID from the insert into the first table (stories) so I can insert that SID into the writing table in my second insert.
I think the way to do this is with mysql_insert_id(); after the first query, but the primary key that auto-increments is called SID. If mysql_insert_id() could grab that value I'd be all set.
What I am finding from a var_dump is that the $SID = mysql_insert_id(); is just returning the value "0" and I'm not sure why.
There is a column called ID in stores, but if it was grabbing that, the value would be "1". Either way, I wish this method could be written as mysql_insert_SID();
Any idea what I am doing wrong or how I can fix this? And yes, I know this is a deprecated approach, but first I want to figure out how before I worry about converting to PDO.
// Get values from form
$category = $_POST['category'];
$genre = $_POST['genre'];
$story_name = $_POST['story_name'];
$text = $_POST['text'];
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query);
$SID = mysql_insert_id();
$SID2 = "select stories.SID from stories where stories.SID=$SID";
$query2 = "INSERT INTO writing (ID, SID, text, position, approved)
VALUES('$user_ID', '$SID2', '$text', '1','N')";
$result = mysql_query($query2);
Retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
(http://php.net/manual/en/function.mysql-insert-id.php)
But you aren't executing any query (via mysql_query()). You're just assigning your query to a variable. Try following:
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
mysql_query($query);
$SID = mysql_insert_id();
I think you've forgotten to execute the query most probably?
Try
$SID = mysql_insert_id();
after executing the query
$query = "INSERT INTO stories (ID, category, genre, story_name, active) VALUES
('$user_ID', '$category', '$genre','$story_name', '1')";
$result = mysql_query($query); // executing
$SID = mysql_insert_id(); // order of queries is important
If you cannot get the value through mysql_insert_id() then try SELECT LAST_INSERT_ID(). Of course there will be a value if you have executed an insert query with AUTOINCREMENT (which you haven't done yet)

Where is the error in my sql code

$fname = addslashes($fname);
$lname = addslashes($lname);
$dob = addslashes($dob);
$email = $_POST['email'];
$sql =
"INSERT INTO subscriber
(fname, lname, dob)
VALUES
('".$fname."', '".$lname."', '".$dob."')
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");
I am getting error in sql query "insertion error". Query is inserting data into DB after removing WHERE statement. What is the error.
You can't use where in an insert statement. You might be thinking of an update instead?
$sql = "update subscriber set fname='".$fname."', lname = '".$lname."', dob = '".$dob."' WHERE email='".$email."'";
If your email is a unique value, you can also combine an insert with an update like this:
insert into
subscriber (fname, lname, dob, email)
values ('".$fname."', '".$lname."', '".$dob."', '".$email."')
on duplicate key update set fname='".$fname."', lname='".$lname."', dob='".$dob."'
This second syntax will insert a row if there isn't one with a matching email (again, this has to be set to a unique constraint on the table) and if there is one there already, it will update the data to the values you passed it.
Basically INSERT statement cannot have where. The only time INSERT statement can have where is when using INSERT INTO...SELECT is used.
The only syntax for select statement are
INSERT INTO TableName VALUES (val1, val2, ..., colN)
and
INSERT INTO TableName (col1, col2) VALUES (val1, val2)
The other one is the
INSERT INTO tableName (col1, col2)
SELECT col1, col2
FROM tableX
WHERE ....
basically what it does is all the records that were selected will be inserted on another table (can be the same table also).
One more thing, Use PDO or MYSQLI
Example of using PDO extension:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
?>
this will allow you to insert records with single quotes.
Oops !!!! You cannot use a WHERE clause with INSERT statement ..
If you are targeting a particular row then please use UPDATE
$sql = "Update subscriber set fname = '".$fname."' , lname = '".$lname."' , dob = '".$dob."'
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");

How to insert the same UUID in two rows of two different tables

I try next script:
// Insert data into mysql
$qry="INSERT INTO $tbl_name1 (ID, REFERENCE, CODE, NAME) VALUES (UUID(), '$REFERENCE', '$CODE', '$NAME')";
$result=mysql_query($qry);
$qry2="INSERT INTO $tbl_name2 (PRODUCT) VALUES ('$ID')"; <--- Here is a problem
$result=mysql_query($qry2)
I do not know how two insert the same UUID in two tables simultanoiusly. Please help me!
I will appreciate much your support!
DONE!!!
THE WORKING SCRIPT:
$q = "SELECT UUID() AS uid";
$res = mysql_query($q) or die('q error: '.mysql_error());
$row = mysql_fetch_assoc($res);
// Insert data into mysql
$qry="INSERT INTO $tbl_name1 (ID, REFERENCE, CODE, NAME) VALUES ('".$row['uid']."', '$REFERENCE', '$CODE', '$NAME')";
$result=mysql_query($qry) or die('err 034r '.mysql_error());
$qry2="INSERT INTO $tbl_name2 (PRODUCT) VALUES ('".$row['uid']."')";
$result=mysql_query($qry2) or die('gg2345 '.mysql_error());
Just do SELECT UUID() before you send the INSERTs and put the values into the statements in PHP. Something like this (untested):
$result = mysql_query("SELECT UUID() AS UUID") or die('SQL error: ' . mysql_error());
$row = mysql_fetch_assoc($result);
$UUID = $row["UUID"];
$qry="INSERT INTO $tbl_name1 (ID, REFERENCE, CODE, NAME) VALUES ('$UUID', '$REFERENCE', '$CODE', '$NAME')";
$result=mysql_query($qry);
$qry2="INSERT INTO $tbl_name2 (PRODUCT) VALUES ('$UUID ')"; <--- Here is a problem
$result=mysql_query($qry2)
Another way would be the use of a user-defined variable (see SQL Fiddle):
SET #UUID = (SELECT UUID() AS UUID);
INSERT INTO test1 VALUES(#UUID, "foo");
INSERT INTO test1 VALUES(#UUID, "bar");
Assuming the ID is the table Unique Index you could add before $qry2:
$ID = mysql_insert_id();

Categories