SQL request dont work as expected - php

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

Related

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

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

PHP $_SESSION variable undefined using Slim

I'm trying to set a session variable in php using Slim. I want the users id to be stored as a variable to use elsewhere. I think I have the syntax or order wrong in my functions.
Here is my function to set the variable:
function loadAdmin()
{
//Set new session and save user id to variable
if (!isset($_SESSION)) {
session_start();
}
$app = \Slim\Slim::getInstance();
$token = $app->request->headers->get('token');
$token_exists = getToken_Validate();
if($token_exists) {
$sql = "SELECT id, title AS admin_title, last_name AS admin_last_name
FROM admin WHERE token=:token";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':token', $token);
$stmt->execute();
$admin = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($admin);
$_SESSION['uid'] = $stmt['id'];
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
} else {
echo '{"err": "failed"}';
}
}
Here is my function to use the variable when fetching specific data:
function loadDashboard()
{
session_start();
$uid = $_SESSION['uid'];
$token_exists = getToken_Validate();
if ($token_exists) {
//Get number of rows from multiple tables
$sql = "SELECT
(SELECT COUNT(*) FROM users WHERE id=:uid) AS total_students,
(SELECT COUNT(*) FROM subjects) AS total_subjects,
(SELECT COUNT(*) FROM notes) AS total_notes";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':uid', $uid);
$stmt->execute();
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($users);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
} else {
echo '{"err": "failed"}';
}
}
The Slim error I get after trying to loadDashboard is:
Undefined index: uid
Sorry if my PHP is awful, any help is appreciated.
Turns out it had nothing to do with Slim.
$_SESSION['uid'] = $stmt['id']; was not storing anything to the variable.
I had to first bind the id column to a variable:
$stmt->bindColumn('id', $uid);
Then I could set that variable as a session variable:
$_SESSION['uid'] = $uid;
Here is the full working function:
function loadAdmin()
{
if (!isset($_SESSION)) {
session_start();
}
$app = \Slim\Slim::getInstance();
$token = $app->request->headers->get('token');
$token_exists = getToken_Validate();
if($token_exists) {
$sql = "SELECT
id,
title AS admin_title,
last_name AS admin_last_name
FROM admin WHERE token=:token";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindValue(':token', $token);
$stmt->execute();
$stmt->bindColumn('id', $uid);
$admin = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
$_SESSION['uid'] = $uid;
echo json_encode($admin);
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
else {
echo '{"err": "failed"}';
}
}

Call to a member function bind_Param() in get method

I wonder whats the problem in my code? I tried all the sources I can search but it still gives me the same error which is still "Call to a member function bind_Param() on a non-object".here's my code.,hope someone can help me, thanks
$app->get('/students/:student_id',function () use($app){
$sql = "SELECT * FROM students WHERE student_id =:student_id";
try {
$db = connect_db();
$stmt = $db->prepare($sql);
$stmt->bind_Param("student_id", $student_id);
$stmt->execute();
$students = $stmt->fetchObject();
$db = null;
echo json_encode($students);
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
This one works:
$app->get('/students/:student_id', function ($student_id) use($app){
$sql = "SELECT * FROM students WHERE student_id = ?";
try {
$db = connect_db();
$stmt = $db->prepare($sql);
$stmt->bind_Param("i", $student_id);
$stmt->execute();
$result = $stmt->get_result();
$students = $result->fetch_object();
$db = null;
echo json_encode($students);
}
catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
});
I assume that you're using this definition of the connect_db function:
function connect_db() {
$dbhost="localhost";
$dbuser="user";
$dbpass="pass";
$dbname="stackoverflow-33750846";
return new mysqli($dbhost, $dbuser, $dbpass, $dbname);;
}
Perhaps there is a bit of confusion using the database connection and read data from it, so I add some points:
Be sure to pass $student_id as a parameter to the callable function;
$stmt->bind_Param accepts a string that represents the type of the parameters and all the binding parameters;
fetchObject is a function of the mysqli_result class.

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

PHP Class Parameters used twice

I am new to OOP, and I am switching all of my websites code to it! I am currently writing a class that grabs a user's information, and will eventually update it.
The code I am using is below:
<?php
require("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public function __construct($userid, $connection, $information) {
$this->userid = $userid;
$this->connection = $connection;
$this->information = $information;
}
public function user_information($userid, $connection, $information) {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $userid);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns["$information"];
}
}
$username = new user($_SESSION["logged_in"], $connection, "username");
echo $username->user_information($_SESSION["logged_in"], $connection, "username");
?>
Now as you can see on the last two lines of code (one from the end) I have to use the parameters twice. Basically the first parameter says what the ID is, second says what the $connection is, and the third is what I want to grab from the database. So what am I doing wrong? Did I define something I did not need to?
EDIT
Would the following be valid as well?
<?php
require("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public function user_information($userid, $connection, $information) {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $userid);
try{
$stmt = $connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns["$information"];
}
}
$username = new user();
echo $username->user_information($_SESSION["logged_in"], $connection, "username");
?>
Like is this in-properer, or wrong...?
If the user class has all the information it needs as data members, then user_information doesn't need to take any arguments:
public function user_information() {
$query = "SELECT * FROM users WHERE id = :id";
$params = array(':id' => $this->userid);
try{
$stmt = $this->connection->prepare($query);
$result = $stmt->execute($params);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$columns = $stmt->fetch();
return $columns[$this->information];
}
Since you have a lot of questions about the way a class works and about OOP I will try to give you a little direction.
There is no standard way of building your class. You are the one that decides what goes where in terms of what belongs to the class and what needs to be injected. This is just to tell you that you cannot pin yourself down. You need to get a feel for it and build a logic.
I took your class and rebuild it some with added comments. Hope that will help you some. Good luck!
<?php
require ("C:\wamp\www\postin'\db_connection.php");
session_start();
class user {
public $dbconnection;
public function __construct($connection) {
/**
* Your user class interacts with the database.
* Inject the connection here and set your
* global class variable.
*/
$this -> dbconnection = $connection;
}
public function user_information($userid, $column) {
/**
* The userid and column are specific for this
* method action. No need to set these variables
* in the global scope of the class.
*/
$query = "SELECT" . $column . " FROM users WHERE id = :id";
$params = array(':id' => $userid);
try {
$stmt = $this -> dbconnection -> prepare($query);
$stmt -> execute($params);
} catch(PDOException $ex) {
echo("Failed to run query: " . $ex -> getMessage());
}
$result = $stmt -> fetch();
return $result;
}
}
$username = new user($connection);
echo $username -> user_information($_SESSION["logged_in"], $information);
?>

Categories