Pass parameter from URL to a php function in an api php - php

I have a working API written in PHP, my code works fine but I need to pass a parameters to the API. but it is not working as expected.
In my readOrders function, I am getting all the orders, but now I want to get all orders with ids above a particular number passed on from the url accessing the api.
function getOrders($last_oid){
$stmt = $this->con->prepare("SELECT oid, uid, order_num, create_date, status_date FROM orders WHERE oid > ?");
$stmt->execute($last_oid);
$stmt->bind_result($oid, $uid, $order_num, $create_date, $status_date);
$orders = array();
while($stmt->fetch()){
$order = array();
$order['oid'] = $oid;
$order['uid'] = $uid;
$order['order_num'] = $order_num;
$order['create_date'] = $create_date;
$order['status_date'] = $status_date;
array_push($orders, $order);
}
return $orders;
}
I was getting all the orders when I didn't have a parameter $last_oid. that parameter is to fetch orders with id WHERE id>? and pass the last_id in execute().
And in my API call, I am passing the last_id, it is currently hard coded, after I am done I will use $_GET to get the value and pass it to the function.
//the READ operation
//if the call is get orders
case 'getOrders':
$db = new DbOperation();
$response['error'] = false;
$response['message'] = 'Request orders successfully completed';
$response['orders'] = $db->getOrders(504);
break;
I am not sure what I am not doing right. I am getting an empty json but I could should be getting some few rows.

You have an error in the code. You are executing a "prepared statement" but with the wrong statements. Try it like this:
function getOrders($last_oid)
{
try {
$orders = array();
$stmt = $this->con->prepare("SELECT oid, uid, order_num, create_date, status_date FROM orders WHERE oid > ?");
// I assume $ last_oid is an integer.
$stmt->bind_param("i", $last_oid);
if ($stmt->execute()) {
$result = $stmt->get_result();
// use the while loop to load the result set
while ($row = $result->fetch_assoc()) {
array_push($orders, array(
'oid' => $row['oid'],
'uid' => $row['uid'],
'order_num' => $row['order_num'],
'create_date' => $row['create_date'],
'status_date' => $row['status_date']
));
}
return $orders;
}
} catch (Exception $ex) {
print $ex->getMessage();
}
}

Related

No Update done with PDO php

I have problem without any error in my code that update row ..
if(!isset($error)){
try {
$sql = "UPDATE `invoice` SET `client`='".$client."', `company`='".$company."' , `clientemail`='".$clientemail."' , `mobailclient`='".$mobailclient."' , `startdate`='".$startdate."' , `enddate`='".$enddate."' WHERE `id` ='".$id."'";
$count = $db->exec($sql);
//redirect to invoice page
header('Location: invoice.php');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
This is my code , i try to get variable $sql and go to mysql phpmyadmin and its work good ,, but in file not work and i dont get any error
==== Update ====
i try this and not work
try {
$sql = 'UPDATE invoice SET client = :client, company = :company, clientemail = :clientemail, mobailclient = :mobailclient, startdate = :startdate, enddate = :enddate WHERE id = :id';
$statement = $db->prepare($sql);
$statement->bindParam(":client", $client);
$statement->bindParam(":company", $company);
$statement->bindParam(":clientemail", $clientemail);
$statement->bindParam(":mobailclient", $mobailclient);
$statement->bindParam(":startdate", $startdate);
$statement->bindParam(":enddate", $enddate);
$statement->bindParam(":id", intval($_GET['id']) );
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "<script>alert('".$statement->rowCount()."')</script>";
}
else
{
echo "<script>alert('No record updated')</script>";
}
Your query is opened for SQL Injection. You should use parameterized query which provide a kind of protection against SQL injection but will not provide 100% of protection. Kindly visit this Post for more details.
Try the following code by replacing table and column names.
$client = "my name";
$company = "my-company";
$id= 2;//make sure your table has a record with that specific id
$sql = 'UPDATE invoice SET client = :client, company = :company WHERE id = :id'; // here i am updating only two columns
//You can add more column that you want to upate like ColumnName = :ParameterIdentifier
//Where ParameterIdentifier Is the name of parameter used in bindParam as in my example company
$statement = $db->prepare($sql);
$statement->bindParam("client", $client); //Binding parameter for client
$statement->bindParam("company", $company); //Binding parameter for company
$statement->bindParam("id", $id);
$statement->execute();
if($statement->rowCount() > 0) // will return 1 if any row is updated
{
echo "Record updated successfully";
}
else
{
echo "No record updated";
}

Unable to get results php mysqli select with bind

I am attempting to return a result set from mysql in php using mysqli. I have attempted several different ways, but they either end in errors, or empty arrays being returned. I know the query is good because I can run it in my db admin client replacing the question mark with the string needed and it returns as expected. Does anyone see something I have missed? Looks like it should be working to me, but obviously something has to be wrong. ¯_(ツ)_/¯
<?php
class db extends mysqli{
function __construct(){
parent::__construct(PUBP_HOST, PUBP_USER, PUBP_PASS, PUBP_DB);
}
/*
--------------------------------------------------------------------------*/
function read_agency_phones($agency_in){
$returnArray = array();
if($stmt = $this->prepare("SELECT firstname, lastname, agency, phonenumber FROM employees WHERE agency = ?")){
try{
$stmt->bind_param('s', $agency_in);
$stmt->execute();
$stmt->bind_result($first, $last, $agency, $phone);
while($stmt->fetch()){
$returnArray[] = array(
'first_name' => $first,
'last_name' => $last,
'agency' => $agency,
'phonenumber' => $phone
);
}
$stmt->free_result();
$stmt->close();
return $returnArray;
} catch (Exception $ex) {
return $ex->getMessage();
}
}
return 'failed001';
}
}
$db = new db();
$results = $db->read_agency_phones("SOME_STRING");
echo '<pre>';
echo var_export($results, true);
echo '</pre>';
die;
The agency field in the database is of type VARCHAR(10).
When running the following query in admin panel, results are returned as expected:
SELECT firstname, lastname, agency, phonenumber FROM employees WHERE agency = "THE-AGENCY"

PHP Delete function is deleting database row, but response is showing error?

I have created a PHP file called DB_Functions which contains my Delete method for removing a database row by User Id. Code:
//Delete User
public function deleteUser($id){
$stmt = $this->conn->prepare("DELETE FROM users WHERE user_id = ?");
$stmt->bind_param("s", $id);
$result = $stmt->execute();
$stmt->close();
}
I have then created another PHP file to act as an endpoint which calls this function after the Id is received as a POST parameter. Code:
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
//json response array
$response = array();
if(isset($_POST['id'])){
//recieve GET parameters
$id = $_POST['id'];
$result = $db->deleteUser($id);
if($result){
$response["error"] = FALSE;
$response["message"] = "User deleted succesfully";
}else{
$response["error"] = TRUE;
$response["error_msg"] = "User did not delete";
}
echo json_encode($response);
}
When testing this using Advanced Rest Client and when using with an Andriod development I am working on, the row is deleted from the database but the parsed response in ARC is the error message and in the Android Logcat the same response message of "User did not delete" is shown?
Any help?
In your deleteUser function you are missing return statement. If you do not return anything then function will always return null.
So, In your case it's returning NULL and in further condition check it's going to else case.
public function deleteUser($id){
$stmt = $this->conn->prepare("DELETE FROM users WHERE user_id = ?");
$stmt->bind_param("s", $id);
$result = $stmt->execute();
$stmt->close();
return $result; // add this
}
Your function does not return any value, so when being compiled automatically returns a NULL value, which is why the error is always shown.
You need to add a return statement.
Return the result in the function...
public function deleteUser($id){
$stmt = $this->conn->prepare("DELETE FROM users WHERE user_id = ?");
$stmt->bind_param("s", $id);
$result = $stmt->execute();
$stmt->close();
return $result;
}

PHP Slim REST API returns null after calling get function

I have developed a simple REST API using PHP Slim and implemented a simple function which will return a list of track upon matching the album name passed thought REST call.
This is my index.php file for making those rest calls,
http://localhost/my_gallery/v1/tracks/:name
$app->get('/tracks/:name', 'authenticate', function($album_keyword) {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch task
$result = $db->getTracksByName($album_keyword);
if ($result != NULL) {
$response["error"] = false;
$response["album_name"] = $result["album_name"];
$response["track_artist"] = $result["track_artist"];
$response["track_name"] = $result["track_name"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
This is the getTracksByName() function for returning a list a tracks after matching the album name,
public function getTracksByName($album_keyword) {
$stmt = $this->conn->prepare(
"SELECT `album`.album_name, `track`.track_artist, `track`.track_name "
. "FROM `category_album` ,`album` , `track` "
. "where `album`.album_id=`track`.album_id AND`album`.`album_name` LIKE ?");
$stmt->bind_param("i", $album_keyword);
if ($stmt->execute()) {
$res = array();
$stmt->bind_result($album_name, $track_artist, $track_name);
$stmt->fetch();
$res["album_name"] = $album_name;
$res["track_artist"] = $track_artist;
$res["track_name"] = $track_name;
$stmt->close();
return $res;
} else {
return NULL;
}
}
Now after making the REST call its returns null values for each track items. Just to mention I've change the SQL query from
... ANDalbum.album_name LIKE ?
to
... ANDalbum.album_id LIKE ?
and its works but for some reason itsn't working with the following query
... ANDalbum.album_name LIKE ?
I'm absolutely new to PHP and any kind of help would be greatly appreciated.
$stmt->bind_param("i", $album_keyword); binds a parameter of type INTEGER. Change to $stmt->bind_param("s", $album_keyword); to bind a parameter of type STRING.
http://php.net/manual/en/mysqli-stmt.bind-param.php
There is two potential issues in your prepared statement code.
First off, you are telling the statement that the parameter is a int:
$stmt->bind_param("i", $album_keyword);
The i indicates Integer. While you want a string (s).
Second issue is that when using LIKE in a prepared statement, you still need the % signs used in a standard LIKE.
For example:
$stmt->bind_param("s", "%$album_keyword%");

invalid parameter number exception using named parameter

I am getting "invalid parameter number:parameter undefined" exception when attempting an insert query to mysql database.
I am returning the result to my Android app as json.
if (!empty($_POST))
{
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
$query_params = array(
':dat' => $_POST['datee'],
':from'=>$_POST['fromm'],
':to'=>$_POST['too'],
':ccode'=>$_POST['course'],
':stud'=>$_POST['sname'],
':rmk'=>$_POST['remark'],
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
//or just use this use this one to product JSON data:
$response["success"] = 0;
$response["message"] = $ex->getMessage();
$response["date"] = $_POST['datee'];
$response["from"] = $_POST['fromm'];
$response["to"] = $_POST['too'];
$response["ccode"] = $_POST['course'];
$response["stud"] = $_POST['sname'];
$response["remark"] = $_POST['remark'];
die(json_encode($response));
}
}
you lack a m in
':from'=>$_POST['fromm'],
should be
':fromm'=>$_POST['fromm'],
you must be careful when using named parameter, I myself am very prone to making such errors
that's why I more easily use the ? placeholder, this way in your exemple:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (?,?,?,?,?,?) ";
$query_params = array(
$_POST['datee'],
$_POST['fromm'],
$_POST['too'],
$_POST['course'],
$_POST['sname'],
$_POST['remark'],
);
then:
$result = $stmt->execute($query_params);
you must be sure that the params are in good order (same as in query)
In your query, you're misspelling from:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:fromm,:too,:ccode,:stud,:rmk ) ";
Replace it with:
$query = "INSERT INTO attendance (tdate,slot_from,slot_to,coursecode,stud_id,remark) VALUES (:dat,:from,:too,:ccode,:stud,:rmk ) ";

Categories