2014-12-08 94 views
-1
$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"; 

这是正确的方法是什么?它说用户不存在,不管是什么;并且我知道在db中有一个名为“test”的用户。检查mysql用户存在

+0

什么ID'$数据[0]'? – zerkms 2014-12-08 01:58:51

+1

if(mysqli_num_rows($ rs)> 0){echo“user exists;} – radar 2014-12-08 01:59:10

+2

...或甚至是'SELECT COUNT(*)...' – zerkms 2014-12-08 01:59:30

回答

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/>'; 
} 
+0

它的工作原理!但为什么我这样做的方式不正确? – 2014-12-08 02:38:35

+0

@HuangLee我的猜测是,你无法知道相比于'> 1'时打算什么列在结果集的0位置,因为你正在使用'SELECT *'而且不管是什么,方式,正在评估以'false' – Phil 2014-12-08 03:23:30

+0

@HuangLee此外,您的原始代码易受SQL注入攻击。使用带有绑定参数的预准备语句可以避免这个问题 – Phil 2014-12-08 03:24:58