问题
$check="SELECT * FROM users WHERE name = '$_POST[name]'";
$rs = mysqli_query($conn,$check);
$data = mysqli_fetch_array($rs, MYSQLI_NUM);
if($data[0] > 1) {
echo "User Already in Exists<br/>";
}else
echo "User does Not exist";
Is this the correct way? It says User does Not exist no matter what; and I know there is a user named "test" in the db.
回答1:
// this line makes mysqli throw exceptions so you'll never have to check
// return values for false
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// prepare a statement checking for existence
$stmt = $conn->prepare('SELECT 1 FROM users WHERE name = ?');
// bind the POST param to the parameter
$stmt->bind_param('s', $_POST['name']);
$stmt->execute();
// if there are any rows, that means the name exists
if ($stmt->fetch()) {
echo 'User "', htmlspecialchars($_POST['name']), '" already exists<br/>';
} else {
echo 'User "', htmlspecialchars($_POST['name']), '" does not exist<br/>';
}
来源:https://stackoverflow.com/questions/27350264/check-if-mysql-user-exists