How to get single value in php instead of $stmt->fetchObject(); - php

This is my function.
public function getOrderValue($order_id) {
$sql = "select SUM(OD.quantity * OD.product_sell_price) from table_order_details OD where OD.order_id= :order_id AND OD.is_delete = 0";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("order_id", $order_id);
$stmt->execute();
$user = $stmt->fetchObject();
return $user;
} catch(PDOException $e) {
return NULL;
//echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
As there is only single column in query, How to return that value? Basically i want how to fetch SUM alone instead of returning an object $stmt->fetchObject();

You can use fetchColumn, but there is nothing wrong with returning $user->total or something similar.
public function getOrderValue($order_id) {
$sql = "SELECT SUM(OD.quantity * OD.product_sell_price) AS total FROM table_order_details OD WHERE OD.order_id= :order_id AND OD.is_delete = 0";
try {
$stmt = $this->db->prepare($sql);
$stmt->bindParam("order_id", $order_id);
$stmt->execute();
$total = $stmt->fetchColumn();
return $total;
} catch(PDOException $e) {
return NULL;
}
}

Assuming you're using PDO, you could use fetchColumn
http://php.net/manual/en/pdostatement.fetchcolumn.php

Related

SQL request dont work as expected

i have a PHP REST API, i did this function to get services with a certain idpro or idclient
function getServices($request) {
require_once 'db.php';
$emp = json_decode($request->getBody());
$id = $request->getAttribute("id");
$sql = "select * FROM service WHERE idpro=:idpro OR idclient= :idclient ORDER BY date_debut DESC";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("idpro", $id);
$stmt->bindParam("idclient", $id);
$stmt->execute();
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
return json_encode( $wines);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
I have in my database a row with idpro=40 and idclient=30 when i execute this function with id=40 in get the disered result but when i execute it with id=30 i dont get anything, i tried to execute this line in PHPMYADMIN: select * FROM service WHERE idpro=30 OR idclient= 30 and it worked as expected
$sql = "select * FROM service WHERE idpro=:idpro OR idclient=:idclient ORDER BY date_debut DESC";
You mentioned that it worked with idpro and it has no space between the parameter and value so try and remove the space between idclient= :idclient to see if thats the issue. Since it works when you execute the line I assume that its how it is syntactically called.
OR
Try using one parameter for the value. Change like this:
function getServices($request) {
require_once 'db.php';
$emp = json_decode($request->getBody());
$id = $request->getAttribute("id");
$sql = "select * FROM service WHERE idpro=:myID OR idclient= :myID ORDER BY date_debut DESC";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("myID", $id);
$stmt->execute();
$wines = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
return json_encode( $wines);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

Using PHP and MySQL, how do you send a variable into a WHERE... IN clause?

The following SELECT statement works just fine:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (65,70,80)');
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
BUT when I try to send a variable into the WHERE clause, I only get one row back.
In this case $ids is a string that looks like '65,70,80'.
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, $ids);
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Do I need to change the way I'm fetching the data, or is my syntax wrong?
A-HA! Thanks for that link Mihai. Here's the code that works:
First: instead of passing in a string, put ids into an $ids array.
// Figure out how many ? marks have to be in your query as parameter placeholders.
$count = count($ids);
$arrayOfQuestions = array_fill(0, $count, '?');
$queryPlaceholders = implode(',', $arrayOfQuestions);
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (' . $queryPlaceholders . ')');
$sql->execute($ids);
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
Try this:
try {
$sql = $db->prepare('SELECT *
FROM classes
WHERE classes.id IN (?)');
$sql->bindParam(1, explode(',', $ids));
$sql->execute();
$sublist = $sql->fetchAll(PDO::FETCH_ASSOC);
} catch(Exception $e) {
echo $e->getMessage();
die();
}

How to get rest api output the number of row imputed on the url

I created a REST API and I've come to the point where I want to output 20 rows (e.g.) if I access the API like http://api.randomuser.me/?results=20.
This is my PHP code. I am new to Slim and AngularJS, please help.
function getUsers() {
$sql = "select * FROM user";
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Thanks in advance.
You will have to change your sql... something like
$limit = $_GET['limit'];
/clean your input make sure it has a value using isset,empty etc
$sql = "select * FROM user ORDER BY id LIMIT ".$limit; //this is a quick example rather use pdo bound parameters.
try {
$db = getConnection();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
Remember to clean your input and use bound parameters in your query.
Read the results parameter in a variable, and use it in the LIMIT clause instead of the hard coded 10
function getUsers() {
try {
$db = getConnection();
$limit = $_GET["results"];
// validate $limit for valid value here and continue only if
// using something like
// $limit = $db->real_escape_string($limit);
// and continue only if successfully validated
$sql = "select * FROM user ORDER BY id LIMIT ".(strlen($limit) ? $limit : 10);
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}

PDO fetchAll not returning all rows

So I am trying to get multiple things from database. It is not working.
In my functions file I have:
public function getAllMultiple($username, $course) {
foreach ($course as $key) {
$query = $this->database->db->prepare("SELECT * FROM `status` WHERE `posted_by` = ? OR `shared` = ? ORDER BY `date_added` DESC");
$query->bindValue(1, $username);
$query->bindValue(2, $key['1']);
try {
$query->execute();
} catch (PDOException $e) {
die($e->getMessage());
}
return $query->fetchAll();
}
}
In my feed function I have:
$array = $course->getAllAsMember($username);
print_r($course->getAllMultiple($username, $array);
I have two courses. I have a drug course and a class course. Unfortunately, it is only returning the drug course. Is there anything I'm doing wrong?
To expand on my comment, you can do something like:
public function getAllMultiple($username, $course) {
$query = $this->database->db->prepare("SELECT * FROM `status` WHERE `posted_by` = ? OR `shared` = ? ORDER BY `date_added` DESC");
$results = array();
foreach ($course as $key) {
$query->bindValue(1, $username);
$query->bindValue(2, $key['1']);
try {
$query->execute();
} catch (PDOException $e) {
die($e->getMessage());
}
results[] = $query->fetchAll();
}
return $results;
}
You should also improve your error handling, for example by putting everything within a try - catch block instead of just a part of it.
The return bit of your function stops execution of the function and returns the value. If you want to return both results of the queries you execute, you need to assign them to an array, and then return that:
public function getAllMultiple($username, $course) {
$return = array(); //initialize the array before the foreach function
foreach ($course as $key) {
$query = $this->database->db->prepare("SELECT * FROM `status` WHERE `posted_by` = ? OR `shared` = ? ORDER BY `date_added` DESC");
$query->bindValue(1, $username);
$query->bindValue(2, $key['1']);
try {
$query->execute();
} catch (PDOException $e) {
die($e->getMessage());
}
$return[] = $query->fetchAll(); //collect the results
}
return $return; //return the array
}
Hopefully my comments are self-explanatory.

PHP PDO mysql_result() equivalent?

What would i use in PDO instead of old mysql_resul()?
function ib_uk_isvalid($db,$uk) {
try {
$sth = $db->prepare("SELECT count(*) FROM ib_userkeys WHERE value=:val");
$sth->bindParam(":val",$uk);
$sth->execute();
$numrows = $sth->fetchColumn();
if($numrows>=1) {
$sth2 = $db->prepare("SELECT * FROM ib_userkeys WHERE value=:val");
$sth2->bindParam(":val",$uk);
$sth2->execute();
$res = $sth2->fetchAll();
print($res[0]->type);
} else {
return 0;
}
} catch (PDOException $e) {
return $e->getMessage();
}
}
ib_uk_isvalid($db,1234)
Gives me error because it returns table instead of an object (which i need).
function ib_uk_isvalid($db, $uk) {
$query = $db->prepare('SELECT * FROM ib_userkeys WHERE value = :val LIMIT 1');
$query->bindValue(':val', $uk);
$query->execute();
$row = $query->fetch(PDO::FETCH_OBJ);
return $row ? $row->type : 0;
}
... is how I'd write that. It may fix the problem.

Categories