PDO - Invalid syntax for UPDATE query - php

I am getting the 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 '= time + '1' WHERE username = 'admin-test'' at line 1 when I attempt to preform the following query:
try
{
$sth = $dbh->prepare("UPDATE alltimehighscores time = time + :time
WHERE username = :username");
$arr = array(
':username' => $username,
':time' => $time
);
$sth->execute($arr);
}
catch (PDOException $e)
{
echo $e->getMessage();
exit();
}
The $time and $username values are assigned earlier on from $_GET. $dbh is also assigned above, which is working fine as there is another query above which executes fine.
Looking at the error message I can see that time isn't being changed into the current database value so I am assuming that there must be a different way of doing this when using PDO.

You're missing a SET
UPDATE alltimehighscores SET time = time + :time WHERE username = :username

SET is missing:
UPDATE alltimehighscores SET `time` = `time` + :time
WHERE username = :username

Related

PHP PDO REPLACE works in phpadmin but not in php

Trying to update the record (timestamp) if it exists or insert a new record if it doesn't exist.
Table is:
id = int 12 primary key, auto increment
userid = int 12
viewerid = int 12
viewDateTime = TIMESTAMP
This sql works in phpmyadmin but not in php
SELECT #id := id FROM `profileViews` WHERE `userid` = 31 AND `viewerid` = 30 LIMIT 1;
REPLACE INTO `profileViews`(id, `userid`, `viewerid`, `viewDateTime`)
VALUES (#id, 31, 30, now());
Here is the php version:
$INSERTViewSQL = "SELECT #id := id FROM `profileViews` WHERE `userid` = ? AND `viewerid` = ? LIMIT 1;
REPLACE INTO `profileViews`(id, `userid`, `viewerid`, `viewDateTime`)
VALUES (#id, ?, ?, now());";
try{
$DBConnection->prepare($INSERTViewSQL)->execute([$profileid, $_SESSION["id"], $profileid, $_SESSION["id"]]);
} catch(PDOException $e) {
file_put_contents($ErrorLogFileForPDO, 'update view : ' .$e->getMessage()."\n", FILE_APPEND);
}
Here is the error message:
update view : 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 'REPLACE INTO profileViews(id, userid, viewerid, viewDateTime)
VALUES (#i' at line 2
Thanks‼️
MySQL document says:
SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by ; characters).
So you need to fetch id value first, execute replace statement after that.
$stmt = $DBConnection
->prepare("SELECT id FROM ...");
$stmt->execute([$profileid, $_SESSION["id"]]);
$id = $stmt->fetchColumn();
$DBConnection
->prepare("REPLACE INTO ...");
->execute([$id, $profileid, $_SESSION["id"]]);

PDO SQLSTATE[42000] on simple select query

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.

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` = ?");

PHP PDO update statement fails

The below sql UPDATE statement returns an error but I'm unable to see why:
Failed to run query: 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 ')' at line 6
I already did a vardump of the array that I pass to bind the parameters but I see nothing unusual. The correct values are passed and I double checked for typos.
What I try to accomplish is to auto-generate a username based on firstname - lastname and user_id after insertion into the database.
Perhaps additional question: do you see any harm in that and if so, what is your suggestion?
I'm still in PHP learning phase.
Thanks.
...
//Autogenerate user_name based on first name, last name and user_id (auto-increment)
$query_username = "
UPDATE user_tbl
SET
user_name = :username
WHERE
user_id = :userid
)
";
// The parameter values
$query_params_username = array(
':username' => $_SESSION['user']['first_name'].".".$_SESSION['user']['last_name'].$_SESSION['user']['user_id'],
':userid' => $_SESSION['user']['user_id']
);
try
{
// Execute the query against the database
$stmt_username = $db->prepare($query_username);
$stmt_username->execute($query_params_username);
}
catch(PDOException $ex)
{
//Not to be used in production
die("Failed to run query: " . $ex->getMessage());
}
$_SESSION['user']['username'] = $_SESSION['user']['first_name'].".".$_SESSION['user']['last_name'].$_SESSION['user']['user_id'];
You had a closing parentheses after user_id = :userid
Try the following:
$query_username = "
UPDATE user_tbl
SET
user_name = :username
WHERE
user_id = :userid
";
Try doing this:
$query_username = "
UPDATE `user_tbl`
SET `user_name` = :username
WHERE `user_id` = :userid
";
There seems to be a lost ) character in your code.

PDO error message 1064

I am having trouble getting this to work I will include the code both working and what I am trying to accomplish. In the first code it is non-working and gives me an error message: Connection failed: 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 ':userName ANDpassword=:userPass' at line 1
I have tried several different combinations of syntax and still no luck. In the second code example it is working code and basically I am trying to get rid of all the unnecessary code to just obtain a $row count from the function to verify that there was 1 row that matched the query.
function checkLogin($conn,$myusername, $mypassword) {
$stmt = $conn->prepare('SELECT COUNT(*) FROM `CLL_users` WHERE `user_name`= :userName AND `password`= :userPass');
$stmt->bindValue(':userName', $myusername);
$stmt->bindValue(':userPass', $mypassword);
$stmt->execute();
$count = $stmt->fetchColumn();
return $count;
}
function checkLogin($conn,$myusername, $mypassword) {
$stmt = $conn->prepare('SELECT COUNT(*) FROM `CLL_users` WHERE `user_name`= :userName AND `password`= :userPass');
$stmt->bindValue(':userName', $myusername);
$stmt->bindValue(':userPass', $mypassword);
$stmt->execute();
$count = $stmt->fetchColumn();
return $count;
}

Categories