准备好的陈述?

时间:2013-09-23 19:23:54

标签: php mysqli prepared-statement

基本上我将我的类文件中的所有语句转换为预处理语句。阅读完php.net手册后,我仍然无法看到我的错误在哪里或是什么。

在这个特定的功能中,我通过用户ID获取用户的个人资料。

任何帮助人员?

    public function getProfile($id){
    if($result = $this->link->prepare("SELECT * FROM users WHERE id =?")){
        $result->bind_param("s", $id);
        $result->execute();
        $result->bind_result($id);
        if($result->num_rows !=0){
            return $result->fetch();
        }else{
            return array("error"=>"Profile-Not-Found");
        }
        $result->close();
    }
}

4 个答案:

答案 0 :(得分:0)

您绑定到$id,但返回return $result->fetch()(bool)的结果。

宁可做

if($result->num_rows !=0){
        $result->fetch();
       return $id;
    }else{
        return array("error"=>"Profile-Not-Found");
    }

此外,您可能希望列出感兴趣的字段并明确绑定它们,而不是执行SELECT *

答案 1 :(得分:0)

您无法将bind_resultSELECT *一起使用。您需要在SELECT

中指定字段
SELECT name, username

并在bind_result

中指定每个变量
$result->bind_result($name, $username);

(注意$result->fetch()只填充bind_result中的变量,它不返回数据,它返回一个布尔值。)

public function getProfile($id){
    if($result = $this->link->prepare("SELECT name,username FROM users WHERE id =?")){
        $result->bind_param("s", $id);
        $result->execute();
        $result->bind_result($name, $username);
        if($result->num_rows !=0 && $result->fetch()){
            return array('name' => $name, 'username' => $username);
        }else{
            return array("error"=>"Profile-Not-Found");
        }
    }
}

或使用get_result()获取整行:

public function getProfile($id){
    if($result = $this->link->prepare("SELECT * FROM users WHERE id =?")){
        $result->bind_param("s", $id);
        $result->execute();
        if($result->num_rows !=0){
            $row = $result->get_result();
            return $row->fetch_assoc();
        }else{
            return array("error"=>"Profile-Not-Found");
        }
    }
}

答案 2 :(得分:0)

这是应该如何做的。

<?php

public function getProfile($id){
    if($result = $this->link->prepare("SELECT * FROM users WHERE id =?")){
        $result->bind_param("s", $id);
        $result->execute();
        $result->store_result();

        if($result->num_rows !=0){
            $result1 = $result->get_result();
            return $result1->fetch_assoc();
        }else{
            return array("error"=>"Profile-Not-Found");
        }
        $result->free_result();
        $result->close();
    }
}
?>

答案 3 :(得分:-1)

尝试更改

$result->bind_param("s", $id);

$result->bind_param("i", $id);

因为我认为某个东西的ID会是一个整数(也许是你记录的唯一ID?)