从DB表中的JSON响应中从mysql转换为mysqli的错误

时间:2015-02-25 16:40:13

标签: php mysql json mysqli

我收到以下两个错误。有人能告诉我哪里出错了。

[Error 1]mysqli_query() expects at least 2 parameters, 1 given
[Error 2]mysqli_fetch_object() expects parameter 1 to be mysqli_result, null given{"projects":[]}

这是我的代码,我正在尝试使用mysqli查询中的表行名返回JSON数据。

$databaseName = "laravel";
  $tableName = "projects";

  // 1) Connect to mysql database
    $con = mysqli_connect('localhost','root','root', 'laravel');
    $dbs = mysqli_select_db($con, 'laravel') or die(mysqli_error($con));


    $return = new stdClass();
    $return->projects = array();  

  // 2) Query database for data
    $result = mysqli_query("SELECT * FROM projects");   
    //echo mysql_errno($link) . ": " . mysql_error($link). "\n";

    if($result !== false) {
      while($row = mysqli_fetch_object($result)){
          $return->projects[] = $row;
      }
    }

    echo json_encode($return);

?>

2 个答案:

答案 0 :(得分:1)

// 1)连接到mysql数据库

$con = mysqli_connect('localhost','root','root', 'laravel');
$return = new stdClass();
$return->projects = array();  

// 2)查询数据库

$result = mysqli_query($con,"SELECT * FROM projects"); 

//echo mysql_errno($link) . ": " . mysql_error($link). "\n";

if($result !== false) {
  while($row = mysqli_fetch_object($result)){
      $return->projects[] = $row;
  }
}

echo json_encode($return);

答案 1 :(得分:0)

当你调用mysqli_query()时,第一个参数需要是连接。 所以这就是你怎么称呼它:

mysqli_query($ con,“SELECT * FROM projects”)