mysqli数组不能正确打印值

时间:2013-02-15 21:15:17

标签: php sql mysqli

我在打印MySQLi查询中的值时遇到问题。这是我正在使用的db连接类。

class db
{
 public function  __construct() 
    {
    $this->mysqli = new mysqli('localhost', 'root','', 'database');
    if (mysqli_connect_errno())
    {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
}

public function Query($SQL)
{
    $this->SQL = $this->mysqli->real_escape_string($SQL);
    $this->Result = $this->mysqli->query($SQL);
    if ($this->Result == true)
    return true;
    else
    die('Problem with Query: ' . $this->SQL);
}

public function Get($field = NULL)
{
    if ($field == NULL)
    {
        $data = array();
        while ($row = $this->Result->fetch_assoc())
        {
            $data[] = $row;
        }
    }
    else
    {
        $row = $this->Result->fetch_assoc();
        $data = $row[$field];
    }

    $this->Result->close();
    return $data;
}

public function __destruct()
{
    $this->mysqli->close();
}
}

运行查询

$db = new db;
$db->Query("SELECT * FROM tblclients WHERE clientid = $this->id");
$result = $db->Get();
echo $result['clientid'];

我收到错误

PHP Notice:  Undefined index: clientid

但是我知道当我运行

时,值会传递给$ results数组
print_r ($result);

我得到了这个

Array ( [0] => Array ( [clientid] => 2 [firstname] => John [lastname] => Doe [dob] => 1962-05-08))

为了它的价值,如果我尝试echo $db->Get('firstname');一切正常。我已经把头撞到墙上一段时间了,任何帮助都表示赞赏。

1 个答案:

答案 0 :(得分:0)

正如您所看到的,您在另一个数组中有一个数组。为了得到你需要的东西你需要这样:

$result[0]['clientid'];

所以我们在这里做的是你首先调用包含索引为$result的数组的[0]变量,然后这个数组包含查询中的列名(例如:{ {1}})。

所以你基本上必须比['clientid']更深入才能从数据库中获取数据,方法是先从数据库中调用包含这些键的数组。

要取消嵌套该数组,请执行以下操作:

$result['clientid']

您可以在方法中使用此功能,这样您将来只能获得正常结果。

相关问题