准备陈述方法..困惑 [英] prepared statement method.. confused

查看:63
本文介绍了准备陈述方法..困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道丢失了什么或为什么它不显示数据.如果我不使用准备好的语句,我的代码将正常工作.当我使用准备好的语句时,似乎代码不再起作用.

I don't know what's missing or why it isn't displaying data. My code is working if I'm not using prepared statements. When I used prepared statements, it seems that code is not working anymore.

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");

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

this is how I would displayed it at my page.

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'];
}

推荐答案

如我们所定义,问题出在您的foreach.

As we have defined, that the issue was with your foreach.

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

What is wrong is with how you're reading it, fetch does not have associative properties so need to use the bind_result.

这是 fetch手册中建议的一种黑客方式:

Here is a hack that is also suggested at the 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来阅读它:

Then you can use your foreach to read it like this:

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

并且您始终可以使用print_r来查看结果数组的状态:

And you can always use print_r to see how your resulting array is:

print_r($data);

这篇关于准备陈述方法..困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆