Querying Mysql with PDO fetch returns false - php

I am trying to query my database in PDO and have the output on a form. However the fetch statement does not work. The code is
try {
include '../../config/database.php';
$database = new Database();
$db = $database->getConnection();
//prepare query
$query = "select
payment_id, payment_supplier, payment_ref, payment_cost_rating, payment_amount
from
payments
where
payment_id = ?
limit 0,1";
$stmt = $db->prepare( $query );
//this is the first question mark
$stmt->bindParam(1, $_REQUEST['myData']);
//execute our query
if($stmt->execute()){
var_dump($stmt->fetch());
//store retrieved row to a variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);
//values to fill up our form
$payment_id = $row['payment_id'];
$payment_supplier = $row['payment_supplier'];
$payment_ref = $row['payment_ref'];
$payment_cost_rating = $row['payment_cost_rating'];
$payment_amount = $row['payment_amount'];
}else{
echo "Unable to read record.";
}
}
var_dump ($stmt); prints
object(PDOStatement)#3 (1) { ["queryString"]=> string(157) "select payment_id, payment_supplier, payment_ref, payment_cost_rating, payment_amount from payments where payment_id = ? limit 0,1" }
But fetch() always returns false. This is the included database.php file if it helps
class Database{
// database credentials
private $host = "localhost";
private $db_name = "test-project";
private $username = "root";
private $password = "";
public $conn;
// get the database connection
public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}}
What am I missing here?

The issue is with the fetch being used twice.
It can be done this way:
if($stmt->execute()){
//store retrieved row to a variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);
// display the row after fetching the contents.
var_dump($row);
//values to fill up our form
$payment_id = $row['payment_id'];
$payment_supplier = $row['payment_supplier'];
$payment_ref = $row['payment_ref'];
$payment_cost_rating = $row['payment_cost_rating'];
$payment_amount = $row['payment_amount'];
}else{
echo "Unable to read record.";
}
This should work well.

Add checking of execute result and see error:
if($stmt->execute()){
...
}else{
echo "Unable to read record:". print_r($stmt->errorInfo(), true);
}

Related

using variable inside mysql update query in php

<?php
require 'functions/connection.php';
$conn = Connect();
$e_id = $conn->real_escape_string($_POST['e_id']);
$first_name = $conn->real_escape_string($_POST['first_name']);
$last_name = $conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->real_escape_string($_POST['e_department']);
$sql = "UPDATE employee SET firstname='$first_name' WHERE id=$e_id";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
I'm trying to use the first_name variable inside the update query.
I tried echo the variable and its working...
this is my connection code that im using.
<?php
function Connect()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "company";
// Create connection
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname) or die($conn->connect_error);
return $conn;
}
?>
if i i replace the variable with anything between "" the database is getting updated
I'd suggest making it more secure and using prepared statements. This is an example using mysqli, but I prefer PDO:
<?php
require 'functions/connection.php';
$conn = Connect();
// Prepare the query
$myQuery = $conn->prepare("UPDATE employee SET firstname=? WHERE id=?");
$e_id = $conn->real_escape_string($_POST['e_id']);
$first_name = $conn->real_escape_string($_POST['first_name']);
$last_name = $conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->real_escape_string($_POST['e_department']);
// Bind your variables to the placemarkers (string, integer)
$myQuery->bind_param('si', $first_name, $e_id);
if ($myQuery->execute() == false) {
echo 'Error updating record: ' . $mysqli->error;
}
else {
echo 'Record updated successfully';
}
$myQuery->close();
?>
Note: The 'cleansing' you're doing in the middle I have left, but it's not really necessary with prepared statements.
functions/connection.php (Now an object):
<?php
class Connect
{
private $dbhost = "localhost";
private $dbuser = "root";
private $dbpass = "";
private $dbname = "company";
public $conn;
public function __construct()
{
if($this->conn = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname))
{
//connection established
//do whatever you want here
}
else
{
//Error occurred
die($this->conn->error);
}
}
//other functions here
}
?>
Change mysqli_query to: $conn->conn->query($sql);
Prepared statement:
Avoid SQLI injection
if($stmt = $conn->conn->prepare("UPDATE employee SET firstname = ? WHERE id = ?"))
{
$stmt->bind_param('si', $first_name, $e_id);
$stmt->execute();
echo $stmt->affected_rows;
}
Final code:
<?php
require 'functions/connection.php';
$conn = new Connect();
$e_id = $conn->conn->real_escape_string($_POST['e_id']);
$first_name = $conn->conn->real_escape_string($_POST['first_name']);
$last_name = $conn->conn->real_escape_string($_POST['last_name']);
$e_salary = $conn->conn->real_escape_string($_POST['e_salary']);
$e_startdate = $conn->conn->real_escape_string($_POST['e_startdate']);
$e_department = $conn->conn->real_escape_string($_POST['e_department']);
if($stmt = $conn->conn->prepare("UPDATE employee SET firstname = ? WHERE id = ?"))
{
$stmt->bind_param('si', $first_name, $e_id);
$stmt->execute();
echo $stmt->affected_rows;
}
$conn->conn->close();
?>

Error on calling a function with connection to SQL server

I am getting
Fatal error: Call to a member function query() on a non-object in
C:...\test.php on line 27
after calling callQuery2.
<?php
dbConnect();
callQuery1();
callQuery2();
function callQuery1(){
// SQL query
$q = "SELECT * FROM table1 WHERE name like 'john%' ";
// Execute query
$data1 = exeQuery($q);
}
function callQuery2(){
// SQL query
$q = "SELECT * FROM table2 WHERE event = 'holiday' ";
// Execute query
$data2 = exeQuery($q);
}
// Execute SQL Query
function exeQuery($qry) {
global $pdo;
####### LINE 27 #######
$stmt = $pdo->query($qry);
if($stmt = $pdo->prepare($qry)) {
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $data;
}
}
// database connection
function dbConnect(){
$DBSERVER = "***";
$DBUSER = "***";
$DBPASS = "***";
$DBNAME = "***";
// OBDC
try {
$pdo = new PDO("odbc:DRIVER={SQL Server};Server={$DBSERVER};Database={$DBNAME}", $DBUSER, $DBPASS);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex) {
//die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
}
}
?>
Why the error only appears after at that time?
Is the a better way to do this?
Regards,
Elio Fernandes
This would be better encapsulated without the global $pdo; part. Instead return the PDO object from your connect method, and pass it to the others, to be used.
N.B. I've deliberately given the variables different names in different places, to illustrate that the name doesn't have to be the same when it's passed from one scope to another, it's the object that's passed which is important. You might perhaps consider using consistent names though, to make it easier to comprehend the code later, and trace the object through the flow.
<?php
$dbConn = dbConnect();
callQuery1($dbConn);
callQuery2($dbConn);
function callQuery1($db){
// SQL query
$q = "SELECT * FROM table1 WHERE name like 'john%' ";
// Execute query
$data1 = exeQuery($q, $db);
}
function callQuery2($db){
// SQL query
$q = "SELECT * FROM table2 WHERE event = 'holiday' ";
// Execute query
$data2 = exeQuery($q, $db);
}
// Execute SQL Query
function exeQuery($qry, $pdo) {
####### LINE 27 #######
$stmt = $pdo->query($qry);
if($stmt = $pdo->prepare($qry)) {
$stmt->execute();
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->closeCursor();
return $data;
}
}
// database connection
function dbConnect(){
$DBSERVER = "***";
$DBUSER = "***";
$DBPASS = "***";
$DBNAME = "***";
// OBDC
try {
$pdo = new PDO("odbc:DRIVER={SQL Server};Server={$DBSERVER};Database={$DBNAME}", $DBUSER, $DBPASS);
// set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
catch(PDOException $ex) {
//die(json_decode(array('outcome' => false, 'message' => 'Unable to connect')));
}
}
?>

Simple PHP MYSQL select statement doesn't return anything

Alright, so I have a simple database with one table, and I have a function which is supposed to get all the rows for that one table:
function get_days() {
global $db;
$query = 'SELECT * FROM days'
. 'ORDER BY idDays';
$statement = $db ->prepare($query);
$statement ->execute();
$the_days = $statement->fetchAll();
//$statement->closeCursor();
return $the_days;
//return $statement;
}
I've checked everything else, everything else functions just fine, including the part of my site where I input data into the table, that insert statement works just fine, so I've narrowed it down to this one select statement.
The problem is in you SQL syntax. You should do this:
function get_days() {
global $db;
$query = 'SELECT * FROM days '
. 'ORDER BY id';
$statement = $db ->prepare($query);
$statement ->execute();
$the_days = $statement->fetchAll();
//$statement->closeCursor();
return $the_days;
//return $statement;
}
The problem is the string concatenation of your query:
$query = 'SELECT * FROM days' . 'ORDER BY idDays';
This results in: SELECT * FROM daysORDER BY idDays
Include a space character instead:
$query = 'SELECT * FROM days' . ' ORDER BY idDays';
You can avoid problems like this with proper error handling:
try{
$statement->execute();
}
catch(PDOException $e){
exit($e->getMessage());
}
You might also want to remove the spaces in:
$db ->prepare($query);
$statement ->execute();
So they become:
$db->prepare($query);
$statement->execute();
This is simple way to select you can use a function for it.
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM days ORDER BY idDays";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//do anything
}
} else {
echo "0 results";
}

How to CRUD using PDO Connection?

I want to CRUD using PDO Connection
I know how to create insert update and delete using msql_query() but I have no idea how to do that with PDO Connection.
Below is the example of that
class connection{
public $cnn;
public function __construct(){
$host = 'localhost';
$db_name = "db_name";
$username = "db_username";
$password = "db_password";
try {
$this->cnn = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
public function select($query){ //this function is created for get data
$result = $this->cnn->query($query);
return $result->fetchAll(PDO::FETCH_ASSOC);
}
public function insert($query){ //this function is created for insert data. it will be return last inserted id.
$this->cnn->exec($query);
return $this->cnn->lastInsertId();
}
public function update($query){ //this function is created for update data and it will be return effected rows (which are updated)
return $this->cnn->exec($query);
}
public function delete($query){ // this function is use to delete data.
return $this->cnn->exec($query);
}
}
$action = new connection;
$result = $action->select("select * from table_name");
print_r($result);
$result = $action->insert("insert into table_name set column_1 = 'first_value', column_2='second_value'");
$result = $action->update("update table_name set column_1 = 'first_value', column_2='second_value' where id=1");
$result = $action->delete("delete from table_name where id=1");
Maybe this is an easier way to do it. now the only thing you have to do is call the functions. Enjoy (:
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "database";
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
function updateuser($pdo, $username, $password, $id){
$sql = "UPDATE users SET username=?, password=? WHERE id=?";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password, $id]);
}
function deleteuser($pdo, $id){
$sql = 'DELETE FROM users WHERE id = ?';
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
}
function createuser($pdo, $username, $password){
$sql = "INSERT INTO users (username, password) VALUES (?,?)";
$stmt= $pdo->prepare($sql);
$stmt->execute([$username, $password]);
}
function readuser($pdo, $id){
$sql = "SELECT id, username FROM users WHERE id=?";
$statement = $pdo->prepare($sql);
$statement->execute([$id]);
return $statement->fetchAll(PDO::FETCH_ASSOC);
}

Function returns boolean not string

What I want is to return MYSQL query in a array however my code returns a bool(true).
Here is the code from code.php
require('model.php');
$id = $_POST['id'];
$password = $_POST['password'];
$user = new user();
$row = $user->check_user($id, $password);
var_dump($row);
Here is the code from model.php
class config {
public $dbhost = "localhost";
public $dbuser = "root";
public $dbpass = "";
public $dbused = "dbname";
function dbconn() {
$conn = mysqli_connect($this->dbhost,$this->dbuser,$this->dbpass,$this->dbused);
if(mysqli_connect_errno()) {
printf("Connection failed: " . mysqli_connect_error());
exit();
}
return $conn;
}
}
class user {
function check_user($id, $pass) {
$config = new config();
$conn = $config->dbconn();
$query = $conn->prepare("SELECT id, password, status FROM e_users WHERE id = ? AND password = ?");
$query->bind_param('is', $id, $pass);
try {
$query->execute();
return $query->fetch();
} catch(PDOException $e) {
die($e->getMessage());
}
}
}
I think the problem is in the $query->fetch(); because I tried return 'test'; and it works fine. Even return an array works fine.
Can anyone help me?
As The Blue Dog pointed out, fetch() returns a status flag, not the row itself. But fetch_assoc() will return a row.
Have a look here:
http://php.net/manual/en/mysqli-stmt.fetch.php
If you work with fetch, you need to bind the variables:
$stmt->bind_result($mySelectedValue_1, $mySelectedValue_2);
Here are examples with fetch_assoc():
http://php.net/manual/de/mysqli.quickstart.prepared-statements.php
So this should work fine:
$row = $res->fetch_assoc();

Categories