PDO SQLSTATE[42000] on simple select query - php

Im just new with programming in OOP, so im writing a function but it gives an error, i think im using PDO wrong, actually i now it for sure, but i dont now how to fix it. This is my code im using currently:
public function takedrugs($soort, $hoeveelheid, $id){
$conn = $this->conn;
$drugsophalen = $conn->prepare('SELECT * FROM gebruikers WHERE id=:id');
$drugsophalen->execute(array(':id' => $id));
$result = $drugsophalen->fetch();
$huidigdrugs = $result[$soort];
if($huidigdrugs >= $hoeveelheid){
//Voldoende drugs dus drugs afnemen
$drugsafnemen = $conn->prepare('UPDATE gebruikers
SET :soort = :soort - :hoeveelheid,
WHERE id = :id');
$drugsafnemen->execute(array(
':soort' => $soort,
':hoeveelheid' => $hoeveelheid,
':id' => $id));
} else {
return false;
}
}
So when i use this function i get an error, its all about the SET :soort = :soort - :hoeveelheid.
This is the error i get:
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 ''Cannabis' =
'Cannabis' - '2000', WHERE id ' at line 2' in
I hope there are some people who now how to fix it since i dont :S
Thanks in advance!

You CANT bind column names SEE Complex Cases in PDO info.
Also as Jason states about lazy binding use bindParam OR bindValue
TRY
$drugsafnemen = $conn->prepare('UPDATE gebruikers
SET $soort = $soort - :hoeveelheid,
WHERE id = :id');
$drugsafnemen->bindParam(':hoeveelheid', $hoeveelheid, PDO::PARAM_INT);
$drugsafnemen->bindParam(':id', $id, PDO::PARAM_INT);
$drugsafnemen->execute();

You have two problems:
First, by using execute() all your values are being treated as a string. This results in the syntax error:
UPDATE gebruikers SET field = 'Cannabis' - '2000' ...
I assume this is not your intention. Instead, use bindParam() so you can define these parameters as integers.
$drugsafnemen->bindParam(':soort', $soort, PDO::PARAM_INT);
Second, you should are setting the column name dynamically (:soort). As such, it too is getting interpolated with $soort, which is probably not your intention.

Related

My PDO Prepared Statement is not working with a fetchALL and Limit [duplicate]

This question already has answers here:
How to apply bindValue method in LIMIT clause?
(11 answers)
Closed 2 years ago.
I am trying to get some products from my database with a prepared PDO statements. The formula worked well if I included the variable inside the SQL but of course this is really bad practice.
Working formula:
protected function getSomeProducts($somequantity){
$sql = "SELECT * FROM products ORDER by ID DESC LIMIT $somequantity";
$stmt = $this->connect()->query($sql);
$result = $stmt->fetchAll();
return $result;
My approach to the prepared statement:
protected function getSomeProducts($somequantity){
$sql = "SELECT * FROM products ORDER by ID DESC LIMIT ?";
$stmt = $this->connect()->prepare($sql);
$stmt->execute([$somequantity]);
$result = $stmt->fetchAll();
return $result;
}
This is the error message I get:
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 ''6'' at line 1.
Any idea what Im doing wrong could be?
replace the below line
$stmt->execute([$somequantity]);
with
$stmt->bindParam(1, $somequantity, PDO::PARAM_INT);
$stmt->execute();

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

Syntax error or access violation: 1064 don t get it?

the text i get in the browser:
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 ''users' WHERE 'username'= 'cAASDASD'' at line 1
maybe it is in this part?
otherwise i have no more 'WHERE'.
public function user_exists($username) {
$query = $this->db->prepare("SELECT COUNT('id') FROM 'users' WHERE 'username'= ?");
$query->bindValue(1, $username);
try {
$query->execute();
$rows = $query->fetchColumn();
if($rows == 1) {
return true;
}
else {
return false;
}
}
catch (PDOException $e) {
die($e->getMessage());
}
}
in the real code you run there are 'single quotes' are used around table name, not backticks as in one posted here
And you have no idea where this error occurred because of the wrong way of using exceptions. So, as soon as you remove that useless try-catch, as soon you will be informed of the exact place where error occurred
The error doesn't relate to the snippet of PHP code you're showing. Going by the error message, it looks like you're using something like:
$query = $this->db->prepare("SELECT * FROM 'users' WHERE 'username' = ?");
Here, the table and column are both using single quotes rather than back ticks. What you want is:
$query = $this->db->prepare("SELECT * FROM `users` WHERE `username` = ?");

Insert a PHP variable in a MySql SQL Statement

I'm trying to do like this using PHP and MySql PDO:
//PHP Variables
$msg_a = 'Too Little';
$msg_b = 'Score OK';
$sql = "select if(stdScore >= stdRequired, $msg_a, $msg_b) from scores;"
$results = $conn->prepare($Sql);
$results->execute();
AFAIK this should have worked. But I keep getting the following error message:
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 '
How can something like this be done?
$results = $conn->prepare($Sql);
---------------------------------------------^ (capital S)
it should be with a lowercase s
$results = $conn->prepare($sql);
because you have:
$sql = "select if(stdScore >= stdRequired, $msg_a, $msg_b)
from scores";(//semicolon after double quotes)
---^
with a lowercase s ($sql)
Can you try this,
$sql = "select if(stdScore >= stdRequired, $msg_a, $msg_b) from scores";
$results = $conn->prepare($sql);
Have you tried it this way ?
$sql = "select if(stdScore >= stdRequired, "'.$msg_a.'", "'.$msg_b.'") from scores;"
Since you're already using PDO don't do query string interpolation leaving your code vulnerable to sql injections and value escaping problems. Instead use prepared statements properly.
Your code could've looked something like
$msg_a = 'Too Little';
$msg_b = 'Score OK';
// use placeholders in a query string
$sql = "SELECT IF(stdScore >= stdRequired, :msg_a, :msg_b) msg FROM scores";
// prepare the statement
$query = $conn->prepare($sql);
// bind parameters and execute the query
$query->execute(array(':msg_a' => $msg_a, ':msg_b' => $msg_b));
// fetch the resultset
$rows = $query->fetchall(PDO::FETCH_ASSOC);

pdo pagination limit error

I have a pagination script and I am trying to change the mysql database into pdo database but I get this error; 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 'DESCLIMIT -2,2' at line 1
The part of code what gives me troubles is;
$limit = "LIMIT ".($page-1)*$perPage.",$perPage";
//$offset = ($page - 1) * $perPage;
$query = $db->prepare('SELECT image_id FROM images WHERE album_id= ? ORDER BY image_id DESC'.$limit);
$query->bindValue(1, $album_id);
//$query->bindParam(':limit', $limit, PDO::PARAM_INT);
try{
$query->execute();
}catch (PDOException $e){
die($e->getMessage());
}
I searched on google for solutions but my pdo knowledge is not good enough to use it right. I got errors like; SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens, because of $query->bindParam(':limit', $limit, PDO::PARAM_INT);
I don't know how to solve this, can anybody help me?
Thanks...
It seems mysql don't like negative offsets. You can make it this way
$limit = ($page-1)*$perPage;
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
$sql = 'SELECT image_id FROM images WHERE album_id=? ORDER BY image_id DESC LIMIT ?,?';
$stmt = $pdo->prepare($sql);
$stmt->execute([$album_id,$limit,$perPage]);
$ids = $stmt->fetchAll(PDO::FETCH_COLUMN);
In the tutorial the first query was $count_query = $db->prepare('SELECT NULL FROM images where album_id= ?');
That worked in the tutorial but not here, I think that gave the negative value.
I changed this into $count_query = $db->prepare('SELECT * FROM images where album_id= ?');
and the error is gone. Other errors is showing up now, hopefully I can solve that.
Thanks for helping me solve this error.

Categories