使用$ row->元素而不是$ row ["元素"]的数据库查询(while或foreach)

时间:2014-07-02 07:13:19

标签: php mysql sql

我想创建一个简单的脚本,但我想允许用户使用$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'];

3 个答案:

答案 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);