准备好的陈述方法..困惑

时间:2013-08-29 02:46:45

标签: php oop mysqli statements

我不知道缺少什么或为什么它没有显示数据。如果我没有使用预准备语句,我的代码正在运行。当我使用预准备语句时,似乎代码不再起作用了。

db.php中

Class Database{


public $mysqli;
public function __construct($db_host, $db_user, $db_password, $db_name){

    $this->con = new mysqli($db_host, $db_user, $db_password, $db_name);

}

    public function selectUserInfo($id){

        $stmt = $this->con->prepare("SELECT * FROM users WHERE os_id = ?");
        $stmt->bind_param("s", $id);
        if($stmt->execute() == FALSE){
            trigger_error($stmt->error, E_USER_ERROR);
        }else{
            $data = array();
            while($row = $stmt->fetch()){
                $data[] = $row;
            }
            return $data;
        }

}
}

的config.php

define("DBHOST","somehost");
define("DBUSER","someroot");
define("DBPASS","somepassword");
define("DB","my_database");

这就是我在页面上显示的方式。

require 'global/db.php';
require_once 'config.php';
$db = new Database(DBHOST, DBUSER, DBPASS, DB);
$data = $db->selectUserInfo($_GET['name']);
foreach ($data as $key) {
    # code...
    echo $key['os_fname'];
}

2 个答案:

答案 0 :(得分:0)

正如我们所定义的那样,问题出在您的foreach上。

您的阅读方式有问题,fetch没有关联属性,因此需要使用bind_result

以下是fetch manual

中也提出的黑客行为
public function selectUserInfo($id)
{
    $stmt = $this->con->prepare("SELECT * FROM users WHERE os_id=?");
    $stmt->bind_param('i', $id);
    if(!$stmt->execute())
    {
        trigger_error($stmt->error, E_USER_ERROR);
    }
    else
    {
        $bindVarArray = array();
        $data = array();
        $result;
        $meta = $stmt->result_metadata();
        while ($column = $meta->fetch_field())
        {
            $columnName = str_replace(' ', '_', $column->name);
            $bindVarArray[] = &$result[$columnName];
        }
        call_user_func_array(array($stmt, 'bind_result'), $bindVarArray);

        $index = 0;
        while ($stmt->fetch() != null)
        {
            foreach ($result as $k => $v)
            {
                $data[$index][$k] = $v;
            }
            $index++;
        }
        return $data;
    }
}

然后您可以使用foreach来读取它:

foreach ($data as $result)
{
    echo $result['os_fname'], ' => ', $result['os_lname'], "\n";
}

您可以随时使用print_r查看结果数组的结果:

print_r($data);

答案 1 :(得分:-3)

你的DB中的od_id类型是字符串还是整数?如果是整数

public function selectUserInfo($id){

    $stmt = $this->con->prepare("SELECT * FROM users WHERE os_id = ?");
    $stmt->bind_param("i", $id);//use 'i' instead of 's'

    if($stmt->execute() == FALSE){
        trigger_error($stmt->error, E_USER_ERROR);
    }else{
        $data = array();
        while($row = $stmt->fetch()){
            $data[] = $row;
        }
        return $data;
    }

}