SQL和PHP检查值是否等于某个值

时间:2014-04-24 16:00:14

标签: php mysql sql

我只是想知道如何检查mysql数据库中的值是否等于某事。数据库连接没问题,这是我的代码。如果你能提供帮助,我将不胜感激。

$array = mysqli_query($connect,"SELECT * FROM users");
$result = mysql_fetch_array($array);
if(in_array($username,$result['username'],TRUE)){
    echo "$username <br/> ";
}else{
    echo "Failed";
}

3 个答案:

答案 0 :(得分:4)

这是WHERE子句的用法。以下是使用预处理语句执行此操作的方法。

$sql = mysqli_prepare($connect, 'SELECT * FROM users WHERE username = ?');
if($sql !== FALSE){
    mysqli_stmt_bind_param($sql, 's', $username);
    mysqli_stmt_execute($sql);

    $result = mysqli_stmt_get_result();
    if($result !== FALSE){
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);

        echo $row['username'];
    }
}
else{
    die(mysqli_error($connect));
}

P.S。 mysqli_stmt_get_result需要MySQLnd driver

答案 1 :(得分:4)

使用mysqli并清理的示例:

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

$query = "SELECT * FROM users WHERE fieldname = data";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($result);

if ($row['username']) {
    echo "$username <br/> ";
 } else {
    echo "Failed";
 }

答案 2 :(得分:0)

使用预准备语句替换查询。

$stmt = mysqli_prepare($connect, "SELECT * FROM users WHERE username = ?");
mysqli_stmt_bind_param($stmt, "s", $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) == 1) {
    echo "$username<br/>";
} else {
    echo "Failed";
}