没有从Mysqli排队

时间:2017-06-30 13:52:50

标签: php mysql mysqli

我正在使用mysqli获取行,但它没有给我行,并且查询中没有错误。

$query="select * from members where useremail='$user_email' and password='$password'";
$result=$db->query($query);
$row = $db->fetch_array($result);
echo $row['id'];

我的query功能

function query($query){
        $result=mysqli_query($this->conn, $query);
        if(!$result){
            echo $this->err_msg = mysqli_error($this->conn);
            return false;
        }else{
            return $result;
        }
}

我的fetch_array功能

function fetch_array($result){
    return mysqli_fetch_array($result);
}

如何使用mysqli获取Row?

1 个答案:

答案 0 :(得分:1)

使用mysqli更改原始代码以反映绑定参数,这更安全,应该可以正常工作

$query="select * from members where useremail='$user_email' and password='$password'";
    $result=$db->query($query);
    $row = $db->fetch_array($result);
    echo $row['id'];

使用mysqli预处理语句绑定参数

$query="select id from members where useremail=? and password=?";   // Don't use select *, select each column, ? are placeholders for your bind variables
$stmt = $connection->prepare($query);
if($stmt){
  $stmt->bind_param("ss",$user_email,$password);   // Bind in your variables, s is for string, i is for integers
  $stmt->execute();  
  $stmt->bind_result($id);  // bind the result to these variables, in the order you select
  $stmt->store_result();   // Store if large result set, can throw error if server is setup to not handle more than x data
  $stmt->fetch();
  $stmt->close();
  }
echo $id;  // this would be same as $row['id'], $id now holds for example 5. 

如果您选择多个内容,例如"SELECT id,name FROM...",那么当您使用bind_result(..)时,只需将它们绑定在那里即可。 $stmt->bind_result($id,$name);

现在$ id和$ name保存与您的查询匹配的该行的列数据。如果有多行匹配,而不是$ stmt-> fetch()你会做

while($stmt->fetch()){    // just like while($row = $result->fetch_assoc()){}
   echo $id;
   echo $name
}