Always getting false response from pdo update query - php

I'm trying to update my database but whenever i do like this
if($query){
echo 'executed';
}
else {
echo 'error';
}
The problem I'm facing is that query is successfully updating database but result in false response here is my code
public static function updateItem($slug, $title, $description, $thumbnail, $preview, $main_file, $screenshot, $category, $amount, $review, $demo_url, $tags, $live, $video, $apc) {
$db = new Database;
$main_category = Login::encrypt_decrypt("decrypt", $apc);
$sub_category = Login::encrypt_decrypt("decrypt", $category);
$q = $db->updateRow("UPDATE items SET name = ?, description = ?, thumbnail = ?, main_file = ?, categories = ?, sub_category = ?, demo_url = ?, slug = ?, price = ?, reviewer_comment = ?, datetime = ?, status = ?, video_file = ?, item_tags_string = ?, preview_file = ?, screenshot_file = ?, live_file = ? WHERE user_id = ? AND temp_files != '' AND temp_file_real != '' AND status = ?", [$title, $description, $thumbnail, $main_file, $main_category, $sub_category, $demo_url, $slug, $amount, $review, Item::nowTime(), 'queue', $video, $tags, $preview, $screenshot, $live, Profile::getid(), 'temp']);
if($q){
echo 'good'; exit;
}
else {
echo 'wrong'; exit;
}
}
This is my database connection code
public function __construct($username = "root", $password = "", $host = "localhost", $dbname = "market", $options = []) {
$this->isConn = TRUE;
try {
$this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
here is update query function
public function updateRow($query, $params = []) {
$this->insertRow($query, $params);
}
public function insertRow($query, $params = []) {
try {
$stmt = $this->datab->prepare($query);
$stmt->execute($params);
return TRUE;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
can anyone tell me why I'm receiving false statement always

Your updateRow function doesn't return anything so '$q' is empty.
public function updateRow($query, $params = []) {
return $this->insertRow($query, $params);
}

Related

REST Api Structure prevents Database access

I'm hosting my files hostinger.in and is implementing REST architecture. When I was implementing the codes without REST, I was getting no error. But now it seems I can't access MySql Database. I narrow down possible errors which comes when I try registering a user and it seems the DB is inaccessible. Here are the codes:
public function sendOtp($mobile, $model, $brand, $device, $fingerprint, $hardware){
//Checking for User registration
if (!$this->isUserExists($mobile)) {
$otp = rand(100000, 999999);
$stmt = $this->con->prepare("INSERT INTO user_register(mobile, registered_mobile_model, registered_mobile_brand, registered_mobile_device, registered_mobile_fingerprint, registered_mobile_hardware, otp) values(?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssss", $mobile, $model, $brand, $device, $fingerprint, $hardware, $otp);
$result = $stmt->execute();
$stmt->close();
//If statment executed successfully
if ($result) {
//Returning 0, otp sent
return 0;
} else {
//Returning 1, failed to insert
return 1;
}
} else {
//user exists, update info and sent otp
$otp = rand(100000, 999999);
//Crating an statement
$stmt = $this->con->prepare("UPDATE user_register set otp = ?, registered_mobile_model = ?, registered_mobile_brand = ?, registered_mobile_device = ?, registered_mobile_fingerprint = ?, registered_mobile_hardware = ? WHERE mobile = ?");
//Binding the parameters
$stmt->bind_param("sssssss", $otp, $model, $brand, $device, $fingerprint, $hardware, $mobile);
//Executing the statement
$result = $stmt->execute();
//Closing the statement
$stmt->close();
//If statement executed successfully
if ($result) {
//Returning 0, user insert/update success, otp sent
return 0;
} else {
//Returning 1, failed to insert
return 1;
}
}
}
private function isUserExists($mobile) {
$stmt = $this->con->prepare("SELECT id from user_register WHERE mobile = ?");
$stmt->bind_param("s", $mobile);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
$stmt->close();
return $num_rows > 0;
}
The index.php code to reroute the api calls:
$app->post('/sendotp', function () use ($app) {
//Verifying the required parameters
verifyRequiredParams(array('mobile', 'model', 'brand', 'device', 'fingerprint', 'hardware'));
//Creating a response array
$response = array();
//reading post parameters
$mobile = $app->request->post('mobile');
$model = $app->request->post('model');
$brand = $app->request->post('brand');
$device = $app->request->post('device');
$fingerprint = $app->request->post('fingerprint');
$hardware = $app->request->post('hardware');
//Creating a DbOperation object
$db = new DbOperation();
$res = $db->sendOtp($mobile, $model, $brand, $device, $fingerprint, $hardware);
//If the result returned is 0 means success
if ($res == 0) {
//Making the response error false
$response["error"] = false;
//Adding a success message
$response["message"] = "OTP Sent";
//Displaying response
echoResponse(201, $response);
//If the result returned is 1 means failure
} else if ($res == 1) {
$response["error"] = true;
$response["message"] = "Oops! An error occurred while registering";
echoResponse(200, $response);
}
});

PHP PDO insert operation failing

I am new to PDO and I am having a problem with the following insert operation. It ends up always in the else case (returning 0).
function insertInclusao($usuarioId, $tipoFaturaId, $parametrosValidadores, $identificadorExtra, $optin) {
$pdoConnection = new PDO("mysql:host=host;dbname=dbname", "user", "pass");
try {
$stmte = $pdoConnection->prepare("INSERT INTO SF_INCLUSAO (UsuarioId, TipoFaturaId, ParametrosValidadores, DataInclusao, IdentificadorExtra, Optin) VALUES (?, ?, ?, NOW(), ?, ?)");
$stmte->bindParam(1, $usuarioId , PDO::PARAM_INT);
$stmte->bindParam(2, $tipoFaturaId , PDO::PARAM_INT);
$stmte->bindParam(3, $parametrosValidadores , PDO::PARAM_STR);
$stmte->bindParam(4, $identificadorExtra , PDO::PARAM_STR);
$stmte->bindParam(5, $optin , PDO::PARAM_INT);
$executarInclusao = $stmte->execute();
if($executarInclusao) {
return $pdoConnection->lastInsertId();
} else {
return 0;
}
} catch (PDOException $e) {
return -1;
}
}
It used to work when I was using mysql_query like this:
function insertInclusao($usuarioId, $tipoFaturaId, $parametrosValidadores, $identificadorExtra, $optin) {
$db_connection = mysql_connect( "host", "user", "pass" ) or die( mysql_error() );
mysql_select_db( "database" ) or die( mysql_error() );
$insert_query = "INSERT INTO SF_INCLUSAO (UsuarioId, TipoFaturaId, ParametrosValidadores, DataInclusao, IdentificadorExtra, Optin) VALUES ('".$usuarioId."', '".$tipoFaturaId."', '".$parametrosValidadores."', NOW(), '".$identificadorExtra."', '".$optin."');";
$query_return = mysql_query($insert_query);
$new_id = mysql_insert_id();
if($query_return) {
return $new_id; // OK
}
else {
return 0;
}
}
Right now I am failing to see what could be wrong. Any suggestions?
You need to set this
$pdoConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdoConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
You will now get the error because you have set the PDO error mode to exception.
function insertInclusao($usuarioId, $tipoFaturaId, $parametrosValidadores, $identificadorExtra, $optin) {
$pdoConnection = new PDO("mysql:host=host;dbname=dbname", "user", "pass");
$pdoConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdoConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
try {
$stmte = $pdoConnection->prepare("INSERT INTO SF_INCLUSAO (UsuarioId, TipoFaturaId, ParametrosValidadores, DataInclusao, IdentificadorExtra, Optin) VALUES (?, ?, ?, NOW(), ?, ?)");
$stmte->bindParam(1, $usuarioId , PDO::PARAM_INT);
$stmte->bindParam(2, $tipoFaturaId , PDO::PARAM_INT);
$stmte->bindParam(3, $parametrosValidadores , PDO::PARAM_STR);
$stmte->bindParam(4, $identificadorExtra , PDO::PARAM_STR);
$stmte->bindParam(5, $optin , PDO::PARAM_INT);
$executarInclusao = $stmte->execute();
if($executarInclusao) {
return $pdoConnection->lastInsertId();
} else {
return 0;
}
} catch (PDOException $e) {
return $e->getMessage();
}
}
Use this
$pdoConnection = new PDO("mysql:host=host;dbname=dbname", "user", "pass",array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
and then you can change this:
if($executarInclusao) {
return $pdoConnection->lastInsertId();
} else {
return 0;
}
for this:
return $pdoConnection->lastInsertId();
Because if something go wrong with query, $stmte->execute() throw PDOException

PHP : return last inserted Id on statement

So I want to get and return last inserted id from query.
I am successfully get the last inserted id but I have a little problem when try to return it to index.php file
This is my method code :
public function InsertUserCard(UserCard $uc)
{
if(!$this->DuplicateUserCard($uc))
{
$stmt = $this->conn->prepare("INSERT INTO ".$this->table_name."
(user_id, card_id, barcode, barcode_format, created_at, updated_at)
VALUES(?, ?, ?, ?, ?, ?)");
if ($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$user_id = NULL;
$card_id = NULL;
$barcode = NULL;
$barcode_format = NULL;
$created_at = NULL;
$updated_at = NULL;
$stmt->bind_param("iissss", $user_id, $card_id, $barcode, $barcode_format, $created_at, $updated_at);
$user_id = $uc->getUserId();
$card_id = $uc->getCardId();
$barcode = $uc->getBarcode();
$barcode_format = $uc->getBarcodeFormat();
$created_at = $uc->getCreatedAt();
$updated_at = $uc->getUpdatedAt();
$stmt->execute();
$result = $this->conn->insert_id; <-- This is how I get the last inserted id
$stmt->close();
}
// Check for successful insertion
if ($result)
{
// User card successfully inserted
return USER_CARD_INSERTED_SUCCESSFULLY;
}
else
{
// Failed to insert user card
return USER_CARD_INSERT_FAILED;
}
}
else
{
return USER_CARD_ALREADY_EXISTED;
}
}
and this is my index.php file
$app->post('/user/card/rev', 'authenticate', function() use ($app)
{
// check for required params
verifyRequiredParams(array('user_id', 'card_id', 'barcode', 'barcode_format', 'created_at', 'updated_at'));
global $user_id;
$response = array();
$timestamp = time();
$now = date("Y-m-d H:i:s", $timestamp);
$uc = new UserCard();
$uc->setUserId($user_id);
$uc->setCardId($app->request->post('card_id'));
$uc->setBarcode($app->request->post('barcode'));
$uc->setBarcodeFormat($app->request->post('barcode_format'));
$uc->setCreatedAt($app->request->post('created_at'));
$uc->setUpdatedAt($app->request->post('updated_at'));
// choose card from db by user
$UserCardDB = new UserCardDB(MySqlDb::getInstance()->connect());
$UserCard = $UserCardDB->InsertUserCard($uc);
if ($UserCard == USER_CARD_INSERTED_SUCCESSFULLY)
{
$response["error"] = false;
$response["message"] = "User Card added successfully";
$response["current_timestamp"] = $timestamp;
$response["current_date"] = $now;
$response["last_inserted_id"] = SHOULD_BE_HERE;
echoRespnse(201, $response);
}
});
as you see, I want to put the last inserted id on $response["last_inserted_id"], but I do not know how to do it.
any ideas ?
thanks:)
I think you have your statements backwards
$inserted_id = $this->conn->insert_id;
$result = $stmt->execute();
In prepared statements, execute is what runs your SQL. So you can't get the ID of what hasn't been inserted yet.
$result = $stmt->execute();
$inserted_id = $this->conn->insert_id;
You're also not storing the data anywhere usable ($inserted_id is a local variable to your function). Consider making a class variable like $this->inserted_id and making a function that would return that value.
Try this in you method:
public function InsertUserCard(UserCard $uc)
{
if(!$this->DuplicateUserCard($uc))
{
$stmt = $this->conn->prepare("INSERT INTO ".$this->table_name."
(user_id, card_id, barcode, barcode_format, created_at, updated_at)
VALUES(?, ?, ?, ?, ?, ?)");
if ($stmt == FALSE)
{
die($this->conn->error);
}
else
{
$user_id = NULL;
$card_id = NULL;
$barcode = NULL;
$barcode_format = NULL;
$created_at = NULL;
$updated_at = NULL;
$stmt->bind_param("iissss", $user_id, $card_id, $barcode, $barcode_format, $created_at, $updated_at);
$user_id = $uc->getUserId();
$card_id = $uc->getCardId();
$barcode = $uc->getBarcode();
$barcode_format = $uc->getBarcodeFormat();
$created_at = $uc->getCreatedAt();
$updated_at = $uc->getUpdatedAt();
}
// Check for successful insertion
if ($stmt->execute())
{
$result = $this->conn->insert_id;
$stmt->close();
return $result;
}
else
{
// Failed to insert user card
return USER_CARD_INSERT_FAILED;
}
}
else
{
return USER_CARD_ALREADY_EXISTED;
}
}
and in you index.php:
$app->post('/user/card/rev', 'authenticate', function() use ($app)
{
// check for required params
verifyRequiredParams(array('user_id', 'card_id', 'barcode', 'barcode_format', 'created_at', 'updated_at'));
global $user_id;
$response = array();
$timestamp = time();
$now = date("Y-m-d H:i:s", $timestamp);
$uc = new UserCard();
$uc->setUserId($user_id);
$uc->setCardId($app->request->post('card_id'));
$uc->setBarcode($app->request->post('barcode'));
$uc->setBarcodeFormat($app->request->post('barcode_format'));
$uc->setCreatedAt($app->request->post('created_at'));
$uc->setUpdatedAt($app->request->post('updated_at'));
// choose card from db by user
$UserCardDB = new UserCardDB(MySqlDb::getInstance()->connect());
$UserCard = $UserCardDB->InsertUserCard($uc);
if (($UserCard != "USER_CARD_INSERT_FAILED") and ($UserCard != "USER_CARD_ALREADY_EXISTED"))
{
$response["error"] = false;
$response["message"] = "User Card added successfully";
$response["current_timestamp"] = $timestamp;
$response["current_date"] = $now;
$response["last_inserted_id"] = $UserCard;
echoRespnse(201, $response);
}
});
The way I read that, your // Check for successful insertion section will never run because the function is terminated with return $result; before the conditional. Therefore, USER_CARD_INSERTED_SUCCESSFULLY is never returned.
In my functions, I usually return an array, for example:
$result = array( "status" => $status, "id" => $id );
return $result;
and, in the main:
$result = my_function();
$status = $result['status'];
$id = $result['id'];
I hope this help you!
In your method code instead of using $inserted_id use a $_SESSION variable $_SESSION['inserted_id']. Now you will be able to use this in your index.php
$response["last_inserted_id"] = $_SESSION['inserted_id '];

Blue-imp file-upload delete from database with additional variable

I'm using Blue-imp file-upload to upload files everything seems to be working great with one expception. I users data being saved to user directories based on their userId but when I try to delete the data from the database it deletes by $name variable, which is the filename.
That means all users with the a file with the same filename are being deleted from the database. How can I set the delete in my uploadHander.php file to delete by name and userId? Or by the insert id?
class CustomUploadHandler extends UploadHandler {
protected function handle_form_data($file, $index) {
$file->description = $_REQUEST['description'][$index];
$file->userId = $_REQUEST['userId'][$index];
$file->location = $_REQUEST['location'][$index];
$file->customId = $_REQUEST['customId'][$index];
}
protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
$index = null, $content_range = null) {
$file = parent::handle_file_upload(
$uploaded_file, $name, $size, $type, $error, $index, $content_range
);
if (empty($file->error)) {
$sql = 'INSERT INTO `'.$this->options['db_table']
.'` (`name`, `size`, `type`, `userId`, `description`,`location`,`customId`,`url`)'
.' VALUES (?, ?, ?, ?, ?, ?,?,?)';
$query = $this->db->prepare($sql);
$query->bind_param(
'sissssss',
$file->name,
$file->size,
$file->type,
$file->userId,
$file->description,
$file->location,
$file->customId,
$file->url
);
$query->execute();
$file->id = $this->db->insert_id;
}
return $file;
}
protected function set_additional_file_properties($file) {
parent::set_additional_file_properties($file);
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$sql = 'SELECT `type`, `description`,`location`,`userId`,`customId`,`url` FROM `'
.$this->options['db_table'].'` WHERE `name`=? and `id`=?';
$query = $this->db->prepare($sql);
$query->bind_param('ss', $file->name,$file->id);
$query->execute();
$query->bind_result(
$type,
$description,
$location,
$userId,
$customId,
$url
);
while ($query->fetch()) {
$file->type = $type;
$file->description = $description;
$file->location = $location;
$file->userId = $userId;
$file->customId=$customId;
$file->url=$url;
}
}
}
public function delete($print_response = true) {
$response = parent::delete(false);
foreach ($response as $name => $deleted) {
if ($deleted) {
$sql = 'DELETE FROM `'.$this->options['db_table'].'` WHERE `name`=? AND `id`=?';
$query = $this->db->prepare($sql);
$query->bind_param('ss',$name,$id);
$query->execute();
}
}
return $this->generate_response($response, $print_response);
}
}
$upload_handler = new CustomUploadHandler($options);
I found one error in your code
$query->bind_param('ss',$name,$id);
Use
query->bind_param('si',$name,$id);
$id is an integer and you were defining it by string.
Hope this will work for you.
Use this code ==>
public function delete($print_response = true) {
$response = parent::delete(false);
foreach ($response as $name => $deleted) {
if ($deleted) {
$sql = 'DELETE FROM `'.$this->options['db_table'].'` WHERE `name`=? AND `id`=?';
$query = $this->db->prepare($sql);
$query->bind_param('si',$name,$id);
$query->execute();
}
}
return $this->generate_response($response, $print_response);
}

INSERT query does not work, empty array?

<?php
class Worker extends Core {
public $name;
public $surname;
public $dob;
public $skills;
public $postcode;
public $street;
public $email;
public $tel;
public $ern;
public $result;
public function __construct () {
$this->name = 'name';
$this->surname = 'surname';
$this->dob = 'dob';
$this->skills = 'skills';
$this->postcode = 'postcode';
$this->street = 'street';
$this->email = 'email';
$this->tel = 'tel';
$this->ern = 'ern';
}
//Saving worker data to database, need provide group name (table name)
public function saveWorker($group) {
if(!(isset($this->conn))) parent::__construct();
try
{
$this->conn ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //catch exceptions
$q = 'INSERT INTO :group (name, surname, dob, skills, postcode, street, email, tel, erefnumber) VALUES (
:name,
:surname,
:dob,
:skills,
:postcode,
:street,
:email,
:tel,
:erefnumber)'; //sql query with group name
$stmt = $this->conn->prepare($q);
$stmt -> bindValue(':group', $group, PDO::PARAM_STR);
$stmt -> bindValue(':name', $this->name, PDO::PARAM_STR);
$stmt -> bindValue(':surname', $this->surname, PDO::PARAM_STR);
$stmt -> bindValue(':dob', $this->dob, PDO::PARAM_STR);
$stmt -> bindValue(':skills', $this->skills, PDO::PARAM_STR);
$stmt -> bindValue(':postcode', $this->postcode, PDO::PARAM_STR);
$stmt -> bindValue(':street', $this->street, PDO::PARAM_STR);
$stmt -> bindValue(':email', $this->email, PDO::PARAM_STR);
$stmt -> bindValue(':tel', $this->tel, PDO::PARAM_STR);
$stmt -> bindValue(':erefnumber', $this->erefnumber, PDO::PARAM_STR);
$results = $stmt->execute();
if($results > 0)
{
return 'Dodano: '.$ilosc.' rekordow';
}
else
{
return 'Wystapil blad podczas dodawania rekordow!';
}
}
catch(PDOException $e)
{
return 'There was some error: ' . $e->getMessage();
}
unset($stmt);
}
//no exceptions
public function getWorker()
{
$workerData = array (
"name" => $this->name,
"surname" => $this->surname,
"dob" => $this->dob,
"skills" => $this->skills,
"postcode" => $this->postcode,
"street" => $this->street,
"email" => $this->email,
"tel" => $this->tel,
"tel" => $this->erefnumber
);
return $workerData;
} // end getWorker();
public function searchWorker($name, $surname, $dob, $skills, $postcode, $street, $email, $tel, $erefnumber) {
}
function deleteWorker() {
}
function getEmployer() {}
public function __sleep () {
parent::__sleep();
}
} // end Person;
//DB connection
class Core {
public $conn;
public function __construct() {
$this->dbConnect();
}
public function dbConnect() {
$host = 'localhost';
$port = '3307';
$username = 'modium_test';
$password = 'test';
$database ='modium_test';
try{
$this->conn = new PDO('mysql:host='.$host.';dbname='.$database.';port='.$port, $username, $password );
echo 'Connection successful!';
echo var_dump($this->conn);
}
catch(PDOException $e){
echo 'Error: ' . $e->getMessage();
}
}
public function __sleep () {
unset($this->conn);
}
}
}
The query just doesn't work. Every previous function worked, but when I try to INSERT tables via sql query, nothing happends.
Worker is an object it's created well, then i get some POST array assigned to it, wich also works fine then i try to saveWorker but it gives nothing.
The invoking line:
var_dump($worker);
if (isset($worker)) echo 'worker is set';
if (isset($worker->conn)) echo 'thers connection is set';
$worker->saveWorker('workers');
With added lines:
echo "\nPDO::errorInfo():\n";
print_r($stmt->errorInfo());
print_r($this->conn->errorInfo());
echo "end of error info";
It gives me:
PDO::errorInfo():
Array ( [0] => ) Array ( [0] => 00000 )
end of error info
$stmt->execute() returns a boolean value (Manual). Try,
$results = $stmt->execute();
if($results !== FALSE) {
return 'Dodano: '.$ilosc.' rekordow';
} else {
return 'Wystapil blad podczas dodawania rekordow!';
}
Also, you cannot bind tablename.

Categories