eee eee - 6 months ago 124
MySQL Question

500 Internal Server Error with PDO connecting to MySQL

I'm connecting to a MySQL database with PHP, and in the beginning I used the mysql_ methods. I then found out that these methods are deprecated, so I've switched to PDO, and am now in the midst of changing my code (and I don't have any experience with PHP PDO). Now I'm getting an error and I (and also my colleague) cannot figure out why I get it, and the code is very straightforward, so I'm not sure..

I have a script that configures connection variables like this:

<?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
?>


Then I've defined a class for connecting to the database:

<?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());
}
}
}
?>


Now I'm running this next script, which fetches all items from one table in my database:

<?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);
}
?>

Answer

It's this:

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

$con is undefined in this context, which means you're doing the equivalent of $this->null = new PDO ....

Try $this->con instead. Note the lack of $ on con.