Error with MySQL Query
Okay, I must be an idiot, because this is my 3rd question for today. Here's my code:
date_default_timezone_set("America/Los_Angeles");
include("mainmenu.php");
$con = mysql_connect("localhost", "root", "********");
if(!$con){
die(mysql_error());
}
$usrname = $_POST['usrname'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
mysql_select_db("`users`, $con) or die(mysql_error()");
$query = ("INSERT INTO `users`.`data` (`id`, `usrname`, `fname`, `lname`, `email`, `password`)
VALUES (NULL, '$usrname', '$fname', '$lname', '$email', 'password'))");
mysql_query('$query') or die(mysql_error());
mysql_close($con);
echo("Thank you for registering!");
I always get th开发者_Python百科e error returned as: "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 '$query' at line 1. Help a newbie. I'm about to stab my monitor.
1) On this line:
mysql_select_db("`users`, $con) or die(mysql_error()");
Should be:
mysql_select_db("users", $con) or die(mysql_error());
Right now you have PHP code inside the string you're sending as the database name.
2) On this line:
mysql_query('$query');
By using single quotes, the literal string $query
will be sent rather than the contents of a variable called $query
. Use either mysql_query($query)
or mysql_query("$query");
Also, where you create $query
, and where you echo
the success message, the parentheses around the string are unnecessary.
WITHIN $query
, you have too many closing parentheses. You also fail to escape any of the input, so if someone writes something nasty in your form (like anything with a single quote character), it'll break your query.
mysql_query($query) or die(mysql_error());
uneeded quotes around your $query variable.
single quotes (') do not allow you to embed variables, while double quotes (") do.
mysql_query('$query') => mysql_query("$query")
How to fix the SQL-injection hole
Change this code
coding horror$usrname = $_POST['usrname'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$password = $_POST['password'];
$email = $_POST['email'];
Into this
$usrname = mysql_real_escape_string($_POST['usrname']);
$fname = mysql_real_escape_string($_POST['fname']);
$lname = mysql_real_escape_string($_POST['lname']);
$password = mysql_real_escape_string($_POST['password']);
$email = mysql_real_escape_string($_POST['email']);
精彩评论