I am new to PDO and I'm trying to build my own CRUDS application. I already created CRD but I'm getting stuck with Updating user information. It seems that I have a problem with my syntax, but I thoroughly checked the documentation and I can't figure out what is wrong with the code. It's passing me this error:
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 'Doe, email=johndoe#gmail.com, location=New York City WHERE id=1' at line 1
Here is my code:
include('database.inc.php');
if (isset($_POST['submit'])) {
$id = $_POST['userId']; // 1
$name = $_POST['employee_name']; // John Doe
$email = $_POST['email']; // johndoe#gmail.com
$location = $_POST['location']; // New York City
try {
$query = "UPDATE users SET employee_name=$name, email=$email, location=$location WHERE id=$id";
$statement = $conn->prepare($query);
$statement->execute();
header('Location: ../index.php');
} catch(PDOException $e) {
echo 'ERROR: ' .$e->getMessage();
}
}
The problem with your code is that you didn't put quotes around the string values in the SQL. But you should use parametrized queries, not substitute variables into the SQL. This solves the quoting problem, and also prevents SQL injection.
$query = "UPDATE users SET employee_name=:name, email=:email, location=:location WHERE id=:id";
$statement = $conn->prepare($query);
$statement->execute(array(':name' => $name,
':email' => $email,
':location' => $location,
':id' => $id));
Try surrounding the variables in the statement with single quotes ( ' )
$query = "UPDATE users SET employee_name='$name', email='$email',
location='$location' WHERE id='$id'";
Related
I'm working with two identical tables from SQL Server and MySQL and my end-goal is to be able to sync their contents through PHP. I made a previous post about this and I found out that the reason my code wasn't working was because of single quotes messing up my SQL Syntax. I then converted my table to use PDO instead because I heard preparing statements/binding param through it is more efficient. However, my code is still not escaping single quotes properly. I've already look into past posts but none of them solved my problem. Here is the code:
<?php
$serverName = "<servername>";
$connectionInfo_mssql = array("Database"=>"<dbname>", "CharacterSet"=>"UTF-8");
try
{
$conn_mssql = new PDO("sqlsrv:Server=$serverName;Database=<dbname>");
$conn_mssql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn_mysql = new PDO("mysql:host=localhost;dbname=<dbname>", "", "");
$conn_mysql->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//SELECT FROM SQL SERVER DB
$mssql_array = array();
$mssql_query = $conn_mssql->prepare("SELECT * FROM Customers");
$mssql_query->execute();
while($row = $mssql_query->fetch(PDO::FETCH_BOTH))
{
$mssql_array[] = array('ID' => $row['ID'],
'Name' => $row["Name"],
'Address' => $row['Address'],
'Email' => $row['Email']);
}
foreach($mssql_array as $key => $value)
{
//SELECT FROM MySQL DB
$mysql_query = $conn_mysql->prepare("SELECT COUNT(*) FROM Customers WHERE ID ='".$value['ID']."'
AND Name = '".$value["Name"]."'
AND Address = '".$value['Address']."'
AND Email = '".$value['Email']."' ");
$mysql_query->execute();
$num_rows = $mysql_query->fetchColumn();
if ($num_rows == 0)
{
//INSERT INTO MySQL DB
$sql = $conn_mysql->prepare("INSERT INTO Customers VALUES (:ID, :Name, :Address, :Email)");
$params = array(':ID' => $value["ID"], ':Name' => $value["Name"], ':Address' => $value["Address"], ':Email' => $value["Email"]);
$sql->execute($params); //this is where the error occurs
}
}
echo 'Table Customers from MS SQL DB and table Customers from MySQL DB are now synced!'."<br>";
echo "<a href='table_updater.php'>Go back to updater</a>";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
What this basically does is it selects all of the SQL Server table's contents and puts it in MySQL, but since one of my rows has the value "Jojo's" it just gives me an error because of the single quote. The error I'm 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 MariaDB server version for the right syntax to use near 's' AND Address = 'IDK''
which pretty much tells me that I'm not escaping the single quote.
Any ideas are much appreciated!
The issue is not with the INSERT statement but with the SELECT one. From the error you can see that it fails to interpret a part of the select query. So the correct code would look like this:
//SELECT FROM MySQL DB
$mysql_query = $conn_mysql->prepare("SELECT COUNT(*) FROM Customers WHERE ID = :ID
AND Name = :Name
AND Address = :Address
AND Email = :Email ");
$params = [':ID' => $value['ID'], ':Name' => $value['Name'], ':Address' => $value['Address'], ':Email' => $value['Email']];
$mysql_query->execute($params);
To further explain, without the placeholders, your select query could look like the following if for example the name had a quote in it:
SELECT COUNT(*) FROM Customers WHERE ID = '123'
AND Name = 'As'd, dfg' # <- Problem here
AND Address = 'some address'
AND Email = 'email#example.com'
For the record, you should always use placeholders for any value that you do not control in code. Even if that's for a SELECT statement or a data source you trust. This prevents unintended injection by accident and handles any type of character.
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");
Subject Update Failed!!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 '' at line 1
I am stuck here can anyone help me what I am missing in this code.The error is in Update Query.
Everything is ok, and I don't get any syntax error when I write the code (I am using a Dreamviwer code editor software. However, when I run it, I get this error:
//Process the form
$id= $current_subject["Id"];
$name=mysql_prep($_POST["Name"]);
$position=(int)$_POST["Position"];
$visible=(int)$_POST["Visible"];
$query="UPDATE subjects SET Name='{$name}',Position=$position,Visible=$visible WHERE Id={$id}";
$result= mysqli_query($conn, $query);
if($result && mysqli_affected_rows($conn)==1){
//success
$_SESSION["message"]="Subject updated.";
redirect_to("manage_content.php");
}else{
//Failure
$message="Subject Update Failed" . $conn->error;
}
Most likely you mistyped the parameter name. Đ•cho your parameters first.
And use prepared statements to prevent SQL injections:
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$query="UPDATE subjects SET Name = ? ,Position = ?,Visible = ? WHERE Id = ?";
$stmt = $dbh->prepare($query);
$stmt->bindParam(1, $name);
$stmt->bindParam(2, $position);
$stmt->bindParam(3, $visible);
$stmt->bindParam(4, $id);
$stmt->execute();
$stmt->fetchAll();
Further reading: PDO.
I am trying to update a simple query and I keep getting the following error 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 ':cat_name, menu_category_description = :cat_desc WHERE id = :id' at line 1
The query I am using looks perfectly valid. I don't know why it keeps showing that error message.
Below is my query I am using.
$query = "UPDATE menu_categories SET menu_category_name = :cat_name, menu_category_description = :cat_desc WHERE id = :id ";
$stmt = $db->query($query);
$stmt->execute([":cat_name" =>$category_name, ":cat_desc" => $category_description, ":id" => $id ]);
You need to first prepare your query: (you're querying instead of preparing)
change this line:
$stmt = $db->query($query);
to:
$stmt = $db->prepare($query);
then change this line
$stmt->execute([":cat_name" =>$category_name, ":cat_desc" => $category_description, ":id" => $id ]);
to (and remove the square brackets)
$stmt->execute(":cat_name" =>$category_name, ":cat_desc" => $category_description, ":id" => $id);
See if this works for you,
$query = "UPDATE menu_categories SET menu_category_name = :cat_name, menu_category_description = :cat_desc WHERE id = :id ";
$stmt = $db->prepare($query);
$stmt->bindParam(':cat_name', $category_name);
$stmt->bindParam(':cat_desc ', $category_description);
$stmt->bindParam(':id', $id);
$stmt->execute();
Also, where are you defining values for your $category_name, $category_description, $id? Make sure they are not empty.
Here's an example of Updating PDO
$pdo = Database::getInstance();
$stmt = $pdo->db->prepare("UPDATE people SET reset='1', active=:acTive WHERE user_id=:id limit 1");
$stmt->bindParam(':acTive', $_POST['active_key']);
$stmt->bindParam(':id', $_POST['id']);
$stmt->execute();
Hope it helps
I just learned I had magic_quotes_gpc on (much to my chagrin). I turned that off.
My database connection is made prior to this query. I have the following:
$subject = mysqli_real_escape_string($link, $_POST["subject"]);
$body = mysqli_real_escape_string($link, $_POST["body"]);
$id = mysqli_real_escape_string($link, $_POST["id"]);
mysqli_query($link, "UPDATE press SET press_title = '$subject', press_release = '$body' WHERE press_id = '$id'") or die( mysqli_error($link) );
With magic quotes on, this works fine. Once I turn it off, single quotes jam up the works (with a MySQL syntax error at the quote). I thought I understood the concept but I must be missing something. Can someone explain what I'm doing wrong?
UPDATE
Error spit out by MySQL:
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 's what she said' at line 1
UPDATE #2
Here's the echo'd query:
UPDATE press SET press_title = \'That\'s what she said\', press_release = \'That\'s what she said again!\' WHERE press_id = \'513\'
Use a parametrized query:
$stmt = mysqli_prepare($link, "UPDATE press SET press_title = ?, press_release = ? WHERE press_id = ?") or die (mysqli_error($link));
mysqli_stmt_bind_param($stmt, "ssi", $_POST['subject'], $_POST['body'], $_POST['id']);
mysqli_stmt_execute($stmt);
Manual