PDO连接到MySQL时出现500内部服务器错误

时间:2016-06-06 17:49:24

标签: php mysql pdo internal-server-error

我用PHP连接到MySQL数据库,最初我使用了mysql_方法。然后我发现这些方法已被弃用,因此我已切换到PDO,现在正在更改我的代码(我没有任何PHP PDO经验)。现在我收到了一个错误,我(以及我的同事)也无法弄清楚为什么我会得到它,代码非常简单,所以我不确定..

我有一个配置连接变量的脚本:

    <?php
define('DB_USER', "user"); // db user
define('DB_PASSWORD', "password"); // db password
define('DB_DATABASE', "myDB"); // database name
define('DB_SERVER', "localhost"); // db server
?>

然后我定义了一个连接数据库的类:

 <?php

/**
 * A class file to connect to database
 */
class DB_CONNECT {
   private $con;

    // constructor
    function __construct() {
        // connecting to database
        $this->connect();
    }

    // destructor
    function __destruct() {
        // closing db connection
        $this->con = null;
    }

    /**
     * Function to connect with database
     */
    function connect() {
        try {
        // import database connection variables
        require_once __DIR__ . '/db_config.php';

        $this->con = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_DATABASE.";charset=utf8mb4", DB_USER, DB_PASSWORD);
        $this->con -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
         return $con;

        } catch (PDOException $ex) {
            die("Error connecting to DB: ".$ex->getMessage());
        }
    }
}
?>

现在我正在运行下一个脚本,该脚本从我的数据库中的一个表中提取所有项目:

<?php

// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';

// connecting to db
$db = new DB_CONNECT();

// get all products from products table
//$result = mysql_query("SELECT * FROM ITEM") or die(mysql_error());

$query = "SELECT * FROM ITEM";
$stmt = $db->prepare($query); //eror here!

$stmt -> execute();

//foreach($db->query("SELECT * FROM ITEM") as $row) {
//    $response["products"] = array();
//}




// check for empty result
if ($stmt->fetchColumn() > 0 ) {
    // looping through all results
    // products node
    $response["products"] = array();

    while ($row =$stmt->fetch(PDO::FETCH_ASSOC)) {
        // temp user array
        $product = array();
        $product["name"] = $row["name"];
        $product["am"] = $row["am"];

        // push single product into final response array
        array_push($response["products"], $product);
    }
    // success
    $response["success"] = 1;

    // echoing JSON response
    echo json_encode($response);
} else {
    // no products found
    $response["success"] = 0;
    $response["message"] = "No products found";

    // echo no users JSON
    echo json_encode($response);
}
?>

1 个答案:

答案 0 :(得分:2)

就是这样:

$this->$con = new PDO(etc...
       ^---

$con在此上下文中未定义,这意味着您正在执行相当于$this->null = new PDO ....

的操作

请尝试使用$this->con。请注意$上缺少con