PLease note I am a beginner.
My situation is thus:
I am trying to run multiple queries, off the back of a dynamic form. So the data is going to end up in two different tables.
I am currently successfully storing in to my item_bank, which has an auto_increment itemId.
I then want to grab the ItemId just created on that last query and insert it into my next query of which I am also inserting an array. (I hope you can follow this)
first off, is it even possible for me to run multiple queries like this on a single page?
Below is my attempt at the queries. Currently the first query works, however I cannot get the ItemId generated from that query.
$answers is an array.
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$query = "INSERT INTO answers_tb (item_id, text_value)VALUES('$itemid',' . implode(',', $answers) . ')";
mysql_query($query) or die(mysql_error());
this is the error i get now: "Column count doesn't match value count at row 1"
To get the ID generated by an auto-increment field in PHP/MySQL just use the mysql_insert_id() function.
Edit:
// store item structure info into item_bank_tb
$query = "INSERT INTO item_bank_tb (item_type, user_id, unit_id, question_text, item_desc, item_name)
VALUES('$type','$creator','$unit','$text','$desc','$name')";
mysql_query($query) or die(mysql_error());
$itemid = mysql_insert_id();
//now store different answers
$answers = mysql_real_escape_string(implode(',', $answers));
$query = "INSERT INTO answers_tb (item_id, text_value) VALUES('$itemid','$answers')";
mysql_query($query) or die(mysql_error());
Have a look at mysql_insert_id():
// store item structure info into item_bank_tb
mysql_query($query);
$itemid = mysql_insert_id();
// now store different answers
Related
Im currently moving rows from "mycart" table to "itemorders" table.
$query = "INSERT into orders
(email,address,postalcode,contactNo,orderdate,status) values
('".$email."','".$address."','".$postalcode."','".$contactNo."','".$orderdate."','".$status."');";
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity) SELECT itemID,itemName,itemSize,itemPrice,quantity FROM mycart WHERE email='".$email."' ";
$result = mysqli_multi_query($conn,$query);
$ordersID = mysqli_insert_id($conn);
Currently, i have an additional field called ordersID in "itemorders" table, the first query also Auto increments a ordersID. I want to insert the $ordersID value that i have used in the first query into the second query. How can i do that?
Use the LAST_INSERT_ID() function in MySQL. It gets the last auto-increment ID, just as mysqli_insert_id() does.
$query .= "INSERT into itemorders (itemID,itemName,itemSize,itemPrice,quantity,orderSID)
SELECT itemID,itemName,itemSize,itemPrice,quantity, LAST_INSERT_ID()
FROM mycart
WHERE email='".$email."' ";
I'm sorry about my PHP skills, but I'm just not figuring out how to do this simple task which is INSERT a new row and save its ID into a variable.
Here's what I got:
// mysql inserting a new row
$sql = "INSERT INTO `order` (orderTitle, orderDescription, orderPrice,userID, categoryID)
VALUES('$title', '$description','$price','$userID','$category');";
$sql .= "SELECT LAST_INSERT_ID();";
$result = mysqli_multi_query($con,$sql);
$result_get_id= mysqli_next_result($con);
$row = mysqli_fetch_row($result_get_id);
$order_id = $row[0]; // <-- how to get this value??
I realized row[0] doesn't work, which is why I would like to know how to extract the LAST_INSERT_ID() value correctly.
A couple of things here...
Don't use mysqli_multi_query - it's unnecessary in your example. Use mysqli_query on the INSERT only. No need to query last insert id in SQL.
To get the last insert id, call mysqli_insert_id directly after your INSERT query. You can assign this to a variable, such as $order_id = mysqli_insert_id();
The database class you're using has built in functions for this e.g. mysqli_insert_id(), or for PDO $db->lastInsertId().
$mysqli->query("INSERT INTO order ... ");
printf ("Primary key of new record: %d.\n", $mysqli->insert_id);
http://php.net/manual/en/mysqli.insert-id.php
I'm very new to PHP, trying to figure things out.
I have the following php code:
$read_more = '[read more]';
$sql = "INSERT INTO database (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
The code is returning "http://www.example.com/index.php?id=0". Note that the "id" parameter is returning "0". My goal is to make it return the latest ID from the database, which is set to auto increment.
I've tried many things but nothing worked for me so far. Thanks!
EDIT: After hours of trial and error, this is how I was able to solve this problem:
//After connecting to the database
$sql = "INSERT INTO table (date, headline, article, read_more) VALUES ('$_POST[date]', '$_POST[headline]', '$_POST[article]', '$read_more')";
$result = mysqli_query($conn, $sql);
$id = mysqli_insert_id($conn);
Now the latest id is saved into a variable that I can use.
Try something like this instead. Check the documentation here.
// insert a datarow, primary key is auto_increment
// value is a unique key
$query = "INSERT INTO test (value) VALUES ('test')";
mysql_query( $query );
echo 'LAST_INSERT_ID: ',
mysql_query( "SELECT LAST_INSERT_ID()" ),
'<br>mysql_insert_id: ',
mysql_insert_id();
How would I go about validating this query? Currently, I getting some omissions where one row hasn't copied over so I need a bombproof method to check and correct. Query:
$query = "
SELECT *
FROM $UID
";
$result = mysql_query($query)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$q = $row['QID'];
$a = $row['answer'];
$c = $row['comment'];
$query = "
INSERT INTO a (UID, QID, answer, comment)
VALUES ('$UID', '$q', '$a', '$c')
";
mysql_query ($query)or die(mysql_error());
}
Thanks.
You can do this in a single query.
INSERT INTO a (UID, QID, answer, comment)
SELECT '$UID', QID, answer, comment FROM `$UID`
As its an atomic operation all the data will be copied in one shot. However you can still verify by using mysql_info function. It'll give output like following.
Records: 23 Duplicates: 0 Warnings: 0
Here Duplicate is the number of rows there were discarded due to duplicate key. If both Duplicates and Warning are 0 you can say query was successful.
Can I get from PHP a value back like the new id from the row I've just added to the database or should I make a SELECT to retrieve it?
<?php
$sql = "INSERT INTO my_table (column_1, column_2) VALUES ('hello', 'ciao')";
$res = mysql_query ($sql) or die (mysql_error ());
$sql = "SELECT column_id FROM my_table WHERE column_1 = 'hello'";
$res = mysql_query ($sql) or die (mysql_error ());
$row = mysql_fetch_assoc ($res);
$id = $row["column_id"];
print "my id is = $id";
?>
Use this: http://php.net/manual/en/function.mysql-insert-id.php
Selecting can be dangerous because an auto-increment often means that records may not otherwise be unique, and therefore not uniquely selectable without the id.
The proper way of getting the id is via mysql_insert_id(), as others have stated. The reason for this is that you may have other inserts taking place immediately following yours, and simply requesting the last id is not guaranteed to return the id that you expected.
$result = mysql_query("INSERT INTO tableName (col1) VALUES ('foo')");
print mysql_insert_id();
There is builtin support for it, mysql_insert_id() or something.