php select query with where parameter error - php

I have written a php script to retrieve data from mysql for a particular username. The username is passed in select query and i am checking the php script using postman. Following is my php code
<?php
//getting the database connection
require_once 'MyDbConnect.php';
//an array to display response
$response = array();
//if it is an api call
//that means a get parameter named api call is set in the URL
//and with this parameter we are concluding that it is an api call
if(isset($_GET['apicall'])){
switch($_GET['apicall']){
case 'getSpecificData':
case 'getSpecificData':
if(isTheseParametersAvailable(array('your_username'))){
//getting values
$your_username = $_POST['your_username'];
$heroes = array();
$sql = "SELECT your_username,your_mobile,referral_name,referral_contact,referral_email,
loan_type,loan_amount FROM mytable WHERE your_username = ? ";
$sql->bind_param("s",$your_username);
$stmt->execute();
$stmt->bind_result($your_username, $your_mobile,$referral_name,$referral_contact,
$referral_email,$loan_type,$loan_amount);
//looping through all the records
while($stmt->fetch()){
$temp = [
'your_username'=>$your_username,
'your_mobile'=>$your_mobile,
'referral_name'=>$referral_name,
'referral_contact'=>$referral_contact,
'referral_email'=>$referral_email,
'loan_type'=>$loan_type,
'loan_amount'=>$loan_amount
];
//pushing the array inside the hero array
array_push($heroes, $temp);
}
echo json_encode($heroes);
}
break;
default:
$response['error'] = true;
$response['message'] = 'Invalid Operation Called';
}
}
else{
//if it is not api call
//pushing appropriate values to response array
$response['error'] = true;
$response['message'] = 'Invalid API Call';
}
function isTheseParametersAvailable($params){
//traversing through all the parameters
foreach($params as $param){
//if the paramter is not available
if(!isset($_POST[$param])){
//return false
return false;
}
}
//return true if every param is available
return true;
}
?>
The problem is in the select query. When i write the select query as i mentioned above in my php code i get nothing. but if i write the select query as follows i get proper data
$sql = "SELECT your_username,your_mobile,referral_name,referral_contact,referral_email,
loan_type,loan_amount FROM mytable WHERE your_username = 'Rohan' ";
Can somebody please explain me the cause of error? Any help would be greatly appreciated.

You're missing the binding of the variable:
// $stmt->bind_param("ss",$your_username);
Is already in your code. Change it to:
$stmt->bind_param("s",$your_username);
The "s" indicates the variable is a string, the binding "replaces" the "?" in the query.
EDIT:
Than use this snippet instead ;)
$your_username = $_POST['your_username'];
//creating the query
$stmt = $conn->prepare("SELECT id,your_username,your_mobile,referral_name,referral_contact,referral_email,
loan_type,loan_amount FROM mytable WHERE your_username = ? ");
$stmt->bind_param("s",$your_username);

Related

code works without error on localhost, but giving SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data on 000webhost

i am working on an python GUI application, and this part is back end of it. i am really unknown to JSON. and familiar with little bit of PHP. if possible, please give me the exact line of code where should i change it.
code giving SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data
my local php version is v 8.1.12 is this a problem?
?
<?php
header('Content-type: application/json');
// Include database connector
include 'database_connector.php';
// test connection
if (isset($_POST['test_connection'])) {
$data['connection_response'] = "OK";
}
// check app key and id
if (isset($_POST['checkapp'])) {
$data['valid_app'] = False;
if (!isset($_POST['app_key']) or empty($_POST['app_key'])) {
$data['response_message'] = "Invalid app key";
}elseif (!isset($_POST['app_id']) or empty($_POST['app_id'])) {
$data['response_message'] = "Invalid app id";
}else{
if (checkAppKey($_POST['app_id'], $_POST['app_key'])) {
if (checkAppKeyExpiration($_POST['app_key'])) {
$data['response_message'] = "App key expired! Please login";
}else{
$data['response_message'] = "Valid app key and id";
$data['valid_app'] = True;
$userDetails = getAppUser($_POST['app_id']);
if(!empty($userDetails) && isset($userDetails['user_name'])){
$data['username'] = $userDetails['user_name'];
}else{
$data['username'] = "";
}
$appDetails = getAppDetails($_POST['app_id']);
if(!empty($appDetails) && isset($appDetails['key_expiration_date'])){
$data['expiry_date'] = $appDetails['key_expiration_date'];
}else{
$data['expiry_date'] = "unknown";
}
}
}else{
$data['response_message'] = "Invalid app id or key";
}
}
$data['app_id'] = $_POST['app_id'];
$data['app_key'] = $_POST['app_key'];
}
// view if app key already exists
function view_app_key($link)
{
global $dbh;
$sql = "SELECT * FROM `applications` WHERE `application_key`='".$link."'";
$query = $dbh->prepare($sql);
$query->execute();
$result = $query;
if ($row = $result->fetch( PDO::FETCH_ASSOC )){
return "true";
}else{
return "false";
}
}
echo json_encode($data);
?>
the full code is here: https://drive.google.com/file/d/1Q5qLAZW5qachxWuc4ibtDMCH5KochjuS/view
In your ajax call try this Simply change,
var respons = jQuery.parseJSON(response);
to
var respons = response;
Explanation:
If the configuration of your AJAX call is having dataType: json you'll get a JavaScript object so it's no longer necessary to use JSON.parse().

Trying to retreive int type from function and compare it with $_Get value (mysql PHP)

I trying to retreive int type from database and compare it with $_Get value
Here is the code for when the user click on the button
if(isset($_GET['btn_placeorder']))
{
$Quantity_Ordered=(int)$_GET['Quantity_Ordered'];
**# retreivng another value from function to compare it as integer**
$number= (int)$auth_user->Blood_Bankavaliable ($Blood_BankID,$Type_Ordered);
try
{
if ($Type_Ordered=="" || $Quantity_Ordered=="")
{
$error[] = "Valid data is required!";
}
else if($Quantity_Ordered >$number) {
$error[] = "This Number is not avaliable in our Stock !";
}
Here is the code for the function
function Blood_Bankavaliable($blood_bankID,$Type_Ordered) {
global $conn;
# query for getting the value from the database
$query = "select sum(Blood_quantity) as d from Donor_Blood_Bank where Blood_Type=$Type_Ordered and blood_bankID= $blood_bankID";
try {
$statement = $this->conn->prepare($query);
$statement->execute();
$result = $statement->fetchall;
return $result;
} catch(PDOException $e)
{
echo $e->getMessage();
}
}
I don't know what is the problem with my code any help?
First, it should be $result = $statement->fetchAll();(a function or method), not $result = $statement->fetchall (a property).
Second, please read the manul, fetchall() return an array. therefore you can't cast it to int directly. run print_r( $auth_user->Blood_Bankavaliable($Blood_BankID,$Type_Ordered) ); to see yourself.

Unable to update values to database in PHP and MySQL

I am trying to update the value to database, but one way or an another i am not able to.
Code:
<?php
include 'init.php';
$dataid = $_POST['data_id'];
if(isset($dataid))
{
/*user connects to database and performs some operation here*/
/* values from database is returned and user passes the same to below function */
calculateamount($kk_data_id,$kk_egg,$kk_cash,$kk_in,$kk_out,$kk_expenditure,$kk_cashout,$kk_wholesale1,$kk_wholesale2,$kk_wholesale3,$kk_touch,$kk_galtha,$kk_kotla,$wholesale_1,$wholesale_2,$wholesale_3,$touch,$galtha,$kotla,$retail,$prevegg,$prevcash);
}
function calculateamount($kk_data_id,$kk_egg,$kk_cash,$kk_in,$kk_out,$kk_expenditure,$kk_cashout,$kk_wholesale1,$kk_wholesale2,$kk_wholesale3,$kk_touch,$kk_galtha,$kk_kotla,$rwholesale_1,$rwholesale_2,$rwholesale_3,$rtouch,$rgaltha,$rkotla,$rretail,,$prevegg,$prevcash)
{
/*performs Mathematical operations
with data retrieved and passes the final values to the below function to update to database*/
//ALL THE VALUES ARE CONVERTED TO STRING BEFORE PASSING ON TO THE BELOW FUNCTION
updatevaluestodatabase($finalwhl1amount,$finalwhl2amount,$finalwhl3amount,$finaltchamount,$finalgalamount,$finalkotamount,$finalretailval,$finalretamount,$finaltotamount,
$finaltottally);
}
function updatevaluestodatabase($finalwhl1amount,$finalwhl2amount,$finalwhl3amount,$finaltchamount,$finalgalamount,$finalkotamount,$finalretailval,$finalretamount,$finaltotamount,
$finaltottally)
{
$updatedata = "UPDATE kk_data SET wholesale1_amt=?,wholesale2_amt=?,wholesale3_amt=?,touch_amt=?,galtha_amt=?,kotla_amt=?,
kk_retail=?,retail_amt=?,kk_total_amount=?,kk_final_tally=? where kk_data_id = ?";
$updatestmt = mysqli_prepare($con, $updatedata);
mysqli_stmt_bind_param($updatestmt, sssssssssss,$finalwhl1amount,$finalwhl2amount,$finalwhl3amount,$finaltchamount,$finalgalamount,$finalkotamount,$finalretailval,$finalretamount,
$finaltotamount,$finaltottally,$dataid);
mysqli_stmt_execute($updatestmt);
mysqli_stmt_store_result($updatestmt);
$response = array();
$response["success"] = false;
if(mysqli_stmt_affected_rows($updatestmt) > 0 )
{
$response["success"] = true;
}
header('Content-Type: application/json');
echo json_encode($response);
}
?>
OUTPUT
Every time I run the below script in postman ('data_id' = value) or through application:
$response["success"] = false;
is returned always . Data is not updated to the database.
What I tried
Instead of using mysqli_stmt_affected_rows($updatestmt) I tried executing using mysqli_stmt_execute($updatestmt); in the if statement. But no luck there
I am unable to figure out where the issue is or if am incorrect in calling the function.
NOTE: I thought I would post a minimized code to avoid clumsiness.

Search user using part of the name

I have this PHP code:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username='%s'",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
But this only returns the user that matches the name exactly.
I'd like to return all users containing that name string, for example:
dani -> daniel, dani_56, dani563, elnenedani, ...
It is usually done by putting in PHP: %dani% but as I have put the %s to grab the variable $user, I do not know how to put it.
Any idea?
It is not a great Question. If you have searched well in Stackoverflow you would have go it the answer.. As you asked the Question the answer is.. Instead of Equal use LIKE:
function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username LIKE %'%s'%",$user);
if (count($result['result'])>0) {
//authorized
print json_encode($result);
} else {
errorJson('Actualization failed');
}
}
It seems the PHP code and DB is working well. Checkout the below links for the error:
iOS 5 JSON Parsing Results in Cocoa Error 3840
Cocoa error 3840 using JSON (iOS)
The Operation couldn't be completed. (Cocoa error: 3840.)
Cocoa Error 3840 - NSJSONSerialization
You should use the LIKE syntax. Make sure to include % to indicate wildcards:
query('SELECT IdUser, username FROM login
WHERE username LIKE "%' . $user . '%"')
My query() function is
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
I do not get fixed. This code is for an ios app that uses AFNetworking, might please that helps you know what happens because I do not get it

PHP Update MySQL DB with AJAX call isn't doing anything

I'm trying to update a field on my database with PHP and AJAX
I have tested and found that the correct data is being sent, but the PHP that is handling the update is not working correctly.
All that happens is that I get the else response in conditional.
I need to update the DB depending on what the user input is.
Like I said, all I get for the response is the else response.
$youruname = $_POST['youruname'];
$selectedplayer = $_POST['selectedplayer'];
$selPlayerUname = $_POST['selPlayerUname'];
$flag = "";
$itStatus = "";
$checkit = mysqli_query($conn,"SELECT it FROM login WHERE uname='$selPlayerUname'");
while($row = mysqli_fetch_array($checkit))
{
$itStatus = $row["it"];
}
if($itStatus == "not it")
{
mysqli_query("UPDATE login SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END WHERE uname IN ('$youruname', '$selPlayerUname')");
$flag = "success";
}
else if($itStatus == "it")
{
$flag = "nope";
}
else
{
$flag = "error";
}
echo json_encode(array("message" => $flag, "tagged" => $selectedplayer));
mysqli_free_result($checkit);
mysqli_close($conn);
There is something confusing here. You have a loop and after loop conditionals. Shouldnt your update query be inside a loop like:
while($row = mysqli_fetch_array($checkit))
{
$itStatus = $row["it"];
if($itStatus == "not it")
{
mysqli_query("UPDATE login SET it = CASE WHEN uname = '$youruname' THEN 'not it' ELSE 'it' END WHERE uname IN ('$youruname', '$selPlayerUname')");
$flag = "success";
}
else if($itStatus == "it")
{
$flag = "nope";
}
else
{
$flag = "error";
}
}
Your $iStatus gets the last value from the database since its in the loop and then you check in conditionals
If above does not help then check your $_POST values to see if any of them are blank or null and do the query on PHPMyAdmin see if it actually returns anything.
mysqli_query requires you to pass the connection.
I wasn't doin that.
When I passed the values to the query directly, I figured it out.
Thank you very much for the help everyone

Categories