我觉得这是一个很容易解决的问题,但我找不到答案。我试图从数据库中获取一个特定的值,然后将其打印到屏幕上,但我一直收到以下错误:
Object of class mysqli_result could not be converted to string
我确信这是因为我请求的是整行而不是一个值。我只是不知道该怎么解决,我试过几个选项,但都不起作用。我的代码:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'mydatabase';
$connection = new mysqli ($host, $user, $pass, $db) or die ("Databse connection failed");
$sql = "SELECT waitlist_text FROM texts";
$waitlist_text = $connection->query($sql);
echo $waitlist_text
?>
数据库表名为"texts",有两列:"id"waitlist_text"。我想要id 1 上waitlist_text列下的文本
是的,查询结果为MYSQLI
对象。您必须实际使用另一个MYSQLI
函数来获取所述数据。
例如:
<?php
$result = $connection->query($sql);
while($row = $result->fetch_rows()){
print_r($row);
//In this case, you can acces results like this: echo $row[0]."<br/>";
}
?>
http://php.net/manual/en/class.mysqli-result.php
有关该主题的更多信息,请参阅上述来源。有很多方法可以获得值,例如,使用fetch_assoc()
而不是fetch_row()
。fetch_assoc()
使您可以访问您的字段(在与以前相同的while循环中),如下所示:$row['columnname']
请参阅本页的示例#1,并将您自己的函数与之进行比较。它可能会帮助您学习:http://php.net/manual/en/mysqli-result.fetch-row.php
使用where条件,绑定参数并执行例如:
$sql = 'SELECT waitlist_text FROM texts WHERE id = :idparm';
$id = 1;
$dbh = new PDO("mysql:host=$host;dbname=$db", $user, $pass);
$sth = $dbh->prepare($sql);
$sth->bindParam(':idparm', $id, PDO::PARAM_INT);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
print_r($result);
或:
while ($result = $sth->fetch(PDO::FETCH_ASSOC))
echo $result['waitlist_text'];
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'mydatabase';
$connection = new mysqli ($host, $user, $pass, $db) or die ("Databse connection failed");
$sql = "SELECT waitlist_text FROM texts";
$waitlist_text = $connection->query($sql);
while($row = $waitlist_text->fetch_assoc()) {
echo $row["waitlist_text"];
}
?>
尝试
echo $waitlist_text->fetch_row()[0]
根据PHP手册。fetch_row
将当前行作为数组,然后您可以打印第一个元素,它将是您的waitlist_text
。
您得到的是所有结果,而不是您正在寻找的结果,这是正确的。为了得到您想要的结果,您需要调用fetch_assoc()来获得第一个结果的数组。在这种情况下,$row
将是一个数组,它将包含您在从表中选择的列的名称索引下选择的所有值。它看起来是这样的:
$row = $waitlist_text->fetch_assoc();
echo $row["waitlist_text"];