I am working with WordPress and I made a form in the admin section. I am trying to submit it to another database (not the default wp one) so I switch databases successfully and do an insert query but I keep getting an error.
This is my code:
$selected = mysql_select_db( 'petracms', $serverAccess );
if (!$selected) {
die ('Can\'t use foo : ' . mysql_error());
}
$query = "INSERT INTO `petra_customers` (`FirstName`, `LastName`, `Email`, `Phone`) VALUES ($fName, $lName, $email, $phone)";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
I keep getting this error:
Invalid query: 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 '@gmail.com, 5859475566)' at line 1
This is my input: (Adam, Page, bofumme@gmail.com, 5859475566)
I have no idea what I am doing wrong
Values in INSERT
statements need to be enclosed in quotes (except "numbers"):
INSERT INTO `foo` (`a`,`b`,`c`) VALUES("foo","bar",1)
This is how you would (safely) construct a variable for use in query string interpolation (this is frowned upon, though):
$email = sprintf('"%s"', mysql_real_escape_string($_POST['email']));
$query = "INSERT INTO `foo` (`email`) VALUES($email)";
A more elegant way (and far more secure, too), is to use prepared statements (example uses PDO ):
# Prepare the statement
$sth = $dbh->prepare('INSERT INTO `foo` (`email`) VALUES(:email)');
# Substitute placeholders in query and execute it
$sth->execute(array(
'email' => $_POST['email']
));
I guess you forgot to add quotes '
to your INSERT
query. Check out any tutorial on the web on how to do simple inserts, eg here: http://www.w3schools.com/php/php_mysql_insert.asp
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.