I have a MYSQL table called 'Buyers'. I am taking form data and inserting it into the table on a page called insert.php.
Now, along with the column names for the form fields, I have an Auto-increment ID column in the table. What I want is; once I send the form data to the table, I want to then execute some SQL to get the ID number for the row into which I just inserted the data into.
E.g, I have the SQL:
INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]');
This will create a row in the 'Buyers' table with the data from form fields 'name', 'email' and 'job'.
This row will have an ID number generated by Auto Increment.
How, then, can I then select that exact ID number? Is there some way to select the most recent row in the table, since that is the row which contains the ID number I want?
Mysqli : mysqli_insert_id()
<?php
mysqli_query($con,"INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]')");
$last_id = mysqli_insert_id($con);
?>
PDO : PDO::lastInsertId()
<?php
$stmt = $con->prepare("INSERT INTO Buyers (name, email, job) VALUES (?,?,?)");
$stmt->bind_param("sss", $_POST['name'], $_POST['email'], $_POST['job']);
$stmt->execute();
$last_id = $con->lastInsertId();
?>
Assuming $con as connection.
Mysql : mysql_insert_id()
<?php
mysql_query("INSERT INTO Buyers (name, email, job) VALUES ('$_POST[name]', '$_POST[email]', '$_POST[job]')");
$last_id = mysql_insert_id();
?>
NOTE: [The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead ]
SELECT x.*
FROM messages x
JOIN
( SELECT from_id, MAX(time_sent) time_sent GROUP BY from_id ) y
ON y.from_id = x.from_id
AND y.time_sent = x.time_sent;
The last part of this puzzle is left as an exercise for the reader.
Use mysql_insert_id() to retrive ID. More details - http://php.net/manual/en/function.mysql-insert-id.php
Related
I have a table which contains pageid, department, position and active. While updating, I have to update active column if pageid is already exists, if not I will insert a new row with the pageid.
I am getting pageid values through checkbox and my update query is like this
$sql = "INSERT INTO access_level (page_id, department, position, active)
VALUES (".$sn.", ".$department.", ".$position.", 1)
ON DUPLICATE KEY UPDATE
department=VALUES(".$department."),
position=VALUES(".$position."),
active=VALUES(1)";
But everything is getting inserted twice in this case.
Where I am doing wrong? Can somebody guide me?
This should probably work for you:
$sql = "INSERT INTO access_level (page_id, department, position, active)
VALUES (".$sn.", ".$department.", ".$position.", 1)
ON DUPLICATE KEY UPDATE
id=LAST_INSERT_ID(id),
active=VALUES(1)";
I have to insert from table 1 into table 2 the values of username, name, lastname, roomnum and dormID.
I have to insert into table 2 the current date of today(it changes everyday), comments(the user wishes to enter- this is a textbox) and the attendance(present, absent, late)(these are the checkboxes).
When trying to click on the submit button the only thing that inserts into the database is the records that I am pulling from table1 into table 2.
When i try to incorporate to also insert the date, latecomments(textbox), and the attendance(checkboxes) it does not store any record.
This are the inserts:
$checkbox1 = $_POST['chk1'];
$latecomment=trim($_POST['latecomment']);
$d=strtotime("today");//todays date
$day=date("Y-m-d", $d);//date format
if($_POST["Submit"]=="Submit"){
for ($i=0; $i < sizeof ($checkbox1); $i++){
$query="Insert into dailyattendance (attendance) VALUES ('".$checkbox1[$i]."')";
mysql_query($query);
$daily=mysql_query("INSERT INTO dailyattendance(username, name, lastname, roomnum, dormID) SELECT user.username, user.name, user.lastname, user.roomnum, user.dormID FROM user WHERE user.role='Student'" );
$otherinfo=mysql_query("INSERT INTO daily attendance set date='".$day."', latecomment='".$latecomment."' WHERE dailyid=''");
}
}
There's a blank in your table name (in your given code):
INSERT INTO daily attendance
There's a WHERE clause in your INSERT statement and you are using UPDATE syntax with SET:
INSERT INTO daily attendance set date='".$day."', latecomment='".$latecomment."' WHERE dailyid=''");
Question: Is there a column named "attendance" in your table?
You should use only one INSERT statement if you want to add one row with all columns.
To clearify it a bit here is a code example you could start with. The SELECT on user is once before the loop because it seems to be same data all the time. You should add a function to escape strings before using them in the SQL statement to avoid errors when quotes are in it. Have a look at PHP or SQL error messages if something went wrong.
if($_POST["Submit"]=="Submit"){
$sql = "SELECT username, name, lastname, roomnum, dormID FROM user WHERE user.role='Student'";
$result = mysql_query($sql);
$student = mysql_fetch_assoc($result);
for($i=0; $i < sizeof ($checkbox1); $i++){
$sql = "INSERT INTO dailyattendance (username, name, lastname, roomnum, dormID, attendance, date, latecomment)";
$sql.= " VALUES ('".$student["username"]."', '".$student["name"]."', '".$student["lastname"]."', '".$student["roomnum"]."', '".$student["dormID"]."'";
$sql.= ", '".$checkbox1[$i]."', now(), '".$latecomment."')";
mysql_query($sql);
}
}
I am working on an events calendar using PHP and MySQL (V5.1) where the admin would add an event, and then an attendance list for that event would be created as well. I have three tables: events, attendance and members. So far I can create the event using information that is entered thorugh a PHP form. I'm trying to update the attendance table by inserting the event id from the event that has just been created, as well as pulling in the list of members (using their member ID) from the members table. Nothing is being added to attendance the table though. Can someone let me know what I should I be doing differently?
Some of the fields I am using in the tables:
Events: event_ID (Primary key, auto-increment), name, location, date
Attendance: attendance_ID (Primary key, auto-increment), event_ID, member_ID, attending
Members: member_ID (Primary key, auto-increment), name, email
enter code here
Here is the code:
mysql_query("SET AUTOCOMMIT=0");
mysql_query("START TRANSACTION");
$query1 = mysql_query("INSERT INTO events (name , location , date) VALUES ('".mysql_real_escape_string($name)."' , '".mysql_real_escape_string($location)."' , '".mysql_real_escape_string($date)."')");
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) SELECT LAST_INSERT_ID(), members.member_ID FROM members");
if ($query1 and $query2) {
mysql_query("COMMIT");
} else {
mysql_query("ROLLBACK");
}
You could use mysql_insert_id()
$query1 = mysql_query("INSERT INTO events (name , location , date) VALUES ('".mysql_real_escape_string($name)."' , '".mysql_real_escape_string($location)."' , '".mysql_real_escape_string($date)."')");
$insert_id = mysql_insert_id() ;
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) SELECT {$insert_id}, members.member_ID FROM members") ;
A couple of important points. First, if you getting your last insert ID you should execute LOCK and UNLOCK queries first:
LOCK TABLES events WRITE;
UNLOCK TABLES
Second, you can use the mysqli_insert_id() method to get the ID of the last insert. This means that you must have an AUTO_INCREMENT field in the table you are inserting.
Put VALUES into $query2 to form a correct SQL-statement:
$query2 = mysql_query("INSERT INTO attendance (event_ID , member_ID) **VALUES (**SELECT LAST_INSERT_ID(), members.member_ID FROM members");
i have a form where i post the data to mysql. the query should insert the data from the form into table1, but also include data from another table2 where the ID that is send from the form is equal to the ID in table2?
i use the old mysql connection, i know, not the best :-) and php!
hope someone can help, thanks :-)
Martin
think maybe I should give some more info :-)
table1 is called: books
from the form, i have the following value: itemCode, itemQty, ownerID
i have 2 static value: status, type
the values from table2 that must be inserted into table1 is:
title, description, price, frontcover
from table2 the field isbn should be equal to itemCode from form.
here is what i have tried so far:
$bookid=$_POST['itemCode'];
$itemQty=$_POST['itemQty'];
$status='2';
$ownerID = $user->id;
$query="INSERT INTO books (name, description, price, picture, status, ownerID, itemqty, type, studie, isbn) SELECT (title, description, price, frontcover FROM isbnbooks WHERE isbn=$itemCode), $status, $ownerID, $itemQty, '1', '1', $bookid)";
UPDATE:
I have also tried this one here:
$bookid=$_POST['itemCode'];
$itemQty=$_POST['itemQty'];
$status='2';
$ownerID = $user->id;
$data2 = mysql_fetch_array (mysql_query("SELECT * FROM isbnbooks WHERE isbn = $bookid"));
$title = $data2[title];
$description = $data2[description];
$price = $data2[price];
$picture = $data2[frontcover];
$query="INSERT INTO books (name, description, price, picture, status, ownerID, itemqty, type, studie, isbn)
VALUES ($title, $description, $price, $picture, $status, $ownerID, $itemQty, '1', '1', $bookid)";
mysql_query($query) or die("Opps some thing went wrong");
If you have values 'a' and 'b' to go into columns f1 and f2 of table1; and in f3 you want the value of table2.field where table2.id is 123, you can prepare and execute a SQL statement along these lines:
INSERT INTO table1 (f1, f2, f3)
SELECT 'a', 'b', field FROM table2 WHERE id = 123;
Further to seeing the code in your updated question, the problem with your first attempt is that you're trying to mix INSERT ... SELECT with INSERT ... VALUES; sadly they are mutually exclusive. However, you could write instead:
INSERT INTO books (
name,
description,
price,
picture,
status,
ownerID,
itemqty,
type,
studie,
isbn
)
SELECT
title,
description,
price,
frontcover,
:status, -- use prepared statements to prevent SQL injection
:ownerID, -- see http://bobby-tables.com/ for more info
:itemQty,
'1', -- do you really want a string containing a number?
'1',
:bookid
FROM isbnbooks
WHERE isbn=:itemCode;
Your second attempt looks as though it ought to work (although you really should use prepared statements, see above!); what problems are you having with it?
in the absence of code, here's the workflow id recommend:
Form is submitted -> check and sanitize values - > execute lookup query against "table 2" and get your related values -> commit the update query with both form and "table2" data -> on successful update, notify user that their information was processed -> thank them.
Something like this ? :
$data2 = mysql_fetch_array (mysql_query("SELECT * FROM table2 WHERE id2 = '1'"));
$data1 = data2['column2'];
mysql_query("INSERT INTO table1 VALUES('value1','$data2') WHERE id1 = id2);
I am trying to insert data into a table (table1) based on another (table2), the only problem is that table1 contains fields set to not allow null values. Do I need to create these fields in table2 where I am pulling the data from and populate them with a value?
Example not null field: password
If I do not include this in my query then I get an error and the record is not inserted however if I create the field in table2 then insert into my query it works fine. This seems a bit out of the ordinary. Example query below:
Example 1 (no password field in table 2):
$insert_new_records_query = "INSERT INTO table1 (first_name, last_name, email_address) ".
"SELECT firstname, lastname, email FROM table2";
This generates an error saying that I must include the password field.
Example 2 (password field in table 2):
$insert_new_records_query = "INSERT INTO table1 (first_name, last_name, password,
email_address) ".
"SELECT firstname, lastname, password = 'password1', email FROM table2";
This allows the record to be created. The problem is that I have many more fields that are not null in table 1 and I don't think I need to create them in table 2 as blank fields and insert them into my query with values just to create a record. Is there a better way to do this?
You don't have to create fields, you can simply 'select' default values. Try this instead:
INSERT INTO table1 (first_name, last_name, password, email_address)
SELECT firstname, lastname, 'password1', email FROM table2