MySQLI fetch_array()

时间:2015-01-02 03:36:17

标签: php mysql mysqli

我遇到以下

的小问题
public function getSiteName() {

    $query = "SELECT name FROM siteinfo";
    $result = $this->con->query($query);

    $row = $result->fetch_array(MYSQLI_ASSOC);
    printf ("%s (%s)\n", $row["name"]);
  }

连接到数据库时我没有收到错误但是我得到以下

Fatal error: Call to a member function fetch_array() on a non-object in /Users/russellharrower/Sites/evocca/etrading/system/core.php on line 15

我想知道为什么它不起作用?我使用了http://php.net/manual/en/mysqli-result.fetch-array.php

我正在使用的引擎是 InnoDB

2 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情:

取自:http://php.net/manual/en/mysqli-result.fetch-assoc.php

<?php
    $mysqli = new mysqli("localhost", "my_user", "my_password", "world");

    /* check connection */
    if ($mysqli->connect_errno) {
        printf("Connect failed: %s\n", $mysqli->connect_error);
        exit();
    }

    $query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";

    if ($result = $mysqli->query($query)) {

        /* fetch associative array */
        while ($row = $result->fetch_assoc()) {
            printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
        }

        /* free result set */
        $result->free();
    }

    /* close connection */
    $mysqli->close();
    ?>

答案 1 :(得分:0)

所以经过一个小时的调试后,我不得不做以下几点。

对于我的项目,我使用config.php作为我放置所有数据库连接定义的地方。

的config.php

<?php
define('DBServer','localhost'); // e.g 'localhost' or '192.168.1.100'
define('DBUser','root');
define('DBPass','PASSWORD');
define('DBName','ET5');
?>

core.php中

<?php
class sys
{
  protected $con;

  public function __construct($con) {
    $this->con = $con;
  }

  public function getSiteName() {
    $query = "SELECT name FROM siteinfo";
    $result = $this->con->query($query);
    $res = array();
    while ($row = $result->fetch_array()) {
      $res[] = $row['name'];
    }
    return $res;
  }
}
?>

的index.php

<?php
require_once("system/config.php");
require_once("system/core.php");
global $con ;
$con = new mysqli(DBServer, DBUser, DBPass, DBName);
if ($con->connect_errno)
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sys = new sys($con);
$result = $sys->getSiteName();
print_r($result);
?>