I need help with fetching my data from the database.
I have a procedure that returns a Results Set in the form of three fields: login, password and id. I'd love to get all this data and store it in an array, but It always returns an empty array. I tested the procedure and it works 100%.
PHP CODE:($data is an array of data which im getting from axios post)
$login = $data->login;
$password= $data->password;
$response = array();
$sql = "CALL xyz_login(:login,:password)";
$statement = $pdo->prepare($sql);
$statement->bindParam(':login',$login,PDO::PARAM_STR);
$statement->bindParam(':password',$password,PDO::PARAM_STR);
if($statement->execute()){
$response[] = $statement->fetchAll();
}
else{
$response[] = "error";
}
echo json_encode($response);
exit;
Related
I am newbie to PHP webservices using MySQL. I follow this tutorial. I created one table -> loan_applications using phpmyadmin. Currenlty I have 3 records in table related to id 1. I would like to retrive all 3 records and would like to encode it in json.
I tried multiple way and tried googling but unable to get proper json array in response. Here is my get_applications_list.php
<?php
require_once 'include/DB_Functions.php';
$db = new DB_Functions();
// json response array
$response = array();
if (isset($_GET['id'])) {
// receiving the post params
$id = $_GET['id'];
$applications = $db -> getApplicationsList($id);
if ($applications) {
// got applications successfully
$response["status"] = 0;
$response["id"] = $applications["id"];
$response["application_id"] = $applications["application_id"];
$response["requested_amount"] = $applications["requested_amount"];
$response["interest_per_day"] = $applications["interest_per_day"];
$response["gst"] = $applications["gst"];
$response["tenure"] = $applications["tenure"];
$response["processing_fees"] = $applications["processing_fees"];
$response["amount_user_get"] = $applications["amount_user_get"];
$response["amount_user_pay"] = $applications["amount_user_pay"];
$response["application_latitude"] = $applications["application_latitude"];
$response["application_longitude"] = $applications["application_longitude"];
$response["application_status"] = $applications["application_status"];
$response["created_at"] = $applications["created_at"];
$response["updated_at"] = $applications["updated_at"];
$response["message"] = "Applications details fetched successfully";
echo json_encode($response);
} else {
// applications failed to store
$response["status"] = 1;
$response["message"] = "Unknown error occurred in getting details!";
echo json_encode($response);
}
} else {
// receiving the post params
$response["status"] = 2;
$response["message"] = "Required parameters is missing!";
echo json_encode($response);
}
?>
Here is my DB_Functions.php
<?php
class DB_Functions {
private $conn;
// constructor
function __construct() {
require_once 'DB_Connect.php';
// connecting to database
$db = new Db_Connect();
$this->conn = $db->connect();
}
// destructor
function __destruct() {
}
public function getApplicationsList($id){
$stmt = $this->conn->prepare("SELECT * FROM loan_applications WHERE id = ?");
$stmt->bind_param("s", $id);
$stmt->execute();
$applications = $stmt->get_result()->fetch_assoc();
$stmt->close();
if($applications){
return $applications;
}else {
return false;
}
}
}
?>
Here is response which I am getting :
{"status":0,"id":1,"application_id":1,"requested_amount":5000,"interest_per_day":"0.50","gst":18,"tenure":28,"processing_fees":"5.00","amount_user_get":4705,"amount_user_pay":5700,"application_latitude":"9.999999999","application_longitude":"9.999999999","application_status":1,"created_at":"2018-10-10 21:45:17","updated_at":"0000-00-00 00:00:00","message":"Applications details fetched successfully"}
I am getting only one record but i need all 3 record which associated with id 1. I tried lot but unable to get.
So multiple problems here
1 - Although unsure but Currenlty I have 3 records in table related to id 1 seems incorrect statement. If id is primary key, you cannot have 3 records against one id
2 - $stmt->get_result()->fetch_assoc(); will always return one row, to get multiple rows or collection of rows you will need to do it like following
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
/* free result set */
$result->free();
}
3 - Its quite clear from following code that you are actually sending only one row back
if ($applications) {
// got applications successfully
$response["status"] = 0;
$response["id"] = $applications["id"];
$response["application_id"] = $applications["application_id"];
$response["requested_amount"] = $applications["requested_amount"];
$response["interest_per_day"] = $applications["interest_per_day"];
$response["gst"] = $applications["gst"];
$response["tenure"] = $applications["tenure"];
$response["processing_fees"] = $applications["processing_fees"];
$response["amount_user_get"] = $applications["amount_user_get"];
$response["amount_user_pay"] = $applications["amount_user_pay"];
$response["application_latitude"] = $applications["application_latitude"];
$response["application_longitude"] = $applications["application_longitude"];
$response["application_status"] = $applications["application_status"];
$response["created_at"] = $applications["created_at"];
$response["updated_at"] = $applications["updated_at"];
$response["message"] = "Applications details fetched successfully";
echo json_encode($response);
}
You should do it like this
$applications = getAllApplications(); //returns array of applications
$response['applications'] = $applications; // if they keys you want to send and database fields are same you don't need to set them separately
return json_encode($response);
I have created a MYSQL Procedure to fetch employee details. The calling procedure is
function call_procedure($procedure)
{
require_once("database_connect.php");
$db = Database::getInstance();
$mysqli = $db->getConnection();
$result = $mysqli->query("CALL $procedure");
return $result;
}
I call this function from another page by using this function:
function get_emp_details($parameters){
//create the query
$procedure = "fetchEmpDetails($parameters)";
$result = call_procedure($procedure);
// check for empty result
if (mysqli_num_rows($result) > 0) {
// looping through all results
// products node
$response['DATA'] = sqltoarray($result);
// success
$response['RESULT'] = 0;
$response['MESSAGE'] = 'Employee Details found';
$response['REQUEST'] =1;
}
else {
$response['DATA'] = '';
// no products found
$response['RESULT'] = 1;
$response['MESSAGE'] = "Incorrect Employee ID";
$response['REQUEST'] =1;
}
// echo no users JSON
return $response;
}
When I am using both the functions in the same file it is working fine. However, when I am using the two functions in different files, I am not getting any results when calling get_emp_details function.
To debug, I tried to echo values of $procedure and $result. The string in $procedure is as expected, but the value I am receiving in $result is nothing.
The login() function which is also defined in the same file as the get_emp_details() function is working fine. It is the get_emp_details() that is causing the problem.
Can anyone help me with this?? Thanks in Advance...
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;
}
I am trying to insert some data to the mysql database
$db = new DataBase($config);
// connect to the database RETURNS true if success false if fails
$conn = $db->connect();
// check whether the connection is successfull or not...
if ($db->isConnected())
{
//prepare the query
$query = 'INSERT INTO scoreboard (score) VALUES(:score) WHERE username=:username';
$bindings = array(
'score' => $score,
'username' => ($_SESSION['username'])
);
// call the query function from db class and retrieve the results as an array of rows.
$results = $db->setData($conn,$query,$bindings);
if ($results)
echo "Your Score is Updated!";
else
echo "Your Score is Not Updated!";
}
Heres what setData() does :
function setData($conn,$query,$bindings)
{
try {
// prepare the query
$stmt = $conn->prepare($query);
//binde the query with the data .here the data is $bindings
$stmt->execute($bindings);
return ( $stmt->rowCount() > 0 )
// return the result if the query is success else return false.
? $stmt
: false;
}
catch(Exception $e) {
// return error if something goes wrong
return false;
}
}
Everytime I run this script I get "Your Score is Not Updated" as output.
Where I am going wrong?
Is that the $_SESSION['username'] causing trouble?
Any help with proper explanation will be highly appreciated!
you are updating or inserting? try your query manually with static data on phpmyadmin, then make sure your session is set & return true if successfully data inserted
the fragment code
if (!empty($_POST)) {
$query = "SELECT userid FROM user WHERE email = :email";
$query_params = array(':email' => $_POST['email']);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex) {
$response["success"] = 0;
$response["message"] = "Database Error Get User ID!";
die(json_encode($response));
}
if ( false !== ($user = $stmt->fetch()))
{
$userid = $user['userid'];
}
else {
$response["success"] = 0;
$response["message"] = "Why you come here!";
die(json_encode($response));
}
I want to ask is that after that $row = $stmt->fetchAll(); How should I write the code of assigning the userid into $userid And php doesn't save the row result into a variable.
fetchAll() returns an array. so $row['userid'] will not be set. $row[0]['userid'] will.
Betterh would be to use:
if ( false !== ($user = $stmt->fetch()) )
{
$userid = $user['userid'];
} else
{
//user not found
}
What this code does, it tries to fetch a row fromt the statement. IF no row was found ->fetch() returns a boolean false. As long as it doesn't return false, we have a row from the statement that is available in the $user var now :)
$userID = isset($row['userid']);
Simply checks if $row['userid'] is set, i.e. it's a bool value.
Simply checking whether the array is empty or not will be sufficient for you to fetch the value straight away:
if(!empty($row))
{
$userId = $row['userid'];
}
You need to make your question become more precise, if this isn't what you're asking for.