使用PHP从MySQL服务器中提取数据以JSON格式显示

时间:2014-08-03 22:44:16

标签: php mysql json wordpress angularjs

我已经看到了很多关于这个问题的类似问题和答案,但我没有尝试过。所以我想我会问,因为这是我与这段代码争斗的第二天无济于事。

这是我的代码:

<?php

$con=mysqli_connect("localhost", "username", "password", "database");

//check connection
if(mysqli_connect_errno())
{
    echo "Failed to connect to MySQL" . mysqli_connect_error();
}

ini_set('display_errors',1);
error_reporting(E_ALL);


$db=new PDO("mysqli:host=localhost;dbname=table", "username","password");

//initial query
$query = "Select * FROM table";

//execute query
try {
      $stmt   = $db->prepare($query);
      $result = $stmt->execute($query_params);
     }
catch (PDOException $ex) {
      $response["success"] = 0;
      $response["message"] = "Database Error!";
      die(json_encode($response));
     }

 // Finally, we can retrieve all of the found rows into an array using fetchAll 
 $rows = $stmt->fetchAll();


 if ($rows) {
     $response["success"] = 1;
     $response["message"] = "Details Available!";
     $response["details"]   = array();

 foreach ($rows as $row) {
     $post             = array();
$post["ID"]  = $row["ID"];
     $post["cohort_name"] = $row["cohort_name"];
     $post["pin"]    = $row["pin"];
     $post["start_date"]  = $row["start_date"];

     //update our repsonse JSON data
     array_push($response["details"], $post);
    }


     // echoing JSON response
     echo json_encode($response);

   } else {
            $response["success"] = 0;
            $response["message"] = "No Details Available!";
            die(json_encode($response));
       }

   ?>

我的PHP太糟糕了,如果不是所有人都阅读其他人使用的内容,我得到了大部分内容。我在这里得到的错误代码是:

  

致命错误:未捕获的异常'PDOException',消息'无法在&gt;'url to php page'中找到驱动程序':15堆栈跟踪:#0&gt;'url to php page'(15):PDO-&gt ; __ construct('mysqli:host = loc ...',&gt;'username','password')#1 {main}在第15行&gt;'url to php page'中抛出

我正在使用运行wordpress的MySQL服务器,我想要解决这个问题并直接连接到数据库,因为我正在为Angular应用程序设置一个单独的用户系统(因此我为什么要使用JSON)我我已经使用.php页面从wordpress网站直接写入相同的sql表但是有问题的php页面会抛出某种错误,如上面的错误,或者根本不抛出任何东西,只是一个空白页面。任何见解将不胜感激。

1 个答案:

答案 0 :(得分:2)

首先,这部分代码不是必需的

$con=mysqli_connect("localhost", "username", "password", "database");

//check connection
if(mysqli_connect_errno())
{
    echo "Failed to connect to MySQL" . mysqli_connect_error();
}

此外,PDO连接应该是这样的

$db = new PDO('mysql:host=localhost;dbname=table', $user, $pass);

确保为table$user$pass提供正确的值

您可以阅读有关PDO连接的更多信息here