I am trying to execute a script to update a database:
my $sql_hash_update = 'UPDATE user SET hash = $hash , updated = 1 WHERE id = $row[0]';
my $sth_hash_update = $dbh->prepare($sql_hash_update);
$sth_hash_update->execute();
I get the error that this is not proper syntax, but this works within SQL itself.
DBD::mysql::st execute 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 '[0]' at line 1 at conexion.pl line 32.
Any ideas what am I doing wrong?
You are using single quotes, so this statement
my $sql_hash_update = 'UPDATE user SET hash = $hash , updated = 1 WHERE id = $row[0]'
will not interpolate the values of $hash and $row[0] into the SQL statement. Instead they will be left as they are, and so the statement isn't valid SQL
You could simply switch to double quotes, which do interpolate, but it is best to use placeholders like this
my $sql_hash_update = 'UPDATE user SET hash = ?, updated = ? WHERE id = ?';
my $sth_hash_update = $dbh->prepare($sql_hash_update);
$sth_hash_update->execute( $hash, 1, $row[0] );
That way you avoid the risk of code injection, and you need to prepare only once for many different execute calls
Placeholders are valid wherever an expression is allowed in the SQL syntax. That means, for instance, you cannot provide a placeholder for a table name, because you couldn't put an expression there in an ordinary SQL statement
Perl does not interpolate single quotes so $row[0] is not being expanded.
You want double quotes.
However, you should also pass $row[0] as a bind parameter.
Something like:
my $sql_hash_update = 'UPDATE user SET hash = ? , updated = 1 WHERE id = ?';
my $sth_hash_update = $dbh->prepare($sql_hash_update);
$sth_hash_update->execute($hash, $row[0]);
Use double quotes instead of single quote
my $sql_hash_update = "UPDATE user SET hash = $hash , updated = 1 WHERE id = $row[0]";
Related
$fnavn = $_POST['fnavn'];
$enavn = $_POST['enavn'];
$adresse = $_POST['adresse'];
$adressenr = $_POST['adressenummer'];
$postnr = $_POST['postnummer'];
$kontonr = $_POST['kontonummer'];
$cvc = $_POST['cvc'];
$fid = $_POST['frakt'];
$gid = $_SESSION['gid'];
$aid = $_SESSION['aid'];
$sql = "INSERT INTO `bestillinger` (`bestilling_id`, `adresse`, `adressenummer`, `postnummer`, `fornavn`, `etternavn`, `kontonummer`, `cvc`, `time`, `fid`, `gid`, `aid`)
VALUES (NULL, '$adresse', '$adressenr', '$postnr', '$fnavn', '$enavn', '$kontonr', '$cvc', now(), '$fid', '$gid', '$aid')";
this is my code, for some reason no data is inserted into my database - and i just cant figure out why.
both sessions have a valid value.
After a form is filled out, my database is supposed to put the info into the database. what is the error?
You are escaping single quotes inside a double quoted string, so that will actually print the \ character as part of the SQL, rendering your SQL invalid.
You need to replace the \' with just ', or wrap the whole query using ' instead of "
I have this query:
$sql = "
INSERT INTO table SET
name = '$name',
sku = '$number',
description = '$desc'
";
But the rows containing some special characters (in my case this ') are not inserted.. How I can solve?
Thanks in advance.
When you construct your query, you need to escape the data you are inserting.
You need to at least use addslashes() function in PHP, like this:
$sql = "INSERT INTO table SET name = '".addslashes($name)."', sku = '".addslashes($number)."', description = '".addslashes($desc)."'";
However more correct way is to use a different function than addslashes, which would properly handle all characters in the data, not only apostrophes.
I am using my custom 'escape' function like this:
function escape($text)
{
return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $text);
}
So using this function, you would write:
$sql = "INSERT INTO table SET name = '".escape($name)."', sku = '".escape($number)."', description = '".escape($desc)."'";
You must use parameterised queries instead of manually appending those values. Currently if name, number or description would contain any sql it would get executed.
A lot more detailed answer is in How can I prevent SQL injection in PHP?
Read about escaping characters in mysql. I think it is done with \
I am trying to query some tables in my database using a simple dropdown in which the name of the tables are listed. the query has only one record result showing the name and age of the youngest institute registered in the database!
$table = $_GET['table'];
$query = "select max('$table'.est_year) as 'establish_year' from '$table' ";
I need to send the name of the table as variable to the querier php file. no matter the method is GET or POST in both ways when I put the variable name in the query statement, it gives the 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 '.order) as 'last' from 'customers'' "
You are wrapping the table name in single quotes, which is not valid SQL (that's the syntax for strings, not table names). You should either not wrap the name at all or else wrap it in backticks (on the american keyboard layout, that's the key above TAB).
You should also not quote the alias established_year:
select max(`$table`.est_year) as establish_year from `$table`
Also, your code is vulnerable to SQL injection. Fix this immediately!
Update (sql injection defense):
In this case the most appropriate action would likely be to validate the table name against a whitelist:
if (!in_array($table, array('allowed_table_1', '...'))) {
die("Invalid table name");
}
single quote ('), in mysql, it represents string value.
SELECT *, 'table' FROM `table`;
Demo
So your query should be
$table = $_GET['table'];
$query = "select max($table.est_year) as 'establish_year' from $table ";
Also read old post, phpmyadmin sql apostrophe not working.
Also your code is vulnerable to SQL Injection. You can use something like this
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
$firstName = clean($_POST['firstName']);
$lastName = clean($_POST['lastName']);
.
.
.
I am currently attempting to update a specific record in my database however although I have checked the syntax thoroughly chrome is telling me that I have it wrong somewhere.
Any advise would be greatly appreciated
$title = $_POST["title"];
$alttext = $_POST["alttext"];
$description = $_POST["description"];
$price = $_POST["price"];
$id = $_POST["ID"];
$insertQuery = "UPDATE cmsproducts SET Title = '$title', Alt_Text = '$alttext', Source = '$target_path', Description = '$description', Price = $price WHERE ID = $id";
// Save the form data into the database
if ($result = $connector->query($insertQuery)){
// It worked, give confirmation
echo '<center><b><span style="color: #FF0000;">Product added to the database</span></b></center><br /><br />';
}else{
// It hasn't worked so stop. Better error handling code would be good here!
echo('<center>Sorry, there was an error saving to the database</center>');
echo "<center><b>File Name:</b> ".$target_path."<br/>";
die(mysql_error());
}
I have tried the query without the variables to check if it was a problem there but it still screamed error at me:
Sorry, there was an error saving to the 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 'of test, Source=../images/Pictures/, Description=This is a test image of test ' at line 1
Always escape user input (mysql_real_escape_string) or use PDO and assign parameters. It seems that $alttext variable has quote or other special character in it. For example,
$title = mysql_real_escape_string($_POST["title"]);
$alttext = mysql_real_escape_string($_POST["alttext"]);
$description = mysql_real_escape_string($_POST["description"]);
$price = mysql_real_escape_string($_POST["price"]);
$id = mysql_real_escape_string($_POST["ID"]);
$insertQuery = "UPDATE cmsproducts SET Title = '$title',
Alt_Text = '$alttext', Source = '$target_path',
Description = '$description', Price = '$price' WHERE ID = '$id'";
It seems you're not escaping quotes as your column Description must have a single quote inside. Use mysql_real_escape_string to escape quotes.
I'm new to CodeIgniter and I get an error I cannot understand.
This is the code that give the error:
$data = array('adr' => $address);
$this->db->where('id', $id);
$this->db->update('domains', $data);
The 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 '://www.example.com WHERE id = '10'' at line 1
This is the query:
UPDATE `domains` SET `adr` = http://www.example.com WHERE `id` = '10'
If I change this to
UPDATE `domains` SET `adr` = 'http://www.example.com' WHERE `id` = '10'
it works. Why is CodeIgniter creating this erroneous query?
Try escaping the single quotes in the $address variable before you call the update method.
Generally the CodeIgniter will automatically surround the value of $address with a single quote. I do not know why did you get this error message?
Curious, see if it works when you escape the string use $this->db->escape()
$data = array('adr' => $this->db->escape($address));
$this->db->where('id', $id);
$this->db->update('domains', $data);
I have the same problem and codeigniter do not add single qoutes to where clause.
When you enter integer value, sql do not give error but when you put string value (as a variable) to where clause, it gives error. But when you add single quotes to query and run it on phpmyadmin, it works.
So the solution is adding (string) statement to your variable: as in this (string)$id
I wrote before to add single quotes to variable as '$id', but this will not going to work (I'm new to codeigniter&php, thanks to commenter Mitchell McKenna, I checked out what I wrote before)