how can i insert data from query results and other variables in one insert query?
sample:
$id = $_POST['id'];
$address = $_POST['address'];
$email = $_POST['email'];
$query = "INSERT INTO info_table(fname, lname, address, email) VALUES (SELECT fname, lname, FROM info WHERE id = '$id')";
$result = db->prepare($query);
$result->execute();
how can i insert $address and $email together with the select results variables?
This should do the trick for the query:
INSERT INTO info_table (
fname,
lname,
address,
email
)
SELECT
fname,
lname,
':address',
':email'
FROM
info
WHERE
id = ':id'
You aren't using the prepare right here. You really should bind to the paramters :address, :email, and :id
$result = db->prepare($query);
$result->bindParam(':id', $id, PDO::PARAM_STR);
$result->bindParam(':email', $email, PDO::PARAM_STR);
$result->bindParam(':address', $address, PDO::PARAM_STR);
$result->execute();
Answering precisely to your question:
$query = "INSERT INTO MyInsecureTable (fname, lname, address, email) SELECT fname, lname, '$address', '$email' FROM info WHERE id = '$id'";
But it is scares the . out of me.
Related
I am trying to INSERT data into a table and I am using mysqli API executing query.
$insert = "INSERT INTO pdhp_patient
(username, password, email, first_name,
last_name, dob, gender, s_s_n, i_n)
VALUES ('$username', '$password', '$email', '$first_name',
'$last_name', '$dob', '$gender', '$s_s_n', '$i_n');";
This is the query I am trying to execute.
mysqli_query($connection, $insert);
The previous line of code is for executing the query. This time the query returns false. I am unable to understand what the mistake is I Have even tried without the single quotes in the query. This however does not work.
Editted:
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$dob = $_POST['dob'];
$dob = date("m-d-Y", strtotime($dob));
$gender = $_POST['gender'];
$cid = $_POST['country'];
$sid = $_POST['city'];
$s_s_n = $_POST['s_s_n'];
$i_n = $_POST['i_n'];
global $connection;
if(isset($_POST['type']) && $_POST['type']==="patient"){
$insert = "INSERT INTO pdhp_patient (username, password, email, first_name, last_name, dob, gender, s_s_n, i_n) VALUES ('$username', '$password', '$email', '$first_name', '$last_name', '$dob', '$gender', '$s_s_n', '$i_n');";
$insert = mysql_prep($insert);
$result = mysqli_query($connection, $insert);
if ( $result === false ) {
echo mysqli_error($connection);
exit;
}
if($val){
echo "This must be working";
}else{
echo "This was not working";
}
}elseif(isset($_POST['type']) && $_POST['type']==="doctor"){
$insert = "INSERT INTO pdhp_doctor (username, password, email, first_name, last_name, dob, gender, s_s_n, i_n) VALUES ($username, $password, $email, $first_name, $last_name, $dob, $gender, $s_s_n, $i_n);";
$insert = mysql_prep($insert);
mysqli_query($connection, $insert);
}elseif(isset($_POST['environment_radio']) && $_POST['type']==="environment"){
$insert = "INSERT INTO pdhp_environmentalist (username, password, email, first_name, last_name, dob, gender, s_s_n, i_n) VALUES ($username, $password, $email, $first_name, $last_name, $dob, $gender, $s_s_n, $i_n);";
$insert = mysql_prep($insert);
mysqli_query($connection, $insert);
}
Some more code for proper info. This code chunk is what I wanna achieve. this is the full code.
Thanks.
Give a man a fish, he eats today. Teach a man to fish, he eats everyday
Add some error checking
$insert = "INSERT INTO pdhp_patient
(username, password, email, first_name,
last_name, dob, gender, s_s_n, i_n)
VALUES ('$username', '$password', '$email', '$first_name',
'$last_name', '$dob', '$gender', '$s_s_n', '$i_n');";
$result = mysqli_query($connection, $insert);
if ( $result === false ) {
echo mysqli_error($connection);
exit;
}
Then you can probably fix your own errors
Per your update and comment your issue is that you are escaping the whole query, and not the values that you are passing in. That is not how escaping works, with escaping you escape the values going in incase they contain 's which would break the SQL encapsulation. So instead do..
$username = mysqli_real_escape_string($connection, $_POST['username']);
$password = mysqli_real_escape_string($connection, $_POST['password']);
$email = mysqli_real_escape_string($connection, $_POST['email']);
$first_name = mysqli_real_escape_string($connection, $_POST['first_name']);
$last_name = mysqli_real_escape_string($connection, $_POST['last_name']);
$dob = mysqli_real_escape_string($connection, $_POST['dob']);
$dob = mysqli_real_escape_string($connection, date("m-d-Y", strtotime($dob)));
$gender = mysqli_real_escape_string($connection, $_POST['gender']);
$cid = mysqli_real_escape_string($connection, $_POST['country']);
$sid = mysqli_real_escape_string($connection, $_POST['city']);
$s_s_n = mysqli_real_escape_string($connection, $_POST['s_s_n']);
$i_n = mysqli_real_escape_string($connection, $_POST['i_n']);
and get rid of mysql_prep. You should probably read up a bit more on SQL injections:
http://php.net/manual/en/security.database.sql-injection.php
https://www.owasp.org/index.php/SQL_Injection
The more secure approach is using parameterized queries with prepared statements.
http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
According to everything I've found and seen, this seems correct. When I print $query the outcome is the following:
"INSERT INTO customers (FirstName, MiddleInit, LastName, Address, City, State, Zip, Email, Gender) VALUES (?,?,?,?,?,?,?,?,?)"
The parameters should have been filled in with the variables in bindValues(). So, for example ...
INSERT INTO customers (FirstName, MiddleInit, LastName, Address, City, State, Zip, Email, Gender) VALUES (Bill, A, Hopkins, 123 Ave, ....)
I'd like to stick with this method - it is surrounded by a try/catch block. From printing the query variable out I can see that is where the issue is.
What am I missing? I really appreciate you looking!
$query = 'INSERT INTO customers (FirstName, MiddleInit, LastName, Address, City, State, Zip, Email, Gender) VALUES (?,?,?,?,?,?,?,?,?)';
echo $query;
$statement = $db->prepare($query);
$statement->bindValue(1, $firstName);
$statement->bindValue(2, $middle);
$statement->bindValue(3, $lastName);
$statement->bindValue(4, $address);
$statement->bindValue(5, $city);
$statement->bindValue(6, $state);
$statement->bindValue(7, $zip);
$statement->bindValue(8, $email);
$statement->bindValue(9, $gender);
$success = ($statement->execute());
We need more code considering the error but you can try this with prepared statements:
$query = 'INSERT INTO customers (FirstName, MiddleInit, LastName, Address, City, State, Zip, Email, Gender) VALUES (:firstName, :middle, :lastName, :address, :city, :state, :zip, :email, :gender)';
$statement = $db->prepare($sql);
$statement->execute(array(':firstName'=>$firstName, ':middle'=>$middle, ':lastName'=>$lastName, ':address'=>$address, ':city'=>$city, ':state'=>$state, ':zip'=>$zip, ':email'=>$email, ':gender'=>$gender));
My sql query is :
"INSERT INTO
order customer_id = $customer_id
, firstname = '".$firstname."'
, lastname = '".$lastname."'
, email = '".$email."'
, telephone = '".$telephone."'
, fax = '".$fax."'
, ip = '".$ip."'
, date_added = NOW()
, date_modified = NOW()
";
I get the error
Notice: Error: You have an error in your SQL syntax; check the manual
that corresponds to your MySQL server version for the right syntax to
use near 'order customer_id =1,firstname ='kuldeep',lastname
='pathak',email ='kuldeep.pat' at line 1 Error No: 1064
You didnt understand how to write SQLs as it seems.
$sql = 'INSERT INTO `order` (customer_id, firstname, blablabla) VALUES ('.$custormer_id.','.$firstname.','.$blablabla.')';
Please look at some basic tutorials about SQL.
"INSERT INTO
`order` SET customer_id = " . $customer_id . "
, firstname = '".$firstname."'
, lastname = '".$lastname."'
, email = '".$email."'
, telephone = '".$telephone."'
, fax = '".$fax."'
, ip = '".$ip."'
, date_added = NOW()
, date_modified = NOW()
";
Should be alright. DonĀ“t forget to escape your data though.
Try
"INSERT INTO `Order` (customer_id, firstname, lastname, email, telephone, fax, ip, date_added, date_modified)
VALUES ($customer_id, '$firstname', '$lastname', '$email', '$telephone', '$fax', '$ip', NOW(), NOW())"
The right syntax is : INSERT INTO tablename (columns) VALUES (values);
If you're likely to have user submitted fields in the dataset or appostrophes or anything else that could cause problems for any reason you'd want something more like
$query = sprintf("INSERT INTO `table` (`Name`, `Email`, `AnotherField`) VALUES ('%s', '%s', '%s'",
mysql_real_escape_string( $_POST['Name'] ),
mysql_real_escape_string( $_POST['Email'] ),
mysql_real_escape_string( $_POST['AnotherField'] )
);
This will sanitise your inputs as well
Use prepared statement to avoiding sql injection.
$custormer_id = "2000";
$firstname = "first name";
$etc = "some other values";
$mysqli = new mysqli('localhost', 'user', 'password', 'database');
$stmt = $mysqli->prepare("INSERT INTO order(customer_id, firstname, etc) VALUES (?, ?, ?)");
$stmt->bind_param('iss', $custormer_id, $firstname, $etc);
// first parameter is corresponding variable type of inserting values,eg i=interger, s=string
$stmt->execute();
$stmt->close();
http://php.net/manual/en/mysqli-stmt.bind-param.php
I am having problems getting an sql query correct to update user profiles. I use (basically) the same query to INSERT the data and it works fine (just without the WHERE id=clientid and without clientid in the execute array. The query below does not update any data in the database.
I tested and made sure that all the variables are being posted and they are. As a sidenote, is this query safe from sql injection?
$conn = new PDO("mysql:host=$DB_HOST;dbname=$DB_DATABASE",$DB_USER,$DB_PASSWORD);
// Deal with the POST variables here...(excluded)
$sql = "UPDATE clients (firstname, lastname, origincountry, dob, gender, email, phone, address, postal, city, province, referred, notes)
VALUES (:firstname, :lastname, :origincountry, :dob, :gender, :email, :phone, :address, :postal, :city, :province, :referred, :notes)
WHERE id = :clientid" ;
$q = $conn->prepare($sql);
$q->execute(array(':firstname'=>$firstname,
':lastname'=>$lastname,
':origincountry'=>$origincountry,
':dob'=>$dob,
':gender'=>$gender,
':email'=>$email,
':phone'=>$phone,
':address'=>$address,
':postal'=>$postal,
':city'=>$city,
':province'=>$province,
':referred'=>$referred,
':notes'=>$notes,
':clientid'=>$clientid));
Your SQL is invalid. See UPDATE. (thanks to #rambocoder for pointing that out).
Use this SQL:
UPDATE clients SET firstname = :firstname, lastname = :lastname, origincountry = :origincountry, dob = :dob, gender = :gender, email = :email, phone = :phone, address = :address, postal = :postal, city = :city, province = :province, referred = :referred, notes = :notes
WHERE id = :clientid
I have a set of PDO statements that do not seem to be working. Basically I am trying to update the "waiting" value in 1 table and then select that same row and insert it into another table.
$statement = $db->prepare("UPDATE waiting SET wait = :status WHERE id = :id");
$statement->bindValue(':status', 0);
$statement->bindParam(':id', $id);
$statement->execute();
$statement = $db->prepare("INSERT INTO approved (fname, lname, student_id, email, type) (SELECT fname, lname, student_id, email, type FROM waiting WHERE id = :id)");
$statement->bindParam(':id', $id);
$statement->execute();
I've also tried setting $statement to null before I do the other query but that didn't work either:
$statement = $db->prepare("UPDATE waiting SET wait = :status WHERE id = :id");
$statement->bindValue(':status', 0);
$statement->bindParam(':id', $id);
$statement->execute();
$statement = null;
$statement = $db->prepare("INSERT INTO approved (fname, lname, student_id, email, type) (SELECT fname, lname, student_id, email, type FROM waiting WHERE id = :id)");
$statement->bindParam(':id', $id);
$statement->execute();
Any ideas why this isn't working?
Your insert query is syntactically wrong. Remove the brackets from around the select and it should work:
INSERT INTO approved (fname, lname, student_id, email, type)
SELECT fname, lname, student_id, email, type FROM waiting WHERE id = :id