How do i debug my query? - php

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

Related

I can't fetch results from my SQL Procedure

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;

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;
}

fetchColumn() failing on simple query, but fine on another

I need a second pair of eyes on this. I can NOT figure out why this function works just fine:
function get_password($db, $id) {
try {
$sql = $db->prepare('SELECT password FROM employee
WHERE employee.emp_id = ?');
$sql->bindParam(1, $id);
$sql->execute();
$password = $sql->fetchColumn();
} catch(Exception $e) {
echo $e->getMessage();
die();
}
return $password;
}
and this function fails on fetchColumn():
function get_name($db, $email) {
try {
$sql = $db->prepare('SELECT login
FROM employee
WHERE email = ?');
$sql->bindParam(1, $email);
$sql->execute();
$user_name = $sql->fetchColumn(0);
} catch(Exception $e) {
echo $e->getMessage();
die();
}
return $user_name;
}
I have verified the following:
I am trimming the email, so no extra white space is in there
the query works from the command line
the prepare() statement is successful and errorInfo() returns nothing
the bindParam() statement returns true and errorInfo() returns nothing
the execute() statement returns 1 row and errorInfo() returns nothing
the fetchColumn(0) statement returns False (ARGH!!!!) but errorInfo() still returns nothing.
I have also tried using just fetchColumn(), fetchAll, and other fetch attempts.
I have also tried re-writing in the SELECT to this:
'SELECT employee.login FROM employee WHERE employee.email = ?'
but results are the same.
Is there some concept here I'm missing? Any other ideas of how I might debug this?

PHP mysql return parameter when query result == true

In php I call a procedure in mysql. Now I want to check if a query result == true then set return variable in my php file in true or false if query failed. How can I do that?
This is my php code:
public function DeleteSingleAccount($accountId)
{
$Config = new Config();
$mysqli = $Config->OpenConnection();
mysqli_query($mysqli, "CALL DeleteSingleAccount($accountId)") or die("Query fail: ". mysqli_error());
}
This is my query in mysql for now:
DELETE
FROM table
WHERE accountId = par_AccountId
This code runs correct but I want to set an return parameter when query is true or false.
public function DeleteSingleAccount($accountId)
{
$Config = new Config();
$mysqli = $Config->OpenConnection();
return !! mysqli_query($mysqli, "CALL DeleteSingleAccount(" . intval($accountId) . ")");
}
I added intval() to avoid SQL injection (not needed if you're sure $accountId is always an integer, never null, empty string, user input, etc.)
Think your looking for something like this:
public function DeleteSingleAccount($accountId) {
$Config = new Config();
$mysqli = $Config->OpenConnection();
$result = mysqli_query($mysqli, "CALL DeleteSingleAccount($accountId)") or die("Query fail: ". mysqli_error());
//^Assignment of the query to a variable
if($result && mysqli_num_rows($result) > 0) {
//^Check if query is successfull ^ Check if query has 1 or more rows in it! (You can delete this check if you don't care about how many row's the result has)
echo "The query is successful and have 1 or more rows in it!";
} else {
echo "The query failed or have 0 rows in it!";
}
}

Updating DB data from PHP variables

I have a problem with variables in an SQL Statement. I have a form where a user can update his profile. The form redirects to action.php?action=settings
When I try without $variables, there is no problem! But the thing is, I have a lot of queries like this, but not for updating.
function change_user_data($trainer) {
require("database.php");
try {
$results = $db->query("UPDATE trainer SET email='$email', status='$status', password='$password' WHERE name='$trainer'");
} catch (Exception $e) {
echo "Data could not be changed!";
exit;
}
}
and this is my action.php
if ($action == "settings") {
$email = $_POST['email'];
$status = $_POST['status'];
$password = $_POST['password'];
change_user_data($trainer);
}
When I echo those $variables, they get displayed so they are not empty. But this query updates my table but with no data, so everything is empty afterwards.
I think the problem is variable scope.
Variables defined outside of function cannot use in function except global variable or something.
You have two method.
First. If change_user_data function is in action.php file, add "global $email, $status, $password" like this:
function change_user_data($trainer) {
global $email, $status, $password;
require("database.php");
try {
$results = $db->query("UPDATE trainer SET email='$email', status='$status', password='$password' WHERE name='$trainer'");
} catch (Exception $e) {
echo "Data could not be changed!";
exit;
}
}
Or second. Pass the email, status, password data to function. Then you can use it.
Please check this manual:
http://php.net/manual/en/language.variables.scope.php
you can try this:
$results = $db->query("UPDATE trainer SET email='".$email."', status='".$status."', password='".$password."' WHERE name='".$trainer."'");
change_user_data($trainer, $email, $password, $status);
function change_user_data($trainer, $email, $password, $status) {
require("database.php");
try {
$results = $db->query("UPDATE trainer SET email='$email', status='$status', password='$password' WHERE name='$trainer'");
} catch (Exception $e) {
echo "Data could not be changed!";
exit;
}
}
After You Gettings Post varibles Then Check For those variables
whether those are empty or not
if not empty or NULL Then Update Database with Update Query With Non empty Variables
May be
Wrong data type of your columns. Check your table structure carefully. Example: if you set you column email as int then you cannot insert or update it's row value as text or letter
Incorrect variables inside single quote. Try to concatenate variable and query string for better practice
If those don't work
Try to make mysql syntax error and check values of those variables, then you can define the error.
Sorry for my bad english
You have few problems with this function:
Scoping issue, you did not pass all values
You are vulnerable to sql injection
You dont check if the record is updated
function:
function change_user_data($db, $params) {
try {
$sql = "UPDATE trainer SET email= ?, status=?, password=? WHERE name=?";
$stmt = $db->prepare($sql);
$stmt->execute($params);
$success = ($stmt->rowCount() > 0) ? true : false;
} catch (Exception $e) {
echo "Data could not be changed!";
$success = false;
}
return $success;
}
Usage
require("database.php");
$params = array($trainer, $email, $password, $status);
$user_data_updated = change_user_data($db, $params);
if($user_data_updated){
echo 'user data updated';
}else{
echo 'user data did not update';
}

Categories