我想创建一个简单的脚本,但我想允许用户使用$row->title
代替$row['title']
。
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_array($result)) {
echo $row['FirstName'] . " " . $row['LastName']; //THIS IS THE PROBLEM, SEE BELOW
echo "<br>";
}
mysqli_close($con);
我想将其设为echo $row->FirstName . " " . $row->LastName
而不是echo $row['FirstName'] . " " . $row['LastName'];
答案 0 :(得分:3)
使用 mysqli_fetch_object 代替mysql_fetch_array
将结果集作为对象。
答案 1 :(得分:1)
检查Manual以查找返回对象而不是数组的mysqli_fetch_object。使用以下代码
while($row = mysqli_fetch_object($result)) {
echo $row->FirstName . " " . $row->LastName;
echo "<br>";
}
答案 2 :(得分:1)
由于->
operator
与对象一起使用,您需要以object
形式而不是array or assoc array
来获取数据。
$con=mysqli_connect("example.com","peter","abc123","my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM Persons");
while($row = mysqli_fetch_object($result)) {
echo $row->FirstName . " " . $row->LastName; //THIS IS THE PROBLEM, SEE BELOW
echo "<br>";
}
mysqli_close($con);