我在打印MySQLi查询中的值时遇到问题。这是我正在使用的数据库连接类。
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');
,一切都会成功。我的头撞在墙上已经有一段时间了,谢谢你的帮助。
正如您所看到的,您在另一个数组中有一个数组。要得到你需要的东西,你需要这样做:
$result[0]['clientid'];
因此,我们在这里要做的是,首先调用$result
变量,该变量包含一个索引为[0]
的数组,然后这个数组包含查询中的列名(例如:['clientid']
)。
因此,您基本上必须比$result['clientid']
更深入地从数据库中获取数据,方法是首先从数据库中调用包含这些键的数组。
要取消嵌套该数组,请执行以下操作:
$result = $db->Get();
$normal_result = 0;
foreach ($result as $value)
{
$normal_result = $value;
}
你可以在你的方法中使用这个,所以你只会在未来得到正常的结果。