SQL Syntax error - SET - php

SQL error in a PHP script, I'm very new to SQL. It's probably something silly that's been asked loads before, but I'm probably searching for the wrong thing and therefore can't find an answer - I did look!
SQL error
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 approved = '1' WHERE primary = '16'' at line 1
The problem line:
$query = "UPDATE $table SET approved = '1' WHERE primary = '$id';";
Rest of my code:
<?PHP require ('config.php');
$id = $_GET['id'];
$query = "UPDATE $table SET approved = '1' WHERE primary = '$id';";
$execute = mysqli_query($conn,$query);
if ($execute){
echo "Entry $id successfully approved.";
}
else { echo "Error: " . $sql . "<br>" . mysqli_error($conn);};
?>

Try this way to set your $table variable first as it causes Syntax Error & add backtick (`) to your primary column name, because it's RESERV Keyword of MYSQL, But this may be not the main reason here.
<?php
require ('config.php');
try {
$id = $_GET['id'];
$approved=1;
$table="your_table_name"; // set table name here
$database="your_database_name";
$dbUser="your_user_name";
$dbPass="your_password";
$dbh = new PDO("mysql:host=your_host_name;dbname=$database", $dbUser, $dbPass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("UPDATE $table SET approved =? WHERE `primary` = ?");
$stmt->execute(array($approved,$id));
echo "Entry $id successfully approved.";
} catch(PDOException $e) {
echo $e->getMessage();
}
?>

Related

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 - PHP MYSQL

I understand this is a duplicate of previously asked questions. However, I have followed previous answers and still getting no results.
I am using a prepared statement to take a comment from a html <form> with the method post. the comment along with the unique id in the session is being passes to the page addComment.php
This is the contents of "addComment.php"
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "somedatabase";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO patients( comments ) VALUES ( :comment ) WHERE unique_id = :unique_id");
$stmt->bindParam( ':comment', $comment );
$stmt->bindParam( ':unique_id', $unique_id );
$comment = $_POST[ 'comment' ];
$unique_id = $_SESSION[ 'unique_id' ];
$stmt->execute();
//header('Location: newMedicine.php');
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
I have done an echo on
$comment = $_POST[ 'comment' ];
$unique_id = $_SESSION[ 'unique_id' ];
and both of them print fine.
The error I am getting is
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 'WHERE
unique_id = 'JohnDoe20RG2018-01-23 11:43:' at line 13
The unique_id field in the patients table in the database has the same value
JohnDoe20RG2018-01-23 11:43:17
I don't see where I am going wrong. I have used multiple prepared statements with Selects and Inserts throughout my project, and they all work fine.
Any help would be appreciated.
If you are creating a new record with the id and comment, then use...
$stmt = $conn->prepare("INSERT INTO patients ( unique_id, comments )
VALUES ( :unique_id, :comment ) ");
If it's an existing record -
$stmt = $conn->prepare("UPDATE patients SET comments=:comment
WHERE unique_id = :unique_id");

PHP Update Data in MySQL using PDO [duplicate]

This question already has answers here:
Sql syntax error using UPDATE database query [closed]
(2 answers)
Closed 7 years ago.
I'm trying to Update Data in MySQL using PDO.
I have set up the code below but get 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 '(h1, text) values ('Blah blah' at line 1
if (isset($_POST['Submit']))://if admin wants to edit category
$h1 = $_POST['h1'];
$text = $_POST['text'];
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "dbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepare statement
$stmt = $conn->prepare('UPDATE sections (h1, text) values (:h1, :text) WHERE id=1');
$stmt->bindParam(':h1', $h1);
$stmt->bindParam(':text', $text);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
Update syntax should be:
UPDATE table_name SET `field1` = new-value1, `field2` = new-value2.
Your query should be:
UPDATE sections SET `h1` = :h1, `text` = :text WHERE id = 1;
See the Update query syntax
text is a reserved word in mysql.
Write your query as below:-
UPDATE sections SET `h1` = :h1, `text` = :text WHERE id = 1;

SQL Error while working on web with PhP

While giving the correct login ID and Password which is there in the databse "tutorial" in table "users", it is giving me an error on the login.php which is being redirected.
Error is:
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 'user' = 'XYZ'' at line 1
where XYZ is the username given from the user.
<?php
$inputuser = $_POST["user"];
$inputpass = $_POST["pass"];
$user = "root";
$password = "";
$database = "tutorial";
$connect = mysql_connect("localhost", $user, $password);
#mysql_select_db($database) or die("Database not found");
$query = "SELECT * FROM 'users' WHERE 'user' = '$inputuser'";
$querypass = "SELECT * FROM 'users' WHERE 'password' = '$inputpass'";
$result = mysql_query($query) or die(mysql_error());
$resultpass = mysql_query($querypass) or die( mysql_error());
$row = mysql_fetch_array($result);
$rowpass = mysql_fetch_array($resultpass);
$serveruser = $row["user"];
$serverpass = $row["password"];
if ($serveruser && $serverpass){
if(!$result){
die("Username Name or Password is invalid");
}
echo "<br><center>Database Output</b> </center><br><br> ";
mysql_close();
echo $inputpass;
echo $serverpass;
if($inputpass == $serverpass){
header('Location: home.php');
} else {
echo "Sorry, bad Login";
}
}
?>
Abhik Chakraborty is correct.
If you want to enclose field/column or table names you have to use backticks (so ` instead of '). The backtick is the diagonal quote on the button next to the "1", above "Tab".
To enclose field values you should use quotes the way you did.
Your corrected query: SELECT * FROM `users` WHERE `user` = '$inputuser';
HOWEVER, you should never, ever insert input gotten from a user directly into a query. If they type in something like a';DROP TABLE your_table_name; they can cause your database to start deleting tables, requesting records, etc.
Use correct escaping of user input: see this StackOverflow article on how to safely escape user input.
Instead of single quotes you should use back ticks (`)

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();
}
?>

PHP updating large database

I have a large database (28k entries in this particular table one table) and I need to append some HTML tags to the front and back of every column in a table.
Here is my code:
try
{
$conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
if(!$conn)
{
echo "Error in connecting to the database.";
}
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
$query = $conn->query("SELECT `id`, `introtext` FROM *TABLE* WHERE id >= 41155");
$query->setFetchMode(PDO::FETCH_OBJ);
//For each row in the table
while($row = $query->fetch())
{
$introtext = '<span class="*SPAN CLASS*">' . $row->introtext . '</span>';
$update_query = $conn->prepare("UPDATE *TABLE* SET introtext = ? WHERE id = ?");
if ($query->execute(array($introtext, $row->id)))
echo $row->id . " Done <br>";
else
echo $row->id . " Err<br>";
}
} catch(PDOexception $e) {
echo $e->getMessage();
}
$conn = null;
When I run the script, it outputs 41155 Done 4132 times. I'm not sure the logic here, but any help to get this working is appreciated.
I agree with Dagon that the database is not the place for that (what if tomorrow you decide that <span> should wrap another HTML tag?).
Anyway, it sounds like a one-time operation, so I wouldn't use PHP. Just run a MySQL client (the command line mysql, or Workbench, and use a query like this:
UPDATE *TABLE*
SET introtext = CONCAT('<span class="*SPAN CLASS*">', introtext, '</span>')
WHERE id >= 41155
One note about your current code: you're never executing the UPDATE query! You just prepare the statement, then instead of executing $update_query, you're executing $query again! That's why you're always printing the same id.

Categories