Insert into MySQL table from value and select statement - php

I would like to insert values into one table by selecting fields from another table and also add information such date and login_id (these do not come from the table where I am selecting).
$sql = "INSERT INTO questions_to_answer (login_id, question_id, Question_Category, QuestionType, Question, Meaning) VALUES (?,?,?,?,?,?)";
$stmt= $DB_con->prepare($sql);
$stmt->execute($test_user_id,
"SELECT question_id,
Question_Category,
QuestionType,
Question,
Meaning all_questions
WHERE personality_profile_questions.Question_Category = 1");

You need to have the SELECT in the prepare, you can't have SQL commands in the execute. If in the execute it will be treated as a literal string, quoted, and escaped.
Try:
$sql = "INSERT INTO questions_to_answer (login_id, question_id, Question_Category, QuestionType, Question, Meaning)
SELECT ?, question_id, Question_Category, QuestionType, Question, Meaning
WHERE personality_profile_questions.Question_Category = 1";
$stmt= $DB_con->prepare($sql);
$stmt->execute(array($test_user_id));
Assuming $test_user_id = login_id. I'm not clear what all_questions is.

Related

How can I use several SQL SELECT queries as WHERE clauses in php?

$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 = ?),
?
);
";

Combine INSERT INTO SELECT, with DELETE at the same time

I have a button
<button onClick=sAve('save','."$id."']."')>SAVE</button>
Once I click it, I want to use AJAX to pass the parameters to the PHP page to perform the following task to MYSQL:
switch... case "Save":
$sql1 = "INSERT INTO permanent_table (id, user, email)
SELECT id, user, email
FROM temp_table WHERE id='".$_GET['id']."'";
$sql2 = "DELETE FROM temp_table WHERE id='".$_GET['id']."'";
Whereby permanent_table having same structure as temp_table. I tried to run both queries just like that but it is not working, so I guess that is not the right way.
In my case, my question is:
What is the real pro way to use PHP/sql to perform this task?
Is there any way I can simplify/combine it to a single query?
I think this is you want
<button onClick="$.post('/php file name/', {'save','."$id."'}, function(data){});">SAVE</button><br/>
Then you could run some query's in the PHP file.
$sql = $conn->prepare("INSERT INTO `permanent_table` (`id`, `user`, `email`) VALUES(?, ?, ?)";
$sql->bind_param("sss", $_GET['id'], "", "");
$sql->execute();
$sql = $conn->prepare("DELETE FROM `temp_table` WHERE `id`=?");
$sql->bind_param("s", $_GET['id']);
$sql->execute();
$sql = $conn->prepare("SELECT `id`, `user`, `email` FROM `temp_table` WHERE `id`=?");
$sql->bind_param("s", $_GET['id']);
$sql->execute();
//select last so that you can grab the results
Run them on your way (PDO or MYSQL)
I know a lot about query's so feel free to ask something to me!

INSERT into mySQL

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)

Insert select MySQL with prepared statements

I am wondering if I need to do this.
To make it more secure, all the things inserted into database is selected from another table with specific clause that is posted from the user.
I use the id for the identity:
$identity = $_POST['id'];
$stmt = $mysqli->prepare ("INSERT into table_one (col_1, col_2, col_3)
VALUES (?,?,?)");
//This is what I use to do
$stmt >bind_param ("sss", $valua, $valueb, $valuec);
//But now I want to that like this
$stmt >bind_param ("sss", SELECT valuea, valueb, valuec FROM ANOTHERtable WHERE id = $identity);
$list->execute();
$list->close();
Is it possible? And how is the correct way to do this?
You dont need to bind the values from your other table. You just need to prepare those for the values that the user provides. You can safely use the existing values.
$stmt = $mysqli->prepare ("INSERT into table_one (col_1, col_2, col_3)
SELECT valuea, valueb, valuec FROM ANOTHERtable WHERE id = ?");
$stmt >bind_param ("i", $identity);
$stmt->execute();

mysql insert into and select in prepared statement

how do I combine the mysql insert and select statement into a prepared statement?? Will this part of the code help me to duplicate information into a database when I hit the "copy" button?
Thanks.
INSERT INTO assignment_speeches_copy (id, subject, body, tags, image)
SELECT * FROM assignment_speeches
WHERE id = $id";
$stmt = $mysqli->prepare("INSERT INTO assignment_speeches_copy VALUES (?,?,?,?,?)"); (how do I continue?)
You don't have to combine anything. INSERT ... SELECT is a simple statement....
$stmt = $mysqli->prepare(
"INSERT INTO assignment_speeches_copy (id, subject, body, tags, image)
SELECT (id, subject, body, tags, image)
FROM assignment_speeches
WHERE id = ?"
);

Categories