how to update table with session variable in php pdo? - php

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

Related

PHP Mysql does not accept table name as variable

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."' ");
}

PDO + MySQL: PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064

I know this is probably ends up being a typo somewhere but I've tried to debug my syntax for two days and I've searched numerous discussion boards and stack overflow questions to no avail.
When I try to execute the following
try {
$cnnxn = new PDO("mysql:host=$db_host;dbname=$db_name", $db_username, $db_password);
} catch (PDOException $e) {
die("ERROR: " . $e->getMessage());
}
$query1 = "INSERT INTO reply_statistics (reply_id, assignment_id, cat1, cat2, cat3, cat4, cat5, cat6, cat7, cat8) VALUES (:replyid, :assid, :cat1, :cat2, :cat3, :cat4, :cat5, :cat6, :cat7, :cat8)
ON DUPLICATE KEY
UPDATE reply_statistics SET `cat1`=:cat1, `cat2`=:cat2, `cat3`=:cat3, `cat4`=:cat4, `cat5`=:cat5, `cat6`=:cat6, `cat7`=:cat7, `cat8`=:cat8 WHERE `reply_id`=:replyid";
$query2 = "UPDATE replies SET status=:status, corrected_reply=:correply, score=:score WHERE id=:replyid";
$cnnxn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$cnnxn->exec("SET NAMES utf8");
$query = $cnnxn->prepare($query1);
$query->bindParam(':replyid', $replyid);
$query->bindParam(':assid', $assid);
$query->bindParam(':cat1', $cat1);
$query->bindParam(':cat2', $cat2);
$query->bindParam(':cat3', $cat3);
$query->bindParam(':cat4', $cat4);
$query->bindParam(':cat5', $cat5);
$query->bindParam(':cat6', $cat6);
$query->bindParam(':cat7', $cat7);
$query->bindParam(':cat8', $cat8);
$query->execute();
if ($query !== false)
{
$statusreport = "OK";
}
if($statusreport == "OK"){
$query = $cnnxn->prepare($query2);
$query->bindParam(':replyid', $replyid);
$query->bindParam(':correply', $correply);
$query->bindParam(':status', $status);
$query->bindParam(':score', $score);
$query->execute();
if ($query !== false)
{
echo "<div class=\"alert alert-success\">Tallennettu.</div>";
}
}
$cnnxn = null;
I get this
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 'SET `cat1`='0', `cat2`='0', `cat3`='0', `cat4`='0', `cat5`='0', `cat6`='0', `cat' at line 3' in /[CENSORED]/do-review.php:56 Stack trace: #0 /[CENSORED]/do-review.php(56): PDOStatement->execute() #1 {main} thrown in /[CENSORED]/do-review.php on line 56
It connects fine and the variables set quite nicely, but it fails on the INSERT -- ON DUPLICATE KEY UPDATE clause.
About the table structure: reply_id is unique, but there is also a separate id column, which is a primary key with auto increment.
You have to treat the ON DUPLICATE set of parameters as totally seperately named parameters, even though you may use the same variables to bind data to them. And the query syntax was a little bit out of wack.
$query1 = "INSERT INTO reply_statistics
(reply_id, assignment_id,
cat1, cat2, cat3, cat4,
cat5, cat6, cat7, cat8)
VALUES (:replyid, :assid,
:cat1, :cat2, :cat3, :cat4,
:cat5, :cat6, :cat7, :cat8)
ON DUPLICATE KEY UPDATE
`cat1`=:cat1a, `cat2`=:cat2a,
`cat3`=:cat3a, `cat4`=:cat4a, `cat5`=:cat5a,
`cat6`=:cat6a, `cat7`=:cat7a, `cat8`=:cat8a ";
$query = $cnnxn->prepare($query1);
$query->bindParam(':replyid', $replyid);
$query->bindParam(':assid', $assid);
$query->bindParam(':cat1', $cat1);
$query->bindParam(':cat2', $cat2);
$query->bindParam(':cat3', $cat3);
$query->bindParam(':cat4', $cat4);
$query->bindParam(':cat5', $cat5);
$query->bindParam(':cat6', $cat6);
$query->bindParam(':cat7', $cat7);
$query->bindParam(':cat8', $cat8);
// parametes for the ON DUP set of params
$query->bindParam(':cat1a', $cat1);
$query->bindParam(':cat2a', $cat2);
$query->bindParam(':cat3a', $cat3);
$query->bindParam(':cat4a', $cat4);
$query->bindParam(':cat5a', $cat5);
$query->bindParam(':cat6a', $cat6);
$query->bindParam(':cat7a', $cat7);
$query->bindParam(':cat8a', $cat8);

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

Why do I get error SQLSTATE42000 in PHP/MySQL

I am working on a project using PHP and MySQL.
I have an HTML table that has 3 columns into which I load data from my "Tasks" table in MySQL. The columns are: id, taskname and a button column that when clicked on, takes you to the Edit page for the relevant task (I pass the task id as a URL) - http://localhost/tasks/?edit&id=3
The problem arises when I try to load the details about this task. This is the code:
if(isset($_GET["id"]))
{
try
{
$sql = "SELECT * FROM tasks WHERE id = :id";
$result = $pdo->prepare($sql);
$result->bindValue(":id", $_GET["id"]);
$result = $pdo->query($sql);
}
catch(PDOException $e)
{
$error = "Error trying to load task - " . $e->getMessage();
include "error.php";
exit();
}
foreach($result as $task)
{
$tasktext = $task["task"];
$id = $task["id"];
}
$title = "Edit task";
$action = "edittask";
$button = "Edit task";
include 'form.php';
exit();
resetParameters();
I get the following error:
Error trying to load task - 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 ':id' at line 1
When I replace the WHERE id = :id with WHERE id = 3 for example it works and loads the details about the task however I simply cannot get it to load the details about the task I have clicked on in the previous screen.
Could anyone spot anything wrong with my code/logic and point me in the right direction please?
You need to use execute() not query() when using prepared query's:
execute() PDOStatement::execute — Executes a prepared statement.
query() PDO::query — Executes an SQL statement.
Try:
<?php
try
{
$sql = "SELECT * FROM tasks WHERE id = :id";
$query = $pdo->prepare($sql);
$query->bindValue(":id", $_GET["id"]);
$query->execute();
$result = $query->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e)
{
$error = "Error trying to load task - " . $e->getMessage();
include "error.php";
exit();
}
?>

Categories