SQL INSERT INTO table(a, b , c) VALUES (:a, :b, :c, SELECT ...) - php

So I'm trying to insert 4 values into a table. I'm getting 3 values from POST and the other one I want to get it from another table. This is how I thought about implementing it but it doesn't seem to be working. Any suggestions?
$query = "INSERT INTO topics (subject, data, uid, role) VALUES (:user, :pass, :uid, SELECT role FROM users WHERE uid=:uid) ";

In SQL, all subqueries need to be surrounded by their own parentheses. So, you can fix your query by using:
INSERT INTO topics (subject, data, uid, role)
VALUES (:user, :pass, :uid, (SELECT role FROM users WHERE uid = :uid));
Personally, I much prefer the INSERT . . . SELECT version of SELECT:
INSERT INTO topics (subject, data, uid, role)
SELECT :user, :pass, :uid, u.role
FROM users u
WHERE uid = :uid;

Related

Insert new data only if it does not exist

Why is this not working? I am trying to insert new data only if it does not meet with my requirements.
$stm= "INSERT INTO `orders` (userid, username, quantity, time, image, uprice, tprice)
VALUES
(:userid, :username, :quantity, :timee, :image, :uprice, :tprice)
WHERE NOT EXISTS (select username from orders where username=:username and image=:image)";
Instead of INSERT .... VALUES which does not allow a WHERE clause, use INSERT .... SELECT:
$stm= "INSERT INTO `orders` (userid, username, quantity, time, image, uprice, tprice)
SELECT :userid, :username, :quantity, :timee, :image, :uprice, :tprice
WHERE NOT EXISTS (select username from orders where username=:username and image=:image)";

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)

Column Count vs Value Count on insert statement - PHP/MySQL

I am working on building an employee database but seem to have run into an interesting issue.
When I run my query to add a new user/employee, I get the error:
Column count doesn't match value count at row 1
From what I have researched, this seems to be an error with inserting more/less values than what is declared in the first part of an insert statement example:
INSERT INTO table (col1, col2) VALUES (val1, val2, val3)
The thing is though, I have looked over my query and the columns and values match perfectly (count wise). I have even looked for things in my query such as missing quotes, commas, etc.
Here is my code (query):
$db->query("INSERT INTO userdata (
Username,
Email,
Phone,
Password,
FirstName,
LastName,
Address,
City,
State,
Zip,
JobTitle,
UserGroup,
JobStatus,
Points,
Status,
BirthDate,
HireDate,
HourlyRate,
DateAdded,
SSN
) VALUES (
'$Username',
'$Email',
'$Phone',
'$Password',
'$FirstName',
'$LastName',
'$Address',
'$City',
'$State',
'$Zip',
'$JobTitle',
'$Group',
'$JobStatus',
0,
'$Status',
'$BirthDate',
'$HireDate',
'$HourlyRate'
'$TodaysDate',
'$SSN'
)") or die(mysqli_error($db));
Some things to note:
This not all of the columns in the table have data inserted here (I think its possible to do this and things such as auto incrementing ID's will fill themselves in and others will be left blank)
From the variable dumps I have done, all of these variables are valid.
I am really confused about this and any help would be appreciated.
Check the following portion again:
INSERT INTO userdata(...,
JobStatus,
UserGroup,
Points,
UserGroup,
Status,
.....
,)VALUES(...,
$JobStatus',
0,
'$Group',
'$Status',
......
)
In values(, ?, ?, ?), after jobstatus, there should be UserGroup and then Points. And UserGroup appeared twice.

mysql/php wrong logic with sql statement

I'm doing a project which has an ability of a user to approve or revoke application (like scholarship). But I can't seem to find out why it's not doing what I wanted to do. Please do check my code below:
$try = mysql_query("UPDATE new_applicants SET ApplicantStatusId='$status', DateManaged = NOW() WHERE ApplicantId='$id'") or die(mysql_error());
$try1 = mysql_fetch_assoc($try);
$status1 = $try1["ApplicantStatusId"];
if( $status1 == 2 ){
header('location: ../employeepage.php');
exit();
}
else{
$sql1 = "INSERT INTO scholar_profile (Firstname, Middlename, Lastname, Address, EmailAddress, BirthDate, BirthPlace, Religion, Age, Gender, ContactNo, Skill, Talent, LevelId, GWA, CategoryId, StatusId, SchoolId, BarangayId) SELECT Firstname, Middlename, Lastname, Address, EmailAddress, BirthDate, BirthPlace, Religion, Age, Gender, ContactNo, Skill, Talent, LevelId, GWA, CategoryId, StatusId, SchoolId, BarangayId
FROM new_applicants
WHERE new_applicants.ApplicantId = '$id'" or die(mysql_error());
}
When the applicantstatus becomes 2 = revoked, it should not copy the data to scholar_profile. But when I tried this, it still copies. What's wrong with this? thanks.
You're updating a table, so mysql_fetch_assoc won't return anything. I.e. $status1 will be null. If you want to select that data (ApplicantStatusID, ...) you'll have to use a SELECT statement instead.
You could just change the where clause of the SQL statement:
WHERE new_applicants.ApplicantId = '$id' and new_Applicants.ApplicantStatusId <> 2"
Then you don't have to worry about the logic in php.
you are fetching $try1 = mysql_fetch_assoc($try); on an UPDATE statment
which is not true.
fetch is only with SELECT statment

Insert on Join Tables Mysql

I've seen several questions and answers about this, but none is quite similar to my problem, so now I am asking.
Here is the situation
I have a table called users, roles, and user_role
table: users
fields: user_id, username, password
table: roles
fields: role_id, role_name
table: user_role
fields: user_id, role_id
foreign key of user_role.user_id is user.user_id
foreign key of user_role.role_id is role.role_id
My problem is when I create a user, I also want to set their roles to a default value or a selected value I chose in <select> element.
I tried several things like:
INSERT INTO users as t1 (t1.username, t1.password, t2.role)
JOIN user_role as t2 ON t1.user_id = t2.user_id
VALUES (:username, :password, :role)
Am I doing it super wrong?
EDIT BECAUSE OF AN ANSWER BELOW
I think something is still wrong, it gives me a blank screen
$this->db->beginTransaction();
$string = "INSERT INTO users (username, password)
VALUES (:user,:pass,:first,:middle,:last,:course)";
$sth = $this->db->prepare($string);
$sth->execute(array(
':user'=> $data['user'],
':pass'=> $data['pass']
));
$sth = $this->db->prepare("INSERT INTO user_roles (user_id, role_id)
VALUES (' . $this->db->lastInsertId(user_id) . ', :role)");
$sth->execute(array(
':role' => 3
));
$this->db->commit();
Since it seems like you're using PHP & PDO, this simplified code will take care of your insert:
$pdo->beginTransaction();
$stmt = $conn->prepare('INSERT INTO users (username, password) VALUES (?, ?)');
$stmt->execute(array($username, $password));
$stmt = $conn->prepare('INSERT INTO user_roles (user_id, role_id) VALUES (' . $pdo->lastInsertId() . ', ?)');
$stmt->execute(array($role));
$pdo->commit();
After you insert a user into the users table, the value returned by $pdo->lastInsertId() is the id that was just inserted into the users table.
Read more on lastInsertId().
Encase these two insert statements in a transaction and you're good to go.

Categories