【问题标题】:PHP: Get mysql data from a function as an objectPHP:从函数中获取mysql数据作为对象
【发布时间】:2014-10-30 08:52:30
【问题描述】:

我对此很陌生,所以我无法弄清楚要使用的代码。我想从一个 SQL 问题中获取一个对象,这样我就可以使用 $thePerson->FirstName 等获取数据。

我这样调用函数:

$thePerson = getPerson(1);

这是目前为止的功能:

function getPerson ($person) {
    global $con;
    $stmt = $con->prepare("SELECT * FROM personal WHERE IDA=?");
    $stmt -> bind_param('i', $person);
    $result = $stmt -> execute();
    $theData = mysqli_fetch_object($result);
    $stmt -> close();
    return $theData;
}

我真的可以使用一些帮助来更改代码以使其正常工作。

【问题讨论】:

  • 那是什么问题?你自己试过echo $thePerson->FirstName吗?
  • “警告:mysqli_fetch_object() 期望参数 1 为 mysqli_result,boolean given”是来自数据库选择部分的错误,然后我得到“注意:尝试获取非对象的属性”如果我尝试“回声 $thePerson->FirstName”

标签: php mysql


【解决方案1】:

Afaik mysql_fetch_object 不适用于准备好的语句。见Is it possible to use mysqli_fetch_object with a prepared statement。

尝试在您的声明中使用->fetch(但之前使用->bind-result)。
Examples on php.net

或者使用->query 代替您的准备/执行行,这应该返回一个与->fetch_object 一起使用的结果集。
Examples on php.net

【讨论】:

  • 谢谢,您的链接帮助我解决了这个问题,我所要做的就是替换 "$theData = mysqli_fetch_object($result);"用“$theData = $stmt->get_result()->fetch_object();”
【解决方案2】:

您需要使用 ORM:对象关系映射器,例如:http://www.doctrine-project.org/

这是一个有点高级的概念,你确定需要在你的项目中使用它吗?

【讨论】:

  • 首选是对象,但我也可以提供二维数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
  • 2021-02-04
  • 1970-01-01
  • 2020-07-09
  • 2017-09-06
相关资源
最近更新 更多