PHP Insert into MySQL Database using $_SESSION['user'] in WHERE clause - php

I'm trying to insert variables into my database where the user data comes from $_SESSION['user'].
<?php
require("common.php");
if(empty($_SESSION['user']))
{
header("Location: login.php");
die("Redirecting to Login");
}
$user = $_SESSION['user'];
~calculations done~
$query = "INSERT INTO db (role,rolesub) VALUES ('$varRole','$varRoleSub') WHERE user = $user";
$query_params = array(
':role' => $varRole,
':roleSub' => $varRoleSub
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query 3: " . $ex->getMessage());
}
I keep getting this error:
Failed to run query 3: 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 user = Array' at line 1
I can not see where my WHERE clause is failing on me.
Any help would be greatly appreciated!!!

You cannot have a WHERE clause in an INSERT statement.
You're either looking for:
UDPATE db SET role = '$varRole', rolesub = '$varRoleSub' WHERE user = $user
Or:
INSERT INTO db (role,rolesub,user) VALUES ('$varRole','$varRoleSub',$user)
Or if you're feeling extra saucy, and user is your PK:
INSERT INTO db (role,rolesub,user) VALUES ('$varRole','$varRoleSub',$user)
ON DUPLICATE KEY UPDATE role = '$varRole', rolesub = '$varRoleSub'

INSERT queries do not and can not have a WHERE clause. This is the cause of the MySQL syntax error. If you need to insert based on some condition, you need to do that logic before the INSERT query.
If you want to do an UPDATE query then you can use the WHERE clause, however, the MySQL error shows $_SESSION['user'] is an array, which can't be put directly into SQL, so you'll need to access one of its elements such as $_SESSION['user']['id'].

First of all, IF you could have a WHERE in the same query as an INSERT, variables need to be separate from the string (outside of the quotes). BUT you CANT put a where clause into an INSERT.
So you could change this line:
$query = "INSERT INTO db (role,rolesub) VALUES ('$varRole','$varRoleSub') WHERE user = $user";
to:
$query = "INSERT INTO db (role,rolesub) VALUES (" . $varRole . ", " . $varRoleSub . ")";

Related

how i can slove this error,SQLSTATE[42000]? [duplicate]

This question already has answers here:
MySQL Insert query doesn't work with WHERE clause
(31 answers)
Closed 2 years ago.
please help me to solve this error.i tired from searching solution...
error: 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 'WHERE name=NULL' at line 1
my database have 3 column=id(int),name(varchar),comment(varchar) and i want insert comment to it.
my php code :
<?php
include "./Config.php";
include './MyPDO.php';
$response = array() ;
$connect = MyPDO::getInstance();
$name = $_REQUEST['name'];
$comment=$_REQUEST['comment'];
$query = " INSERT INTO user "
. " (comment) "
. " VALUES "
. " (:comment) "
. " WHERE name=:name ";
$stmt = $connect->prepare($query);
$stmt->bindParam(":name",$name);
$stmt->bindParam(":comment",$comment);
try {
$stmt->execute();
$response['massage'] = "sucess";
echo json_encode($response);
exit;
} catch (PDOException $ex) {
$response['massage'] = "error";
$response['error']=$ex->getMessage();
echo json_encode($response);
}
Looks like you mixed the syntax here. You seem to want to update an existing record. Use
update user
set comment = :comment
where name = :name
insert if for creating a new record.
The insert into ... values() syntax does not take a where clause.
If you want to insert, then:
insert into user(name, comment) values(:name, :comment)
But actually it looks like you might want an update:
update users set comment = :comment where name = :name;
The former creates a new record in the table, with the given name and comment.
The latter modifies the already-existing record that has the same name and sets its comment value.

insert data from a table and insert into another table in different database

I have 2 database that link together. I need to retrieve data from that table and insert those column into a table in different database based on their Unique id number.
<?php
$handle = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_query("USE shop",$handle);
$query = "SELECT ModelCode,Class FROM shopfloor_pro WHERE CommNo = '0985560712'";
$result = mysql_query($query);
while ($data = mysql_fetch_object($result)){
$variable1 = $data->ModelCode;
$variable2 = $data->Class;
mysql_query("USE vt",$handle);
$sql = "INSERT INTO track SET
t_model_code = '$variable1',
t_class = '$variable2' WHERE t_comm_no = '0985560712'";
if (!mysql_query($sql)) {
echo '<p>Error adding data into database: ' . mysql_error() . '</p>';
}
mysql_query("USE paintshop",$handle);
}
?>
this is the data that i want to retrieve
this is where i want to put the data
When i run the code it shows
"Error adding data into database: 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 t_comm_no = '0985560712'' at line 3"
You can most likely do this in a single query - but as pointed out the mysql api has been deprecated a long time ago and totally removed from PHP 7+.
To do the query in a single operation you might try like this:
insert into `vt`.`track` (`t_model_code`,`t_class` )
select `ModelCode`,`Class` from `shop`.`shopfloor_pro` where `CommNo`='0985560712'

PHP insert query gives syntax error but still writes into database

A query executes and writes into a database table and the field data is fetched and displayed in a WHILE loop so basically it works but I get a php error :
Error Inserting!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 \'1\' At Line 1
With line 1 being
<?php
I have tried playing around with commas and colons but I cannot get rid of the error. This is the query.
$Link = mysql_connect($Host, $User, $Password);
$user = $_SESSION['UserName'];
$query = mysql_query("INSERT INTO films VALUES ('0', '".($user)."','".($formValue["subject"])."',NOW(),'".($usercomments)."','".($formValue["rating"])."','action')");
if(mysql_query ($query, $Link)){
$message = "Thank you for your comments";
header("Location: films.php?message=$message");
}else{
$message = "Error Inserting!" . mysql_error();
header("Location: films.php?message=$message");
$query = "INSERT INTO films VALUES ('0', '$user','$formValue[subject]',NOW(),'$usercomments','$formValue[rating]','action')";
This may simplify the code and solve your error.

PHP, MYSQL error?

i recently started working with PHP and MYSQL, everything was going fine till I starter to get this error. Code works when I insert it into the query window at phpMyAdmin, but it doesnt work inside php code when i open it with a browser. Im already connected to database, so thats not the problem.
this is the error i get:
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 ''fatmam' (user,
messageid) VALUES ('ayihan', '5')' at line 1
try
{
$alicengiz = $_POST['actor'].'m';
$sql = 'INSERT INTO :tablename (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
$s->bindValue(':tablename', $alicengiz);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error 1qqq. '. $e->getMessage();
include 'error.php';
exit();
}
No. You cannot prepare table names, field names and sql keywords.
Problem is, that prepare() will add single quotes around the input, but table names and field names require backticks around them when you want to escape them.
This time you need to escape manually (*real_escape_string doesn't help here):
$sql = 'INSERT INTO `'.addcslashes($alicengiz, "\\'").'` (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
P.s.: but really, this is a bad idea. I'd use a whitelist instead of escaping, because when $_POST["actor"]."m" isn't a table name, a PDOException will be thrown.
How about this?
$alicengiz = $_POST['actor'].'m';
$sql = 'INSERT INTO messages (user, messageid) VALUES
(:user, :messageid)';
$s = $pdo->prepare($sql);
$s->bindValue(':user', $_SESSION['username']);
$s->bindValue(':messageid', $_POST['action1']);
$s->execute();

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.

Categories