trying to test API using postman - php

i am trying to test an api using postman , each time i try to signup i keep getting "unexpected e".
Don't really know what is going on
here is my code:
$app->post('/signup', function() {
$app = \Slim\Slim::getInstance();
$name = $app->request()->post('name');
$email = $app->request()->post('email');
$pass = $app->request()->post('pass');
$app->response->setStatus(200);
$app->response()->headers->set('Content-Type', 'application/json');
try
{
$db = getDB();
$sth = $db->prepare("select count(*) as count from user WHERE email=:email");
$sth->bindParam(':email', $email, PDO::PARAM_INT);
$sth->execute();
$row = $sth->fetch();
if($row['count']>0){
$output = array(
'status'=>"0",
'operation'=>"student already registered"
);
echo json_encode($output);
$db = null;
return;
}
else{
// where i try to insert values into my database.
$sth = $db->prepare("INSERT INTO user (name, email,password)
VALUES(:name,:email,:pass)");
$sth->bindParam(':name', $name, PDO::PARAM_INT);
$sth->bindParam(':email', $email, PDO::PARAM_INT);
$sth->bindParam(':pass', $pass, PDO::PARAM_INT);
$sth->execute();
$output = array(
'status'=>"1",
'operation'=>"success"
);
echo json_encode($output);
$db = null;
return;
}
}
catch(Exception $ex){
echo $ex;
}
});

"unexpected e" happens because Postman was expecting the output to be a JSON response.
When you get the response, click the 'Raw' or 'Preview' tab. Or choose one of the other formats from the drop-down menu. You'll see the rest of the response.

Related

Android Error: Value <br of type java.lang.String cannot be converted to JSONObject

Currently, I create an apps with a login function. To connect from android to MySQL database, I use PHP. When I use MySQLi, everything is okay. But when I convert to PDO, The error will appear the same as my question's title. Can anyone knows what is the problem? Below is my PHP code:
<?php
require_once 'configPDO.php';
$response = array();
if(isTheseParametersAvailable(array('badgeid', 'pwd'))){
$badgeid = $_POST['badgeid'];
$pwd = $_POST['pwd'];
$stmt = $conn->prepare("SELECT badgeid, email, fullname, roles_id, team_id FROM users WHERE badgeid = :badgeid AND pwd = :pwd AND roles_id = 3");
// $stmt->bind_param("ss",$badgeid, $pwd);
$stmt->bindParam(':badgeid',$badgeid,PDO::PARAM_STR);
$stmt->bindParam(':pwd',$pwd,PDO::PARAM_STR);
$stmt->execute();
//$stmt->store_result();
if($stmt->rowCount() > 0){
$stmt->bindParam($badgeid, $email, $fullname, $roles_id, $team_id);
$stmt->fetch();
$user = array(
'badgeid'=>$badgeid,
'email'=>$email,
'fullname'=>$fullname,
'roles_id'=>$roles_id,
'team_id'=>$team_id
);
$response['error'] = false;
$response['message'] = 'Login successfull';
$response['user'] = $user;
}else{
$response['error'] = false;
$response['message'] = 'Invalid username or password';
}
}
echo json_encode($response);
function isTheseParametersAvailable($params){
foreach($params as $param){
if(!isset($_POST[$param])){
return false;
}
}
return true;
}
Your second bindParam() (You should read and understand what exactly this method do!) inside the if condition is nonsense!
Change this:
if($stmt->rowCount() > 0){
$stmt->bindParam($badgeid, $email, $fullname, $roles_id, $team_id);
$stmt->fetch();
$user = array(
'badgeid'=>$badgeid,
'email'=>$email,
'fullname'=>$fullname,
'roles_id'=>$roles_id,
'team_id'=>$team_id
);
to this:
$result = $stmt->fetch(\PDO::FETCH_ASSOC); // Get results as array
if ($result) {
// Since we only get the fields we want to send back, you can assign `$result` directly to `$response['user']`
$response['user'] = $result;
PHP had thrown an related error, which you would have seen in the raw response of you request!

PHP call SQL Server SP returning data, output parameters and return value

I'm a beginner in PHP programming.
I have an SP in SQL Server with input, output and ReturnValue parameters that returns data from an sample table.
CREATE PROCEDURE [dbo].[sp_PHP]
#in1 int, #in2 int, #out3 int OUTPUT
WITH EXEC AS CALLER
AS
SET #out3 = #in1 * #in2
SELECT * FROM PHP
RETURN #in1 + #in2
This is my PHP code
<?php
try
{
$conn = new PDO("sqlsrv:Server=xxxxx,1433;Database=xxxxxx", "xx", "xx");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (Exception $e)
{
die(print_r($e->getMessage()));
}
$query = '{? = CALL sp_PHP(?, ?, ?)}';
$stmt = $conn->prepare($query);
$returnVariable = -1;
$inputVariable1 = 18;
$inputVariable2 = 24;
$outputVariable3 = -1;
$stmt->bindParam(1,$returnVariable, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, 100);
$stmt->bindParam(2,$inputVariable1, PDO::PARAM_INT);
$stmt->bindParam(3,$inputVariable2, PDO::PARAM_INT);
$stmt->bindParam(4,$outputVariable3, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, 100);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row) {
echo $row['PHP_ID'].' '.$row['PHP_Char'].'<br>';
}
echo '<hr>';
echo 'Return value: '.$returnVariable.'<br>';
echo 'Output parameter: '.$outputVariable3.'<br>';
?>
If I remove the line in the SP
SELECT * FROM PHP
and don't read the data received in PHP with following code
$results = $stmt->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row) {
echo $row['PHP_ID'].' '.$row['PHP_Char'].'<br>';
}
I receive the correct values of $returnVariable (42) and $outputVariable3 (432).
But if I read (and show) the data read from the SP, $returnVariable and $outputVariable3 are equal to -1 (the assigned value)
I wanto to read output parameter, ReturnValue and data at the same time.
Is it possible? Where am I wrong?
Thanks!!
Solution:
The value of the output (or input/output) parameter is accessible when you consume all results returned by the stored procedure (PDO and not PDO versions). In your case you need to move throw resultsets with PDOStatement::nextRowset to get the values for the output parameters.
Example:
I've reproduced your example and next code works for me.
<?php
$server = 'server\instance,port';
$database = 'database';
$uid = 'user';
$pwd = 'password';
try {
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
try {
$sql = "{? = CALL sp_PHP(?, ?, ?)}";
#$sql = "EXEC ? = sp_PHP(?, ?, ?)";
$stmt = $conn->prepare($sql);
$returnVariable = -1;
$inputVariable1 = 18;
$inputVariable2 = 24;
$outputVariable3 = -1;
$stmt->bindParam(1, $returnVariable, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->bindParam(2, $inputVariable1, PDO::PARAM_INT);
$stmt->bindParam(3, $inputVariable2, PDO::PARAM_INT);
$stmt->bindParam(4, $outputVariable3, PDO::PARAM_INT | PDO::PARAM_INPUT_OUTPUT, PDO::SQLSRV_PARAM_OUT_DEFAULT_SIZE);
$stmt->execute();
do {
echo 'Result set:'."<br>";
while ($row = $stmt->fetch( PDO::FETCH_ASSOC) ){
print_r($row)."<br>";
}
echo "<br>";
echo "<br>";
} while ($stmt->nextRowset());
} catch( PDOException $e ) {
die( "Error executing query" );
}
$stmt = null;
$conn = null;
echo 'Stored procedure return value: '.$returnVariable."</br>";
echo 'Stored procedure output parameter: '.$outputVariable3."</br>";
?>

changePSW function does not work

can you help out a beginner trying to learn PHP? I wrote a code for changing password without any validations yet, just to change it and it does not work. It's been days I've been trying and couldn't figure out what's wrong. Thanks in advance.
id is variable name in database where id is kept.
db connection is done with first line and it definitely works.
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
session_start();
print_r($_SESSION);
function changePSW()
{
//$password = $_POST['currPassword']; // required
$newPassword = $_POST['newPassword']; // required
//$newPassword2 = $_POST['NewPassword2']; // required
$newPasswordH = password_hash($newPassword, PASSWORD_DEFAULT);
echo($newPassword);
$id = $_SESSION['userID'];
echo($id);
// create PDO connection object
$dbConn = new DatabaseConnection();
$pdo = $dbConn->getConnection();
try {
$statement = $pdo->prepare("SELECT * FROM `users` WHERE id = :id LIMIT 1");
$statement->bindParam(':id', $id);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
echo "SADASDASD";
// no user matching the email
if (empty($result)) {
$_SESSION['error_message'] = 'Couldnt find user';
header('Location: /Online-store/userForm.php');
return;
}
$sql = "UPDATE users SET password=:newPasswordH WHERE id = :id";
// Prepare statement
$stmt = $pdo->prepare($sql);
echo "AFGHANIKO";
// execute the query
$update_status = $stmt->execute(array(':password' => $newPasswordH, ':id' => $id));
echo "IHAAA";
echo($update_status);
if ($update_status === TRUE) {
echo("Record updated successfully" . "\r\n");
echo nl2br("\nPassword: ");
echo ($newPassword);
echo nl2br("\nHashed Password: ");
echo ($newPasswordH);
return true;
} else {
echo "Error updating record";
die();
}
} catch (PDOException $e) {
// usually this error is logged in application log and we should return an error message that's meaninful to user
return $e->getMessage();
}
}
if($_SESSION['isLoggedIn'] == true) {
require_once("database/DatabaseConnection.php");
unset($_SESSION['success_message']);
unset($_SESSION['error_message']);
changePSW();
}
?>
$update_status = $stmt->execute(array(':newPasswordH' => $newPasswordH, ':id' => $id));
This is what I needed to have instead of
$update_status = $stmt->execute(array(':password' => $newPasswordH, ':id' => $id));

Receiving Error Message in ionic App from PHP file on Post Request

It is required to add the product to the MySql Database (remote)
by the ionicApp. There is a Product Page. When submit is pressed, the post method is called from the ionicApp "Product.ts" page by function createEntry().
The record has been created successfully if there is no constraint error with the help of a PHP file named manage_products.php.
In the ionic app if(data.status === 200) is true then the body get executed. But there is no way if the record has been created or not. if there is some problem, for example, some null constraint (Db side) then it is only via the Chrome network tab that I come to know about some constraint error. Is there any way to receive error text from the PHP file in the ionic App.
Here is the function to createEntry called from ionicApp "Product.ts"
createEntry()
{
let id = "0000";
let name = "Some Product";
let description = "Some Product description";
let manufacturer_name = "manufacturer_name";
let weight = "some weight is here";
let weight_unit = "kg";
let halal_status = "HALAL";
let body : string = "key=create&id=" + id + "&name=" + name + "&description=" + description + "&manufacturer_name=" + manufacturer_name + "&weight=" + weight + "&weight_unit=" + weight_unit + "&halal_status=" + halal_status ,
type : string = "application/x-www-form-urlencoded; charset=UTF-8",
headers : any = new Headers({ 'Content-Type': type}),
options : any = new RequestOptions({ headers: headers }),
url : any = this.baseURI + "manage_products.php";
this.http.post(url, body, options)
.subscribe((data) =>
{
// If the request was successful notify the user
if(data.status === 200)
{
// this.hideForm = true;
console.log(`Congratulations the technology: ${name} was successfully added`);
console.log('successfully added the record. .......');
}
// Otherwise let 'em know anyway
else
{
// this.sendNotification('Something went wrong!');
console.log('Couldnt add the record.....xxx');
}
});
}
The above code is calling the PHP file. Here is the code for the PHP file.
<?php
header('Access-Control-Allow-Origin: *');
// Define database connection parameters
$hn = 'localhost';
$un = 'username';
$pwd = 'password';
$db = 'name-of-database';
$cs = 'utf8';
// Set up the PDO parameters
$dsn = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
PDO::ATTR_EMULATE_PREPARES => false,
);
// Create a PDO instance (connect to the database)
$pdo = new PDO($dsn, $un, $pwd, $opt);
// Retrieve specific parameter from supplied URL
$key = strip_tags($_REQUEST['key']);
$data = array();
// Determine which mode is being requested
switch($key)
{
// Add a new record to the technologies table
case "create":
// Sanitise URL supplied values
$id = filter_var($_REQUEST['id'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$name = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$manufacturer_name = filter_var($_REQUEST['manufacturer_name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight = filter_var($_REQUEST['weight'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight_unit = filter_var($_REQUEST['weight_unit'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$halal_status = filter_var($_REQUEST['halal_status'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$description = filter_var($_REQUEST['description'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
// Attempt to run PDO prepared statement
try {
$sql = "INSERT INTO Products(id,name,manufacturer_name,weight,weight_unit,halal_status,description) VALUES(:id, :name, :manufacturer_name, :weight, :weight_unit, :halal_status, :description)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $id, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':manufacturer_name', $manufacturer_name, PDO::PARAM_STR);
$stmt->bindParam(':weight', $weight, PDO::PARAM_STR);
$stmt->bindParam(':weight_unit', $weight_unit, PDO::PARAM_STR);
$stmt->bindParam(':halal_status', $halal_status, PDO::PARAM_STR);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->execute();
echo json_encode(array('message' => 'Congratulations the record ' . $name . ' was added to the database'));
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;
// Update an existing record in the technologies table
case "update":
// Sanitise URL supplied values
/*
$name = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$description = filter_var($_REQUEST['description'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$recordID = filter_var($_REQUEST['recordID'], FILTER_SANITIZE_NUMBER_INT);
*/
$id = filter_var($_REQUEST['id'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$name = filter_var($_REQUEST['name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$manufacturer_name = filter_var($_REQUEST['manufacturer_name'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight = filter_var($_REQUEST['weight'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$weight_unit = filter_var($_REQUEST['weight_unit'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
$halal_status = filter_var($_REQUEST['halal_status'], FILTER_SANITIZE_STRING, FILTER_FLAG_ENCODE_LOW);
// Attempt to run PDO prepared statement
try {
$sql = "UPDATE Products SET id = :id, name = :name,manufacturer_name = :manufacturer_name,weight = :weight,weight_unit = :weight_unit,halal_status = : halal_status, description = :description WHERE id = :id";
$stmt = $pdo->prepare($sql);
/*
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':description', $description, PDO::PARAM_STR);
$stmt->bindParam(':id', $recordID, PDO::PARAM_INT);
*/
$stmt->bindParam(':id', $name, PDO::PARAM_STR);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':manufacturer_name', $description, PDO::PARAM_STR);
$stmt->bindParam(':weight', $name, PDO::PARAM_STR);
$stmt->bindParam(':weight_unit', $name, PDO::PARAM_STR);
$stmt->bindParam(':halal_status', $description, PDO::PARAM_STR);
$stmt->bindParam(':description', $name, PDO::PARAM_STR);
$stmt->execute();
echo json_encode('Congratulations the record ' . $name . ' was updated');
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;
// Remove an existing record in the technologies table
case "delete":
// Sanitise supplied record ID for matching to table record
$recordID = filter_var($_REQUEST['id'], FILTER_SANITIZE_NUMBER_INT);
// Attempt to run PDO prepared statement
try {
$pdo = new PDO($dsn, $un, $pwd);
$sql = "DELETE FROM Products WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $recordID, PDO::PARAM_INT);
$stmt->execute();
echo json_encode('Congratulations the record ' . $name . ' was removed');
}
// Catch any errors in running the prepared statement
catch(PDOException $e)
{
echo $e->getMessage();
}
break;
}
?>
you can use the alertcontroller or toastcontroller and display the error message by adding a catch after you have subscribed to the data...like this
catch((err)=>{
this.AlertMessage("error", err);
});

Table value are not changing

There is my code of EDIT.php DB_Functions,and g.php..I'm not geting where is the fault is anyone here who can help me to find out mistake on my code
Every things happen as easy but change in table is not reflecting..my SQL query is working properly on XAMP server..
It may be silly mistake but not able to find it..
edit.php
<?php
//error_reporting(0);
include("class_db.php");
include_once('DB_Functions.php');
if (isset ($_GET['edit_id']))
{
$id=$_GET['edit_id'];
{
if(isset($_POST['nam']))
{
$id =($_POST['edit_id']);
$name=($_POST['name']);
$lastname=($_POST['lastname']);
$email=($_POST['email']);
$duser=($_POST['duser']);
$pass=($_POST['pass']);
$mob=($_POST['mob']);
$website=($_POST['website']);
$result = file_get_contents('http://localhost/rajju/demo/webservises/webservises/webservices/g.php?action=update_details&id='.$id.'&name='.$name.'&lastname='.$lastname.'&email='.$email.'&duser='.$duser.'&pass='.$pass.'&mob='.$mob.'&website='.$website);
$result = json_decode($result, true);
if($result == 'success'){
header("location:http://localhost/rajju/demo/webservises/webservises/webservices/list.php");
}
else{
print_r($result);
}
}
}
}
$select =mysql_query("select * from users where id=$id");
$var = mysql_fetch_object($select);
?>
DB_Functions.php
public function updateUser($id,$name,$lastname,$email,$duser,$pass,$mob,$website)
{
$app_list =mysql_query("UPDATE users SET name='".$name."',lastname='".$lastname."',email='".$email."',duser='".$duser."',pass='".$pass."',mob='".$mob."',website='".$website."' WHERE id='".$id."'");
if ($app_list) {
return true;
} else {
return false;
}
}
g.php
else if($tag == 'update_details')
{
$db = new DB_Functions();
//$id = ($_GET['id']);
$name=($_GET['name']);
$lastname=($_GET['lastname']);
$email=($_GET['email']);
$duser=($_GET['duser']);
$pass=($_GET['pass']);
$mob=($_GET['mob']);
$website=($_GET['website']);
//exit (json_encode($name));
if ($db ->updateUser($name,$lastname,$email,$duser,$pass,$mob,$website))
{
exit (json_encode('success'));
}else
{
exit (json_encode('errorzz'));
}
}
The following should work. Note this still wont totally protect you against xss and other attacks. However its a lot better than using mysql_query!! Additionally, you should sanatise and check your incoming $_GET params and Salt+Hash your passwords.
<?php
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$sql = "UPDATE users SET name=:name, lastname=:lastname, email=:email, duser=:duser, pass=:pass, mob=:mob, website=:website, WHERE id=:id";;
$st = $conn->prepare( $sql );
$st->bindValue(":name", $name, PDO::PARAM_STR);
$st->bindValue(":lastname", $lastname, PDO::PARAM_STR);
$st->bindValue(":email", $email, PDO::PARAM_STR);
$st->bindValue(":duser", $duser, PDO::PARAM_STR);
$st->bindValue(":pass", $pass, PDO::PARAM_STR);
$st->bindValue(":mob", $mob, PDO::PARAM_STR);
$st->bindValue(":website", $website, PDO::PARAM_STR);
$st->bindValue(":id", $id, PDO::PARAM_INT);
$st->execute();
?>

Categories