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);
}
?>
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.
Related
this is my php file
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['userName']) && isset($_POST['userContact']) && isset($_POST['userAddress']) && isset($_POST['userStore']) && isset($_POST['userRequest'])) {
$userName = $_POST['userName'];
$userContact = $_POST['userContact'];
$userAddress = $_POST['userAddress'];
$userStore = $_POST['userStore'];
$userRequest = $_POST['userRequest'];
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = "INSERT INTO userrequests(userName, contactNumber, userAddress, storeList, requestBody) VALUES('$userName', '$userContact', '$userAddress', '$userStore', '$userRequest')";
// check if row inserted or not
if (mysqli_query($result,$db)) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
echo $result;
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
And this is my db_connect.php
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE) or die(mysqli_error());
// Selecing database
$db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error()) or die(mysqli_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
}
}
?>
It seems that there's something wrong with my code and this is the error I got
mysqli_query() expects parameter 1 to be mysqli, string given in. Anyone knows how to solve this ? I have searched through StackOverFlow regarding this and tried all the solutions but still cant be solved.
Modify your db connect class to maintain the connection:
class DB_CONNECT {
protected $connection = null;
// constructor
function __construct() {
// connecting to database
$this->connection = $this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE) or die(mysqli_error());
// Selecing database
$db = mysqli_select_db($con,DB_DATABASE) or die(mysqli_error()) or die(mysqli_error());
// returing connection cursor
return $con;
}
public function getConnection() {
return $this->connection;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
}
}
Then modify your query line to:
if (mysqli_query($db->getConnection(), $result)) {
http://docs.php.net/mysqli_query:
Procedural style
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
The first parameter must be a valid/active connection resource that has been returned by mysqli_connect()
As the error said, your first parameter should be the mysqli class, not the query. Like this:
if (mysqli_query($db, $result)) {
use this
mysqli_query($db,$result) //connection first.. query at second position
instead of
mysqli_query($result,$db)
It has to be like this
$result = "INSERT INTO userrequests(userName, contactNumber, userAddress, storeList, requestBody) VALUES('$userName', '$userContact', '$userAddress', '$userStore', '$userRequest')";
// check if row inserted or not
if (mysqli_query($db,$result)) {
}
I am trying to get a JSON from a MySQL database, but it does not recover anything. Here my code:
db_config.php
<?php
/*
* All database connection variables
*/
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "biblioapp"); // database name
define('DB_SERVER', "localhost"); // db server
?>
db_connect
<?php
/**
* A class file to connect to database
*/
class DB_CONNECT{
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
get_products_details.php
<?php
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
$search = '';
if (isset($_POST['search'])){
$search = strtolower($_POST['search']);
// get a product from products table
$result = mysql_query("SELECT * FROM registres WHERE titol LIKE '%".$search."%' OR autor LIKE '%".$search."%'");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["id"] = $result["id"];
$product["titol"] = $result["titol"];
$product["autor"] = $result["autor"];
$product["descripcion"] = $result["descripcion"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
get_all_products.php
<?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 registres") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["registres"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["id"] = $result["id"];
$product["titol"] = $result["titol"];
$product["autor"] = $result["autor"];
$product["descripcion"] = $result["descripcion"];
// push single product into final response array
array_push($response["registres"], $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);
}
?>
If I go to localhost/json/get_product_details.php I receive this:
{"success":0,"message":"Required field(s) is missing"}
If i go to localhost/json/get_all_products.php I receive this:
{"registres":[{"id":null,"titol":null,"autor":null,"descripcion":null},{"id":null,"titol":null,"autor":null,"descripcion":null},{"id":null,"titol":null,"autor":null,"descripcion":null},{"id":null,"titol":null,"autor":null,"descripcion":null},{"id":null,"titol":null,"autor":null,"descripcion":null}],"success":1}
What's wrong here? Thanks...
while ($row = mysql_fetch_array($result)) {
$product = array();
$product["id"] = $result["id"];
Your results are not in $result, but in $row :
$product["id"] = $row["id"];
I see nothing common with json in your issue :-)
The only problem you have - empty values in array you've created.
You didn't give us any information about table structure you have, and values you are trying to debug.
So just a quick fix to start better debugging could be:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$response["registres"][] = $row;
}
but reviewing your code I want to suggest you to stop using deprecated mysql_ calls. Use mysqli or PDO.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
i am beginer to php and i need your help.i want to make the following code to PDO to have a json output for an android app i am trying to bulit.I tryed a lot of solution but nothing correct came because of the JSON responce.I couldn also find good example and tutorials.Also i am new as i said with php so i am afraid to try complicated scenarios
here is the php code
This is my Config file
db_config.php
<?php
define('DB_USER', "root"); // db user
define('DB_PASSWORD', ""); // db password (mention your db password here)
define('DB_DATABASE', "androidhive"); // database name
define('DB_SERVER', "localhost"); // db server
?>
This is connection file
db_connect.php
<?php
class DB_CONNECT {
// constructor
function __construct() {
// connecting to database
$this->connect();
}
// destructor
function __destruct() {
// closing db connection
$this->close();
}
/**
* Function to connect with database
*/
function connect() {
// import database connection variables
require_once __DIR__ . '/db_config.php';
// Connecting to mysql database
$con = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD) or die(mysql_error());
// Selecing database
$db = mysql_select_db(DB_DATABASE) or die(mysql_error()) or die(mysql_error());
// returing connection cursor
return $con;
}
/**
* Function to close db connection
*/
function close() {
// closing db connection
mysql_close();
}
}
?>
get_all_products.php
<?php
/*
* Following code will list all the products
*/
// 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 products") or die(mysql_error());
// check for empty result
if (mysql_num_rows($result) > 0) {
// looping through all results
// products node
$response["products"] = array();
while ($row = mysql_fetch_array($result)) {
// temp user array
$product = array();
$product["pid"] = $row["pid"];
$product["name"] = $row["name"];
$product["price"] = $row["price"];
$product["created_at"] = $row["created_at"];
$product["updated_at"] = $row["updated_at"];
// 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);
}
?>
I know is very easy for someone with experience but i am strungle with it.please help because i have a strick deadline and no time now for deaper search.Thank you
**Would it be helpfull if i post what i have done?I didnt post it for space reason**s
EDIT
THIS IS WHAT I HAVE DONE SO FAR ANY IDEAS?
$db = new PDO("mysql:host=$dbhost;dbname=$dbname;", $dbuser, $dbpass);
$query = "Select * FROM products";
//execute query
try {
$stmt = $db->prepare($query);
$result = $stmt->execute(HAVE NO IDEA!!!!);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error!";
die(json_encode($response));
}
$rows = $stmt->fetchAll();
if ($rows) {
$response["success"] = 1;
$response["message"] = "Post Available!";
$response["posts"] = array();
foreach ($rows as $row) {
$post = array();
$post["pid"] = $row["pid"];
$post["name"] = $row["name"];
$post["price"] = $row["price"];
//update our repsonse JSON data
array_push($response["posts"], $post);
}
// echoing JSON response
echo json_encode($response);
} else {
$response["success"] = 0;
$response["message"] = "No Post Available!";
die(json_encode($response));
}
?>
Try this approach:
<?php
$response = array()
try {
//connection
$db = new PDO("mysql:host=$dbhost;dbname=$dbname;", $dbuser, $dbpass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//prepare
$query = "Select * FROM products";
$stmt = $db->prepare($query);
//get resutlt
$result = $stmt->execute();
if ($stmt->rowCount > 0) {
$response["success"] = true;
$response["message"] = "Post Available!";
//populate post array
while($row = $stmt->fetch()){
$response["posts"][] = $row;
}
}else{
$response["success"] = false;
$response["message"] = "No Post Available!";
}
}
catch (PDOException $ex) {
$response["success"] = false;
$response["message"] = "Database Error!";
}
echo json_encode($response);
?>
Prepared statements and stored procedures
using fetch all:
$rows = $stmt->fetchAll();
var_dump($rows);
$response["posts"] = $rows;
I've bought a domain-hosting from a local company. Their customer service is pretty horrible.
My code for connecting to the database seems ok but still its not working. Here my code:
function __construct(){
if(!#mysql_ping()){
$this->db_connect();
}
$sql = "SELECT value FROM settings WHERE field = 'auto_logout'";
$res = mysql_fetch_array($this->execute_single_query($sql));
$this->LOGIN_DURATION = $res['value'];
}
private function db_connect(){
// Mysql connect
$link = #mysql_connect('localhost', 'created_who_has_all_prev', 'pass_note_my_cpanel_and_mysql_has_same_pass');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully<br/>';
// Mysql select db select --->
$db_selected = mysql_select_db($this->DB, $link);
if (!$db_selected) {
die ('Can\'t use specified Database : ' . mysql_error());
}
//echo "<br/>Database Selected<br/>";
return $link;
}
And this is the snapshot:
Your main problem is that the link that you create isn't accessible. So, PHP tries to connect with defaults (apparently in your setup it means the user is root) and since it has no password, the connection fails which is the cause of most of your warning messages.
The last warning is a consequence of the others.
To fix this problem - as you haven't provided details of the actual parts that are executing the query - here is how to re-write your code so it works:
$mysqli = new mysqli("localhost", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "(".$mysqli->connect_errno.") ".$mysqli->connect_error;
}
$sql = "SELECT `value` FROM `settings` WHERE `field` = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param("s","auto_logout");
if (!$stmt->execute()) {
echo "(".$stmt->errno.") ".$stmt->error;
}
$res = $stmt->get_result();
$row = $res->fetch_assoc();
LOGIN_DURATION = $row['field'];
This is really sloppy code. I would use PDO as it is secure. Below is a class you can use but study how it works and why it works.
class Core {
public $dbh; // handle of the db connection
private static $instance;
private function __construct() {
$options = array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->dbh = new PDO("mysql:host=localhost;dbname=dealership", "root", "",$options);
}
public static function getInstance() {
if (!self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __clone() {}
private function __wakeup() {}
}
In your code call it like below:
require "/classes/pdo.class.php";
$db = Core::getInstance();
$stmt = "SELECT `lastname` FROM `employees` where id = 2";
$pep = $db->dbh->prepare($stmt);
$pep->execute();
foreach($pep->fetchAll(PDO::FETCH_ASSOC) as $row) {
echo $row['lastname']. "\n";
}
Make sure you look into PDO, prepared statments, and singleton pattern to understand why it works.
I know I can close a PDO SQL connection setting the handler to NULL.
But if I don't do that, does PHP close the connection at the end of the script?
Fore example, can I use
$db = new PDO('sqlite:db.sqlite');
/* Code */
if ($cond1) { exit; }
/* More code */
if ($cond2) { exit; }
/* ... */
$db = NULL;
/* Code not related to the database */
... or should I use this:
$db = new PDO('sqlite:db.sqlite');
/* Code */
if ($cond1) {
$db = NULL;
exit;
}
/* More code */
if ($cond2) {
$db = NULL;
exit;
}
/* ... */
$db = NULL;
/* Code not related to the database */
According to the docs:
The connection remains active for the lifetime of that PDO object. To
close the connection, you need to destroy the object by ensuring that
all remaining references to it are deleted--you do this by assigning
NULL to the variable that holds the object. If you don't do this
explicitly, PHP will automatically close the connection when your
script ends.
EXAMPLE.
This is your dbc class
<?php
class dbc {
public $dbserver = 'server';
public $dbusername = 'user';
public $dbpassword = 'pass';
public $dbname = 'db';
function openDb() {
try {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
} catch (PDOException $e) {
die("error, please try again");
}
return $db;
}
function getAllData($qty) {
//prepared query to prevent SQL injections
$query = "select * from TABLE where qty = ?";
$stmt = $this->openDb()->prepare($query);
$stmt->bindValue(1, $qty, PDO::PARAM_INT);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $rows;
}
?>
your PHP page:
<?php
require "dbc.php";
$getList = $db->getAllData(25);
foreach ($getList as $key=> $row) {
echo $row['columnName'] .' key: '. $key;
}
Your connection will be closed as soon as the results are returned
According to the docs When you call exit:
Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called.
This means your PDO connection will be closed. It's always good practice to close it yourself though.