Okay, so I've been going at it for a while now.
What I'm trying to achieve is to prevent people from being able to create the same name that is entered in the name='name' field. Here's the html code.
Name Your Card
and this is my mysql page.
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "christmas";
// Create connection
$dbhandle = mysqli_connect ($servername, $username, $password, $dbname) or die ("could not connect to database");
$selected = mysql_connect('christmas', $dbhandle);
$query = mysql_query("SELECT * FROM list WHERE name='$name'");
if(mysql_num_rows($query) > 0){
echo 'that name already exists';
}else{
mysql_query("INSERT INTO list(name, one , two, three, four, five, six, seven, eight) VALUES ('$name' , '$one' , '$two' , '$three' , '$four' , '$five' , '$six', '$seven' , '$eight')");
}
mysql_close();
?>
what the heck am I doing wrong?
解决方案
There is quite a few things wrong here.
You're using a MySQL keyword list as a function, and that alone will cause you problems.
Sidenote: Yes, I know it's not a "reserved" word, it's a "keyword" and MySQL treats keywords specially if used as a function, which is what you're doing now in your second query, and is the way that MySQL is interpreting it as; a function rather than a table declaration name.
I suggest you rename that table to lists, or wrap it in ticks.
You're also mixing MySQL APIs/functions that do not intermix.
So your new code would read as,
while dropping $selected = mysql_connect('christmas', $dbhandle);
$query = mysqli_query($dbhandle, "SELECT * FROM `list` WHERE name='$name'")
or die (mysqli_error($dbhandle));
if(mysqli_num_rows($query) > 0){
echo 'that name already exists';
}else{
mysqli_query($dbhandle, "INSERT INTO `list` (name, one, two, three, four, five, six, seven, eight)
VALUES ('$name' , '$one' , '$two' , '$three' , '$four' , '$five' , '$six', '$seven' , '$eight')")
or die (mysqli_error($dbhandle));
}
mysqli_close($dbhandle);
Your code is also open to an SQL injection. Use a prepared statement.
Now, we have no idea as to where all your variables are coming from.
Use error reporting.
I also suggest you use a conditional empty() for your variables/inputs.
Otherwise, you may also get other errors that MySQL may complain about.
I.e.:
if(!empty($var)){...}
Ultimately and to make sure there are no duplicate entries in your database, you can set a UNIQUE constraint.