Is there any difference between this 3 query?
query 1
$query = "INSERT INTO reserve( c_id, c_username, r_id, r_name, checkin, checkout)";
$query .= " VALUES ( $c_id, $c_username, $r_id, $r_name, $checkin, $checkout )";
query 2
$sql = "INSERT INTO reserve( c_id, c_username, r_id, r_name, checkin, checkout)
VALUES ( '$c_id' , '$c_username', '$r_id', '$r_name', '$checkin', '$checkout' )";
query 3
$result = $mysqli->query("INSERT INTO reserve (c_id, c_username, r_id, r_name, checkin, checkout) VALUES ('$c_id' , '$c_username', '$r_id', '$r_name', '$checkin', '$checkout');")
And which one should I use to select a data from my database and which one should I use to insert data into database
On a quickly glance they all appear to do the same thing. You don't need to learn parameter passing at your stage. Be aware of injection attacks and clean those variables before you do calls.
I tend to do this for readability:
$sql = "INSERT INTO reserve(c_id
,c_username
,r_id
,r_name
,checkin
,checkout)
VALUES ('$c_id'
,'$c_username'
,'$r_id'
,'$r_name'
,'$checkin'
,'$checkout')";
Related
$sql = "INSERT into x (y,z,t)
VALUES ((SELECT userID FROM users WHERE username ='".$usersql."'),"
."'"."(SELECT itemID from items WHERE category ='".$category."'),"
."'".$amountdays."')";
Thank you for your time.
You should use PDO or mysqli with prepared statements. Then you can define variables for your values and set them after the query. That makes it more readable and you prevent sql injections in your code.
https://www.php.net/manual/de/pdo.prepared-statements.php
$stmt = $dbh->prepare("INSERT into x (y,z,t)
VALUES (
SELECT userID FROM users WHERE username = :username,
SELECT itemID FROM items WHERE category = :category,
:amountdays
)";
$stmt->bindParam(':username', $username);
$stmt->bindParam(':category', $category);
$stmt->bindParam(':amountdays', $amountdays);
Something like that.
A little bit of formatting will go a long way:
$sql = "INSERT into x
(
y,
z,
t
) VALUES (
(SELECT userID FROM users WHERE username = ?),
(SELECT itemID from items WHERE category = ?),
?
);
";
This question already has answers here:
Retrieve id of each INSERT statement in multi query
(5 answers)
Closed 3 years ago.
I've been working with this project, now am stuck where i have to insert the id of the first query of which it identifies the relations of that table to others, i want the id of the first query to be saved as a variable and then be inserted into the following queries
I've tried to set value to be used but its not working, as i want all these to work in one multi-query, down here are some code of the queries
$query = "INSERT INTO guests (
user_id,
first_name,
last_name,
nationality,
status,
sign_up)
VALUES (
'$user_id',
'$first_name',
'$last_name',
'$nationality',
'$status',
NOW());";
$query = "SELECT #last_id := LAST_INSERT_ID();"
$query .= "INSERT INTO bookings (
user_id,
guest_id,
coming_from,
going_to,
date_in,
date_out,
sign_up)
VALUES (
'$user_id',
#last_id,
'$coming_from',
'$going_to',
'$date_in',
'$date_out',
NOW());";
$query .= "INSERT INTO preference (
guest_id,
prefer,
alergy,
sign_up)
VALUES (
#last_id,
'$prefer',
'$alergy',
NOW());";
$query .= "INSERT INTO rooms (
user_id,
guest_id,
room_number,
room_type,
room_price,
sign_up)
VALUES (
'$user_id',
#last_id,
'$room_number',
'$room_type',
'$room_price',
NOW())";
if(mysqli_multi_query($conn, $query))
{
echo "Guest Received successfully!";
} else {
echo "Failed! Data input error!";
}
}
i expected it to fetch the first query guest id and insert it into #last_id column, Kindly any ideas?
On occasion, I've had to use this:
SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'tablename'
or
SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_name = your_tablename' AND table_schema = DATABASE( ) ;
Perhaps that will work for you
References:
https://dev.mysql.com/doc/refman/8.0/en/show-table-status.html
https://php.net/manual/en/mysqli.insert-id.php
So I have 3 tables: donor, blood_type, user_account. I am trying to populate the donor table which contains user_id and blood_id, but there is no join between the blood_group and the user_account table so I tried this, but it didn't work. Can someone please tell what I am doing wrong? I am very new to php and databases.
<?php
if(isset($_POST['submit'])) {
$conn = mysqli_connect("localhost", "root" , "");
if(!$conn) {
die("Cannot connect: ");
}
mysqli_select_db($conn,"blood_bank_project");
$sql = "INSERT INTO user_account(username, password) VALUES ('$_POST[user]', '$_POST[psw]');";
$sql .="INSERT INTO donor(first_name,last_name,email_add,gender, birthday, telephone, city, last_donation,user_id, blood_id)VALUES('$_POST[fname]', '$_POST[lname]', '$_POST[email]', '$_POST[gender]', '$_POST[Birthday]', '$_POST[Telephone]', '$_POST[city]', '$_POST[lastdonation]')";
$sql .="UPDATE donor SET blood_id = (SELECT blood_id from blood_type where blood_group= '$_POST[bloodgroup]');";
$sql .="UPDATE donor SET user_id = (SELECT user_id from user_account where username= '$_POST[user]')";
if(mysqli_multi_query($conn, $sql)){
echo'executed';
}
}
?>
You can use a SELECT clause to produce the values for an INSERT. In this case, you can use that to select the appropriate values from the other tables.
INSERT INTO donor (user_id, blood_id, first_name,last_name,email_add,gender, birthday, telephone, city, last_donation)
SELECT u.user_id, b.blood_id,
'$_POST[fname]', '$_POST[lname]', '$_POST[email]', '$_POST[gender]', '$_POST[Birthday]', '$_POST[Telephone]', '$_POST[city]', '$_POST[lastdonation]'
FROM user_accounts AS u
CROSS JOIN blood_type AS b
WHERE u.username = '$_POST[user]' AND b.blood_group= '$_POST[bloodgroup]'
I also strongly recommend you use prepared queries instead of substituting $_POST variables, as the latter subjects you to SQL-injection. I also recommend against using mysqli_multi_query -- it's rarely needed and only makes checking for success harder. If you insert into user_accounts using a separate query, you can then use mysqli_insert_id($conn) to get the user_id assigned when you inserted into user_accounts, instead of using the above JOIN. You can also use the MySQL built-in function LAST_INSERT_ID() to get it.
$stmt = mysqli_prepare($conn, "INSERT INTO user_account(username, password) VALUES (?, ?);") or die("Can't prepare user_account query: " . mysqli_error($conn));
mysqli_stmt_bind_param($stmt, "ss", $_POST['user'], $_POST['psw']);
mysqli_execute($stmt);
$stmt2 = mysqli_prepare($conn, "
INSERT INTO donor (user_id, blood_id, first_name,last_name,email_add,gender, birthday, telephone, city, last_donation)
SELECT LAST_INSERT_ID(), b.blood_id, ?, ?, ?, ?, ?, ?, ?, ?
FROM blood_type AS b
WHERE b.blood_group= ?") or die ("Can't prepare donor query: " . mysqli_error($conn));
mysqli_stmt_bind_param($stmt2, "sssssssss", $_POST['fname'], $_POST['lname'], $_POST['email'], $_POST['gender'], $_POST['Birthday'], $_POST['Telephone'], $_POST['city'], $_POST['lastdonation'], $_POST['bloodgroup']);
mysqli_execute($stmt2);
theres a few things wrong with that code snippet:
Line 15: You've got a rogue 'w' at the start of the line before your $sql variable
All of your $_POST'ed parameters need to be in the format $_POST['parameter'] (Missing quotes, remember to escape your already quoted ones in places)
The where clause sub-select query in line 14 is selecting from a table that does not exist (blood_type)
I guess what your trying to achieve is a mapping between 'user_account' and 'donor' of which you may be better either storing a foreign key in the user account table of the 'donor_id', or a matrix/mapping table that links the two together.
The matrix/mapping table would hold the primary key date from both user_account and donor to create your matrix.
You can then get to either table information from the other knowing just one side of the information.
I'd also make sure your escaping your inbound variables in your queries to prevent any SQL Injection attacks (see here)
For my ordering system, when an admin inserts an order i need to check if the customer he inserts for the order exists in my customer table.
Im trying something like this, but with no luck..
$sql = "IF EXISTS(SELECT * FROM customer WHERE customer_id = '$customer')
THEN insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
values ('$customer', '$product', '$quantity', 'now()', '$note', '$employee')";
Error: syntax error in first line.
What is wrong here?
And is this the right approach? Is there a better way?
you might want to do it "backwards" - insert if exists:
$sql = "insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
select '$customer', '$product', '$quantity', now(), '$note', '$employee'
from dual
where EXISTS(SELECT * FROM customer WHERE customer_id = '$customer')";
Here's a neat trick you can do:
$sql = "INSERT INTO `order`
(`customer_id`, `product`, `quantity`,
`creation_time`, `order_note`, `order_employee`)
SELECT `customer_id`, '$product', '$quantity', now(), '$note', '$employee'
FROM `customer` WHERE `customer_id`='$customer'";
Note that I'm trusting you have already properly sanitised your variables!
But this will only insert the order if the customer with that ID exists.
I think you should think your problem in another way.
Proceed with steps :
1 - I need to know if customer my customer exist?
$sql = "SELECT ID FROM customer WHERE customer_id = '$customer'";
2- I try my customer, does he exist?
If(!empty($result_cust)){
$sql = insert into `order` (customer_id, product, quantity, creation_time, order_note, order_employee)
values ('$customer', '$product', '$quantity', 'now()', '$note', '$employee')";
}
With this way your code will be more easily to understand.
Divide and Rule
They said.
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')";