INSERT into mySQL - 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)

Related

Mysql MAX ID+1 incriment with insert query

Please help in manually incrementing id filed with insert query and PDO
(note: No primary key set in table)
if ($valid) {
$max="SELECT MAX(id)+1 from class";
$sql = "INSERT INTO class (id,Class,Notes) values(?,?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($max,$Class, $Notes));
header("Location: class_create.php");
}
This insert not incrementing id, Please help
INSERT INTO class (id, Class, Notes)
SELECT MAX(id)+1, ?, ?
FROM class
and
$q->execute(array($Class, $Notes));
Be ready to duplicated values due to parallel execution interference.

Insert into MySQL table from value and select statement

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.

UPDATE table record instead of adding a new record MySQL

Ok .. Here is the thing. I want to list users logged on and change their status when logged out. This works perfect. I created a table for that called tblaudit_users. The existing users I SELECT from a tbl_users table.
What I want, is that if an user already exists in the tblaudit_users table it will UPDATE the LastTimeSeen time with NOW(). But instead of updating that record, it creates a new record. This way the table will grow and grow and I want to avoid that. The code I use for this looks like:
+++++++++++++++++++
$ipaddress = $_SERVER['REMOTE_ADDR'];
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' AND active = '1' LIMIT 1");
$query->execute();
foreach($query->fetchAll(PDO::FETCH_OBJ) as $value){
$duplicate = $value->username;
}
if($duplicate != 1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($duplicate = 1){
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE username = '{$username}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
I am lost and searched many websites/pages to solve this so hopefully someone here can help me? Thanks in advance !!
UPDATE:
I've tried the below with no result.
+++++
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
Ok. I altered my query and code a little:
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE username = '{$username}' LIMIT 1");
$query->execute();
if($query){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
ON DUPLICATE KEY UPDATE set LastTimeSeen = NOW(), status = '1'
");
$insert->execute();
} else {
header('Location: index.php');
die();
}
}
I also added a UNIQUE key called pid (primary id). Still not working.
Base on http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html, don't use 'set' in update syntax
example from the page:
INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=9;
Several issues:
You test on $query, but that is your statement object, which also will be valid even if you have no records returned from the select statement;
There can be issues accessing a second prepared statement before making sure the previous one is closed or at least has all its records fetched;
There is a syntax error in the insert statement (set should not be there);
For the insert ... on duplicate key update to work, the values you provide must include the unique key;
SQL injection vulnerability;
Unnecessary split of select and insert: this can be done in one statement
You can write your test using num_rows(). To get a correct count call store_result(). Also it is good practice to close a statement before issuing the next one:
$query = $db->prepare("SELECT * FROM tblaudit_users
WHERE username = '{$username}' LIMIT 1");
$query->execute();
$query->store_result();
if($query->num_rows()){
$query->close();
// etc...
However, this whole query is unnecessary when you do insert ... on duplicate key update: there is no need to first check with a select whether that user actually exists. That is all done by the insert ... on duplicate key update statement.
Error in INSERT
The syntax for ON DUPLICATE KEY UPDATE should not have the word SET following it.
Prevent SQL Injection
Although you use prepared statements (good!), you still inject strings into your SQL statements (bad!). One of the advantages of prepared statements is that you can use arguments to your query without actually injecting strings into the SQL string, using bind_param():
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district,
gemeente, ipaddress, LastTimeSeen, status)
VALUES (?, ?, ?, ?, ?, ?, NOW(), '1')
ON DUPLICATE KEY UPDATE LastTimeSeen = NOW(), status = '1'
");
$insert->bind_param("ssssss", $userId, $username, $achternaam,
$district, $gemeente, $ipaddress);
$insert->execute();
This way you avoid SQL injection.
Make sure that user_id has a unique constraint in the tblaudit_users. It does not help to have another (auto_increment) field as primary key. It must be one of the fields you are inserting values for.
The above code no longer uses $query. You don't need it.
I found the issue
if(isset($_SESSION['id'])){
$userId = $_SESSION['id'];
$username = $_SESSION['username'];
$achternaam = $_SESSION['achternaam'];
$district = $_SESSION['district'];
$gemeente = $_SESSION['gemeente'];
$query = $db->prepare("SELECT * FROM tblaudit_users WHERE user_id = '{$userId}' LIMIT 1");
$query->execute();
if($query->rowcount()<1){
$insert = $db->prepare("
INSERT INTO tblaudit_users (user_id, username, achternaam, district, gemeente, ipaddress, LastTimeSeen, status)
VALUES ('{$userId}', '{$username}', '{$achternaam}', '{$district}', '{$gemeente}', '{$ipaddress}', NOW(), '1')
");
$insert->execute();
} elseif($query->rowcount()>0) {
$update = $db->prepare("UPDATE tblaudit_users SET LastTimeSeen = NOW(),status = '1' WHERE user_id = '{$userId}'");
$update->execute();
} else {
header('Location: index.php');
die();
}
}
Instead of using $username in my query, I choose $userId and it works.

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();

Where is the error in my sql code

$fname = addslashes($fname);
$lname = addslashes($lname);
$dob = addslashes($dob);
$email = $_POST['email'];
$sql =
"INSERT INTO subscriber
(fname, lname, dob)
VALUES
('".$fname."', '".$lname."', '".$dob."')
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");
I am getting error in sql query "insertion error". Query is inserting data into DB after removing WHERE statement. What is the error.
You can't use where in an insert statement. You might be thinking of an update instead?
$sql = "update subscriber set fname='".$fname."', lname = '".$lname."', dob = '".$dob."' WHERE email='".$email."'";
If your email is a unique value, you can also combine an insert with an update like this:
insert into
subscriber (fname, lname, dob, email)
values ('".$fname."', '".$lname."', '".$dob."', '".$email."')
on duplicate key update set fname='".$fname."', lname='".$lname."', dob='".$dob."'
This second syntax will insert a row if there isn't one with a matching email (again, this has to be set to a unique constraint on the table) and if there is one there already, it will update the data to the values you passed it.
Basically INSERT statement cannot have where. The only time INSERT statement can have where is when using INSERT INTO...SELECT is used.
The only syntax for select statement are
INSERT INTO TableName VALUES (val1, val2, ..., colN)
and
INSERT INTO TableName (col1, col2) VALUES (val1, val2)
The other one is the
INSERT INTO tableName (col1, col2)
SELECT col1, col2
FROM tableX
WHERE ....
basically what it does is all the records that were selected will be inserted on another table (can be the same table also).
One more thing, Use PDO or MYSQLI
Example of using PDO extension:
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmt = $dbh->prepare("INSERT INTO REGISTRY (name, value) VALUES (?, ?)");
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $value);
// insert one row
$name = 'one';
$value = 1;
$stmt->execute();
?>
this will allow you to insert records with single quotes.
Oops !!!! You cannot use a WHERE clause with INSERT statement ..
If you are targeting a particular row then please use UPDATE
$sql = "Update subscriber set fname = '".$fname."' , lname = '".$lname."' , dob = '".$dob."'
WHERE email='".$email."'";
$register = mysql_query($sql) or die("insertion error");

Categories