简体   繁体   中英

PHP - Check if index already exists in SQL

I'm new to PHP and am practicing by programming a very basic signup form, which dumps the info into a MySQL database. However, I'm having a problem where, even if the name is taken, my program still adds the account to the SQL table. This is my code to check if the name exists:

$sql = "SELECT * FROM accounts WHERE name = '$name'";
$result = $conn->query($sql);

if (mysql_fetch_array($result) === true) {
     die("Error: Username has been taken");
} else {
//register account
}

Every time I run this, no matter what the name is, the program runs the block of code inside the else statement. I can provide more info if needed.

您可以更改表并添加以使字段唯一。

if you are using mysqli then use.

if ($result->num_rows > 0) { 
 die("Error: Username has been taken"); 
}
else {
// register here;
}

PS do not use mysql read here .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM