PHP Mysql does not accept table name as variable - php

mysql does not recognize the name of my table in a variable in a function, what can it be?
My PHP Code:
$TableMaster = "table_name";
function recursiveDelete($id,$db,$table){
$db_conn = $db;
$query = $db->query("SELECT * FROM ".$table." WHERE Padre = '".$id."' ");
if ($query->rowCount()>0) {
while($current=$query->fetch(PDO::FETCH_ASSOC)) {
recursiveDelete($current['id'],$db_conn);
}
}
$db->exec("DELETE FROM ".$table." WHERE id = '".$id."' ");
}
recursiveDelete($_POST['id'],$db,$TableMaster);
ERROR PHP LOG:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE Father = '99'' at line 1' in
Note: But when I write the name of my mysql table directly in the statement there is no problem.
Whats happen?

You left out the $table argument when making the recursive call.
There's also no need for the $db_conn variable, you can just use $db.
function recursiveDelete($id,$db,$table){
$query = $db->query("SELECT * FROM ".$table." WHERE Padre = '".$id."' ");
if ($query->rowCount()>0) {
while($current=$query->fetch(PDO::FETCH_ASSOC)) {
recursiveDelete($current['id'],$db,$table);
}
}
$db->exec("DELETE FROM ".$table." WHERE id = '".$id."' ");
}

Related

how to update table with session variable in php pdo?

i have one table called post_data, In that i want to update columns based on session variable.
this is my query.
$id = $_SESSION['userSession'];
$stmt = $user_home->runQuery("UPDATE post_data
set
cam_name='$cname',
cam_model ='$model',
cam_rent='$rent',
cam_img='$upic',
mobile='$umob'
upd_date='$jdate'
where userID='$id'
");
$stmt->bindParam(':cname',$camname);
$stmt->bindParam(':model',$modelname);
$stmt->bindParam(':rent',$rentpday);
$stmt->bindParam(':upic',$userpic);
$stmt->bindParam(':umob',$usermob);
$stmt->bindParam(":jdate",$upd_date);
if($stmt->execute())
{
$successMSG = "Record saved success";
}
else
{
$errMSG = "error while inserting....";
}
this is runQuery() implementation in USER class
public function runQuery($sql)
{
$stmt = $this->conn->prepare($sql);
return $stmt;
}
i got error like this
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'upd_date='2017-09-24 21:29:18' where ' at line 8 in C:\xampp\htdocs\DSLR_proj\profile.php:97
You are missing , just after mobile='$umob'.
Also, $cname is not same :cname. I would prefer to use placeholder as ? instead of any specific string to avoid any typo.
Also, you are missing binding for userID column.
UPDATE post_data
set cam_name=?,cam_model =?, cam_rent=?, cam_img=?, mobile=?, upd_date=?
where userID=?
$stmt->bindParam(1,$camname);
$stmt->bindParam(2,$modelname);
$stmt->bindParam(3,$rentpday);
$stmt->bindParam(4,$userpic);
$stmt->bindParam(5,$usermob);
$stmt->bindParam(6,$upd_date);
$stmt->bindParam(7,$id); // you are missing this as well

Mysql delete query using zend

i'm developing an application where there is a function (correctly called) that receive an id an should delete records from a table where the id is present.
This is my code:
public function deleteAction($id) {
if ($id) {
$where[] = $this->_db->quoteInto('transazione = ?', $id);
$this->_db->delete($this->_name, $where);
}
}
The function is correctly called but i receive this error:
An error occurred
SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ')' at line 1
How can i solve this?
try
$n = $this->_db->delete('tablename', "column_id = $id");
/*or*/
$q = $this->_db->quoteInto('DELETE * FROM bugs WHERE reported_by = ?', $id);
$this->_db->query($q);

SQL Syntax Error with update

I'm trying to set up a way for users to set settings, i'm saving the settings in a json format in the databse. When I try to update the user though I get this syntax error:
Warning: PDOStatement::execute(): SQLSTATE[42000]: Syntax error or
access violation: 1064 You have an error in your SQL syntax; check the
manual that corresponds to your MariaDB server version for the right
syntax to use near ''settings' = '{\"background-color\":\"050505\"}'
WHERE ID = '2'' at line 1 in
C:...\htdocs\app\model\model.database.php on line 29
Here is the code that I have.
public function setColor(){
$modUser = $this->model('user');
$modInput = $this->model('input');
$modViewData = $this->model('viewData');
$modUser->setSetting("background-color",str_replace('#', "", $modInput->returnPost("color")));
$this->view('profile/view.profile', $modViewData->getData());
}
//in User model
public function setSetting($name, $value){
$settings = $this->getSetting();
$settings[$name] = $value;
$settings = json_encode($settings);
$this->update("settings", $settings);
}
public function update($field, $value){
$sql = "UPDATE `users` SET :field = :value WHERE `ID` = :id";
$params = [":field" => $field, ":value" => $value, ":id" => $this->_data->ID];
$database = $this->model('database');
$database->query($sql,$params);
}
You cannot a parameterize table and column names. You need to insert those directly into the query string. One method is:
$sql = "UPDATE `users` SET $field = :value WHERE `ID` = :id";

PHP PDO UPDATE query with bind params

I'm trying to run the following query:
$sth = "UPDATE `users` SET users_password VALUES (:hash) WHERE users_id = $users_id";
$q = $conn->prepare($sth);
$q->execute(array(':hash'=>$hash));
But Im getting the following:
Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VALUES ('$2y$12$Ao46iC7W9Lj8FFfSmAaeoeQs9O.3QRVtDbHAyvpzH90YIUN61ma8i') WHERE us' at line 1'
Any ideas?
(and yes the code isn't in a try, catch block yet just experimenting at them moment with a few things)
change this
$sth = "UPDATE `users` SET users_password VALUES (:hash) WHERE users_id = $users_id";
to
$sth = "UPDATE `users` SET users_password = :hash WHERE users_id = $users_id";

PDO order by throws error

I am confused.
This is working:
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC';
$stmt = $conn->prepare($sql);
$stmt->execute();
This is not:
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD :orderbydateofupload';
$stmt = $conn->prepare($sql);
$stmt->bindValue(':orderbydateofupload', $orderbydateofupload, PDO::PARAM_STR);
$stmt->execute();
I have checked and set $orderbydateofupload by $orderbydateofupload='DESC', so it's definitely not null.
I get an error to the last line ($stmt->execute()):
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''DESC'' at line 1' in /home/gh6534/public_html/query.php:77 Stack trace: #0 /home/gh6534/public_html/query.php(77): PDOStatement->execute() #1 {main} thrown in /home/gh6534/public_html/query.php on line 77
I also tried to use the column as parameter:
$sort = 'DATEOFUPLOAD';
$sql = 'SELECT * FROM TABLE ORDER BY :sort :orderbydateofupload';
$stmt = $conn->prepare($sql);
$stmt->bindParam(':sort', $sort);
$stmt->bindParam(':orderbydateofupload', $orderbydateofupload);
$stmt->execute();
This does not throw an exception, but all items are queried without any sorting. What's wrong?
Try this
$orderbydateofupload = 'ASC'; //Or DESC
if($orderbydateofupload == 'DESC')
$sql = 'SELECT * FROM TABLE ORDER BY DATEOFUPLOAD DESC';
else
$sql = 'SELECT * FROM TABLE'
You can't bind identifiers with PDO because prepared statements can be used only with data, but not with identifiers or syntax keywords.
So, you have to use whitelisting, as shown in the example I posted before
That's why in my own class I use identifier placeholder, which makes whole code into one line (when you need to set the order by field only):
$data = $db->getAll('SELECT * FROM TABLE ORDER BY ?n',$sort);
but with keywords whitelisting is the only choice:
$order = $db->whiteList($_GET['order'],array('ASC','DESC'),'ASC');
$data = $db->getAll("SELECT * FROM table ORDER BY ?n ?p", $sort, $order);

Categories