返回结果集的当前行,然后打印每个字段的值:
<?php
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
if ($mysqli -> connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
exit();
}
$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";
if ($result = $mysqli -> query($sql)) {
while ($obj = $result -> fetch_object()) {
printf("%s (%s)\n", $obj->Lastname, $obj->Age);
}
$result -> free_result();
}
$mysqli -> close();
?>
查看底部的程序样式示例。
fetch_object() / mysqli_fetch_object() 函数将结果集的当前行作为对象返回。
笔记:从此函数返回的字段名称区分大小写。
$mysqli_result -> fetch_object(
classname,
params)
mysqli_fetch_object(
result,
classname,
params)
Parameter | Description |
---|---|
result | Required. Specifies a result set identifier returned by mysqli_query(), mysqli_store_result() or mysqli_use_result() |
classname | Optional. Specifies the name of the class to instantiate, set the properties of, and return |
params | Optional. Specifies an array of parameters to pass to the constructor for classname objects |
返回值: | 返回具有所获取行的字符串属性的对象。如果结果集中没有更多行,则为 NULL |
---|---|
PHP 版本: | 5+ |
变更日志: | PHP 5.0.0 中添加了作为不同对象返回的功能 |
返回结果集的当前行,然后打印每个字段的值:
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
$sql = "SELECT Lastname, Age FROM Persons ORDER BY Lastname";
if ($result = mysqli_query($con, $sql)) {
while ($obj = mysqli_fetch_object($result)) {
printf("%s (%s)\n", $obj->Lastname, $obj->Age);
}
mysqli_free_result($result);
}
mysqli_close($con);
?>
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!