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)) {
}
Related
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.
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.
I'm transitioning from MYSQL to MYSQLI and I am in need of assistance with putting MYSQLI into separate / distinct functions.
From all the "tutorials" i have located on the web, they all have everyrything in one big long code, and not distinct / separate functions that my main scripts can call.
Eg :-
Connect to MYSQLI
Do SELECT
Exit MYSQLI
what i'm after is :-
MYSQLI.PHP
<?
function connect_mysqli()
{
$con=mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_errno();
}
// Return the connection back to where i called it ??
}
function do_query ($sql)
{
$row = $con->query("$sql")->fetch_array();
return $row;
}
function close_mysqli()
{
$mysqli->close();
}
?>
in my script i want to call :-
another.php
<?
include_once("MYSQLI.PHP");
connect_mysqli();
....
do some SELECT
do some UPDATE
close_mysqli();
?>
So far, from the error codes I am receiving, the "connection" to mysqli is not being passed to/from my other script(s)
Has anyone got a working / tested example of mysqli using functions (not just half the code) - but a working example of simple SELECT
Once i get that far, i can do the rest.
fix your include file to
/**
* #return mysqli
*/
function connect_mysqli()
{
$con = mysqli_connect("localhost","wrong_user","my_password","my_db");
// Check connection
if (!$con)
{
die("Connection error: " . mysqli_connect_errno());
}
return $con;
}
function do_query ($con, $sql)
{
$row = $con->query("$sql");
if($row) {
return $row->fetch_array();
}
return null;
}
function close_mysqli($con)
{
$con->close();
}
now you can run a script like this
include_once("MYSQLI.PHP");
$connection = connect_mysqli();
if(null !== $connection) {
print_r(do_query($connection, "SELECT * FROM yourTable"));
close_mysqli($connection);
}
but for correct handling create a connection interface and a implementation for mysqli like this
interface myConnectionClass {
function connect();
....
}
and a mysqli implementation
class myMysqlIConnection implements myConnectionClass {
function connect() {
//do more... save connection etc...
return true; //sucess
}
}
Example Demos
Scroll down there are a lot of exmaples...
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Create table doesn't return a resultset */
if ($mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City") === TRUE) {
printf("Table myCity successfully created.\n");
}
/* Select queries return a resultset */
if ($result = $mysqli->query("SELECT Name FROM City LIMIT 10")) {
printf("Select returned %d rows.\n", $result->num_rows);
/* free result set */
$result->close();
}
/* If we have to retrieve large amount of data we use MYSQLI_USE_RESULT */
if ($result = $mysqli->query("SELECT * FROM City", MYSQLI_USE_RESULT)) {
/* Note, that we can't execute any functions which interact with the
server until result set was closed. All calls will return an
'out of sync' error */
if (!$mysqli->query("SET #a:='this will not work'")) {
printf("Error: %s\n", $mysqli->error);
}
$result->close();
}
$mysqli->close();
?>
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.