Syntax error in mysql when inserting an image into a database - php

I am new to mysql and I would really appreciate any help. What I want to do is to upload an image to a specific row in a database and then display the image in the user's page. The error I get is:
Error in Query:
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 id = 1' at line 4.
This is the piece of code referenced:
$sql = "INSERT INTO users5 (image, imageName)
VALUES ('{$imgData}', '{$_FILES['userfile']['name']}')WHERE id = $id;";

What I want to do is to upload an image to a specific row in a database
You have to use an UPDATE command if a row is already existing.
$sql = "UPDATE users5 SET image = ?, imageName = ? WHERE id = ?";
$stmt = $mysqli->prepare( $sql );
$stmt->bind_param( 'ssi', $imgData, $_FILES['userfile']['name'], $id );
As suggested, you better use prepared statement to bind parameter values for placeholders safely, avoiding SQL injection.

Related

Update query not working in PHP and Mysql

I have made an update page which fetches record from a table, shows all the details on html form where user can change/Edit the values and submit. Next page fetches those values using $_POST and Update the table.
$new_id = $_POST['c_id'];
$new_name = $_POST['c_name'];
$table_name = "tcompany";
$sqlStatement = "UPDATE $table_name SET 'name'=$new_name WHERE 'id'= $new_id";
if($result_1 = mysql_query($sqlStatement))
{
header('Location: edit_company.php');
}
else {
echo "". mysql_error();
}
I am getting 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 ''name'=HARDWARE Exporters WHERE 'id'= 69' at line 1
I am not considering security issues related to injection. Using this code for personal use.
Don't use apostrophe (') for column names and use it instead to your variables.
$sqlStatement = "UPDATE ".$table_name." SET name='$new_name' WHERE id='$new_id'";
You should also sanitize the values you are binding to your query. Use *_real_escape_string.
$new_id = mysql_real_escape_string($_POST["c_id"]);
And mysql_* API is already deprecated and you should consider using mysqli prepared statement instead.
If you want an example of prepared statement, using the code you have given, you can refer below. No need to sanitize each values before using them to your query.
/* ESTABLISH FIRST YOUR CONNECTION */
$con = new mysqli("YourHost","Username","Password","Database"); /* REPLACE NECESSARY DATA */
if($stmt = $con->prepare("UPDATE ? SET name = ? WHERE id = ?")){ /* CHECK IF STATEMENT IS TRUE */
$stmt->bind_param("ssi",$table_name,$_POST["c_name"],$_POST["c_id"]); /* BIND VALUES TO YOUR QUERY */
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->close();
} /* END OF PREPARED STATEMENT */
The problem is that variable $new_name contains spaces. So you should quote the use of variables in the statement, like this:
$sqlStatement = "UPDATE $table_name SET 'name'='$new_name' WHERE 'id'= '$new_id'";

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

MYSQL Query error WHERE id = $id

I'm creating and then editing a row in a table, however my edit mysql query in php is giving me an error that I can't figure out. Any help?
The creation query:
$query = "INSERT INTO timelines (
id, event_name, event_date, date_created, attendee_count, attendee_names, maximum_attendees, creator_id, creator_name, price, thumbnail
) VALUES (
'{$timelineID}', '{$event_name}', '{$event_date}', '{$date_created}', '{$attendee_count}', '{$attendee_names}', '{$maximum_attendees}', '{$creator_id}', '{$creator_name}', '{$price}', '{$thumbnail}'
)";
The edit query:
$query = "UPDATE timelines SET
event_name = '{$event_name}',
event_date = '{$event_date}',
maximum_attendees = '{$maximum_attendees}',
price = '{$price}',
thumbnail = '{$thumbnail}',
WHERE id = {$timelineID}";
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 'WHERE id =' at line 8
you have an extra comma before the WHERE clause. just remove it and it will work fine.
thumbnail = '{$thumbnail}',
^ here
WHERE ...
final query,
$query = "UPDATE timelines SET
event_name = '{$event_name}',
event_date = '{$event_date}',
maximum_attendees = '{$maximum_attendees}',
price = '{$price}',
thumbnail = '{$thumbnail}'
WHERE id = {$timelineID}";
Your query is vulnerable with SQL INJECTION, please read the article below to learn how to protect from it.
How can I prevent SQL injection in PHP?

mysql error but works fine on mysql workbench

MySQL Query works fine using MySQL workbench but produces an error when I am executing it through PHP.
$sql = "INSERT INTO authors (submission_id, first_name, last_name, email, affiliation, country)
VALUES ('83', 'Chris', 'Hobbit', 'asfasf#gmail.com','Maryland', 'PK');
UPDATE articles
SET title='83',
abstract = 'Comp'
where article_id = '83';
";
$result = Model::getConnection()->query($sql) or die(mysqli_error(Model::getConnection()));
This is the error I get from PHP.
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 'UPDATE articles SET title='83', abstract = 'Comp' where
article_id = '8' at line 1
Yet this same SQL script works fine on MySQL workbench. Whats the problem?
You cannot execute multiple queries with mysql_query. Split your query into two (and get rid of the semicolons I think) and call mysql_query twice
Put your sql statement on two variables
$query = "INSERT INTO authors (submission_id, first_name, last_name, email, affiliation, country)
VALUES ('83', 'Chris', 'Hobbit', 'asfasf#gmail.com','Maryland', 'PK')";
$query1 = "UPDATE articles SET title='83', abstract = 'Comp' where article_id = '83'";
Then execute your queries:
$result = Model::getConnection()->query($query) or die(mysqli_error(Model::getConnection()));
$result = Model::getConnection()->query($query1) or die(mysqli_error(Model::getConnection()));

Error Uploading JPEG to MySQL

I am getting the error below when trying to upload an JPEG image to my MySQL database (Image is a BLOB):
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 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 id=57 (Image) VALUES ('ÿØÿà\0JFIF\0\0\0\0\0\0ÿá\0XExif\0\0MM\0*\0\0\' at line 1
I would really appreciate if you could tell me the problem in my code.
$sql = sprintf(
"INSERT INTO recipies WHERE id=$id (Image) VALUES ('%s')", mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"])));
$results = mysql_query($sql) or die(mysql_error());
Its insert into or update where.
You might want this:
$sql = sprintf(
"UPDATE recipies SET Image = '%s' WHERE id=$id", mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"])));
$results = mysql_query($sql) or die(mysql_error());
Maybe like this would be more correct syntax
$sql = sprintf(
"INSERT INTO recipies (Image) VALUES ('%s') ", mysql_real_escape_string(file_get_contents($_FILES["image"]["tmp_name"])));
$results = mysql_query($sql) or die(mysql_error());
EDIT
It seems you're confused with SQL UPDATE syntax and MySQL particular mess. So correct syntax would be
INSERT
[INTO] tbl_name [(col_name,...)]
{VALUES | VALUE} ({expr | DEFAULT},...),(...),...
Or:
INSERT
[INTO] tbl_name
SET col_name={expr | DEFAULT}, ...
So you friend is the MySQL::INSERT Syntax Manual.
Happy Querying!
Looks more like you are trying to update rather than insert
UPDATE recipes SET Image= ('%s') WHERE id = %d

Categories