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)
Related
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;
I am trying to insert data into a database after the user clicks on a link from file one.php. So file two.php contains the following code:
$retrieve = "SELECT * FROM catalog WHERE id = '$_GET[id]'";
$results = mysqli_query($cnx, $retrieve);
$row = mysqli_fetch_assoc($results);
$count = mysqli_num_rows($results);
So the query above will get the information from the database using $_GET[id] as a reference.
After this is performed, I want to insert the information retrieved in a different table using this code:
$id = $row['id'];
$title = $row['title'];
$price = $row['price'];
$session = session_id();
if($count > 0) {
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
The first query $retrieve is working but the second $insert is not. Do you have an idea why this is happening? PS: I know I will need to sanitize and use PDO and prepared statements, but I want to test this first and it's not working and I have no idea why. Thanks for your help
You're not executing the query:
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
it needs to use mysqli_query() with the db connection just as you did for the SELECT and make sure you started the session using session_start(); seeing you're using sessions.
$insert = "INSERT INTO table2 (id, title, price, session_id)
VALUES('$id', '$title', '$price', '$session');";
}
$results_insert = mysqli_query($cnx, $insert);
basically.
Plus...
Your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
If that still doesn't work, then MySQL may be complaining about something, so you will need to escape your data and check for errors.
http://php.net/manual/en/mysqli.error.php
Sidenote:
Use mysqli_affected_rows() to check if the INSERT was truly successful.
http://php.net/manual/en/mysqli.affected-rows.php
Here's an example of your query in PDO if you'req planning to use PDO in future.
$sql = $pdo->prepare("INSERT INTO table2 (id, title, price, session_id) VALUES(?, ?, ?, ?");
$sql->bindParam(1, $id);
$sql->bindParam(2, $title);
$sql->bindParam(3, $price);
$sql->bindParam(4, $session_id);
$sql->execute();
That's how we are more safe.
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')";
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();
Is this possible if I want to insert some data into two tables simultaneously?
But at table2 I'm just insert selected item, not like table1 which insert all data.
This the separate query:
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
Can I insert COUNT(model) at table2?
I have found some script, could I use this?
$sql = "INSERT INTO table1(model, serial, date, time, qty) VALUES ('star', '0001', '2010-08-23', '13:49:02', '10')";
$result = mysql_query($sql,$conn);
if(isset($model))
{
$model = mysql_insert_id($conn);
$sql2 = "INSERT INTO table2(model, date, qty) VALUES ('star', '2010-008-23', '10')";
$result = mysql_query($sql,$conn);
}
mysql_free_result($result);
The simple answer is no - there is no way to insert data into two tables in one command. Pretty sure your second chuck of script is not what you are looking for.
Generally problems like this are solved by ONE of these methods depending on your exact need:
Creating a view to represent the second table
Creating a trigger to do the insert into table2
Using transactions to ensure that either both inserts are successful or both are rolled back.
Create a stored procedure that does both inserts.
Hope this helps
//if you want to insert the same as first table
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (one,two, three) VVALUES('$one','$two','$three')";
$result = #mysql_query($qry2);
//or if you want to insert certain parts of table one
$qry = "INSERT INTO table (one, two, three) VALUES('$one','$two','$three')";
$result = #mysql_query($qry);
$qry2 = "INSERT INTO table2 (two) VALUES('$two')";
$result = #mysql_query($qry2);
//i know it looks too good to be right, but it works and you can keep adding query's just change the
"$qry"-number and number in #mysql_query($qry"")
its cant be done in one statment,
if the tables is create by innodb engine , you can use transaction to sure that the data insert to 2 tables
<?php
if(isset($_POST['register'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$website = $_POST['website'];
if($username == NULL OR $password == NULL OR $email == NULL OR $website == NULL) {
$final_report2.= "ALERT - Please complete all fields!";
} else {
$create_chat_user = mysql_query("INSERT INTO `chat_members` (`id` , `name` , `pass`) VALUES('' , '$username' , '$password')");
$create_member = mysql_query("INSERT INTO `members` (`id`,`username`, `password`, `email`, `website`) VALUES ('','$username','$password','$email','$website')");
$final_report2.="<meta http-equiv='Refresh' content='0; URL=login.php'>";
}
}
?>
you can use something like this. it works.
In general, here's how you post data from one form into two tables:
<?php
$dbhost="server_name";
$dbuser="database_user_name";
$dbpass="database_password";
$dbname="database_name";
$con=mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to the database:' . mysql_error());
$mysql_select_db($dbname, $con);
$sql="INSERT INTO table1 (table1id, columnA, columnB)
VALUES (' ', '$_POST[columnA value]','$_POST[columnB value]')";
mysql_query($sql);
$lastid=mysql_insert_id();
$sql2=INSERT INTO table2 (table1id, table2id, columnA, columnB)
VALUES ($lastid, ' ', '$_POST[columnA value]','$_POST[columnB value]')";
//tableid1 & tableid2 are auto-incrementing primary keys
mysql_query($sql2);
mysql_close($con);
?>
//this example shows how to insert data from a form into multiples tables, I have not shown any security measures