Error in SQL UPDATE query - php

$result = mysql_query("UPDATE categories
SET cd_title='$docuTitle' , cd_link='$linkTitle'
WHERE c_name='$catID'");
What is wrong with this update query?

There is probably something wrong with the data in your variables — but we can't see what they contain.
You should be using parameterized queries, which would deal with any odd characters in your data that might mess up the statement.
See How can I prevent SQL injection in PHP? and When are the most recommended times to use mysql_real_escape_string()

I would change the query to this, to avoid errors if input contains apostrophes:
$result = mysql_query(
"UPDATE categories SET
cd_title='" . mysql_real_escape_string($docuTitle) . "',
cd_link='" . mysql_real_escape_string($linkTitle) . "'
WHERE
c_name='" . mysql_real_escape_string($catID) . "'");

If your data is sanitized, remove the single quotes from around the php variables.

Related

How do i correct this MySql query?

I have a query that I am trying to update a MySQL table with
UPDATE `" . TABLE_PREFIX . "TABLE` SET FIELD = CONCAT(FIELD, " . $MyString . ")
$MyString would contain a useragent like MOZILLA/5.0 (COMPATIBLE; SEMRUSHBOT/1.2~BL; +HTTP://WWW.SEMRUSH.COM/BOT.HTML but I am getting a syntax error? The field is set up as TEXT NULL and default is NULL.
Any help appreciated.
For clarity all I am trying to do is add text to a text field in the database, the text IS exactly like the useragent above!
Kind regards,
Simon
String delimiters in sql are ', I assume that your query in the question is some kind of mix between php and sql. I would suggest that you start by getting the sql correct first, and after that incorporate it into php. Your query probably should look something like:
UPDATE ST_uAgent
SET agent = CONCAT(agent, 'MOZILLA/5.0 (COMPATIBLE; DOTBOT/1.1; HTTP://WWW.OPENSITEEXPLORER.ORG/DOTBOT, HELP#MOZ.COM)');
You need to put ' quotes ' around your string.
"UPDATE `" . TABLE_PREFIX . "TABLE` SET FIELD = CONCAT(FIELD, '". $MyString ."')"
Without this MySQL doesn't know how to interpret the data you are passing it.
That said, what you are attempting here is extremely risky and leaves you wide open to SQL injection.
Consider using parameterisation / prepared statements as provided by mysqli or PDO instead - see here: How can I prevent SQL injection in PHP?
I guess the problem is the delimiter ´.
Eliminate the delimiter:
("UPDATE ". TABLE_PREFIX ." TABLE SET FIELD = CONCAT(FIELD, '". $MyString ."')");
It's just a guess.

How to use concat in an update query

Hi I have the following query:
$sql = "update zzz_users set password = "'".$encrypted."' where username = '".$email."'";
CustomQuery($sql);
And I just cannot get the concat right, could someone please show me how to do it
The correct query is:
$sql = "update zzz_users set password = '" . $encrypted . "' where username = '" . $email . "'";
There's a lot more wrong here than not getting the concatenation right.
First of all, if you're just trying to put variables into a string in PHP, consider using double quotes and putting the variables directly into the string:
$sql = "UPDATE `zzz_users` SET `password` = $encrypted WHERE `username` = $email";
There's no need for all the starting and stopping of strings in that case.
However, what you're doing here is extremely dangerous because of SQL Injection attacks. You should DEFINITELY NOT be putting variables directly into your SQL commands.
The best way to do this is to use a library that knows how to accept formatting strings and create safe SQL for you. For example, something like MeerkoDB will let you write this SQL statement like this:
DB::query("UPDATE `zzz_users` SET `password`=%s WHERE `username`=%s", $encrypted, $email);
This is actually safe, because it will ensure that the SQL is properly escaped, preventing SQL injection attacks. Of course, you can roll your own escaping, but it's almost always a better idea to use a well-established library (there are many free/open source and commercial/proprietary offering out there).
There is an " too much after password =. You should escape the strings before writing it to the database, otherwise you may get a possible SQL injection issue.
$sql = "update zzz_users set password = '" .mysql_real_escape_string($encrypted). "' where username = '" .mysql_real_escape_string($email). "'";
CustomQuery($sql);

How to include php echo within mysql update?

So I am updating my mysql database using php. Below is the end of the UPDATE, and if I have a string instead of echo $row[embedcode]"); it works fine, and this echo sets data on the page just fine retrieving the right value, but within this UPDATE it doesn't work.
...WHERE `embedcode` = echo $row[embedcode]");
I have tried using ". ." around it and adding its own php tag around it but I'm not sure what needs to be done.
Just use this:
...WHERE `embedcode` = " . $row[embedcode]);
There is no need for echo.
As a side note, you should probably parameterize or at least sanitize any strings that go into a MySQL query to prevent SQL injection and other bad things.
" ... WHERE `embedcode=` '" .$row[embedcode]. "';");
WHEREembedcode= . $row[embedcode]); will set the value.
There is not need for echo inside the sql statement. echo is used for displaying something from php to the webbrowser.
You don't use echo, perhaps it should be:
...WHERE `embedcode=` . $row[embedcode]");
Not that if $row[embedcode] is a string you have to put quotes around it.
Let say for example...
("UPDATE `tblProfile` SET `profilename` = 'abc' WHERE `embedcode` = '".$row['embedcode']."'");
to prevent SQL injection, you can pass that value as a parameter if you are using PDO or MySQLi.
For example,
$stmt = $dbConnection->prepare('...WHERE `embedcode` = :embedcode');
$stmt->execute(array(':embedcode' => $row[embedcode]));
See this for details.

SQL-injection - is this (oneliner) safe?

PHP:
$SQL = "SELECT goodies FROM stash WHERE secret='" .
str_replace("'",'',$_POST['secret']) .
"'";
Could an evil genius hacker inject SQL into my SELECT - How ?
Why won't you use mysql_real_escape_string() or even better - prepared statements? Your solution seems silly.
I've had a think about this for a while and I can't see any way to inject SQL into this statement.
An SQL string that starts with a single quotes terminates at the next single quote unless it is escaped with a backslash or another quote (\' or ''). Since you are removing all single quotes there cannot be a doubled quote. If you escape the closing quote you will get an error, but no SQL injection.
However this method has a number of drawbacks:
Single quotes in the input are ignored.
Backslashes in the input aren't handled correctly - they will be treated as escape codes.
You get an error if the last character is a backslash.
If you later extend the query to add a second parameter, it would allow an SQL injection attack.
For example:
$SQL = "SELECT goodies FROM stash WHERE secret='" .
str_replace("'",'',$_POST['secret']) .
"' AND secret2 = '" .
str_replace("'",'',$_POST['secret2']) .
"'";
When called with parameters \ and OR 1 = 1 -- would result in:
SELECT goodies FROM stash WHERE secret='\' AND secret2=' OR 1 = 1 -- '
Which MySQL would see as something like this:
SELECT goodies FROM stash WHERE secret='...' OR 1 = 1
Even if it's impossible to cause an injection in this case the drawbacks make this unsuitable for a general purpose way to avoid SQL injection.
The solution, as already pointed out, is to use a prepared statement. This is the most reliable way to prevent SQL injection attacks.
May be.
The best way is:
$query = sprintf("SELECT goodies FROM stash WHERE secret='%s'",
addcslashes(mysql_real_escape_string($_POST['secret']),'%_'));
Why just don't use mysql_escape_string? And yes, he could, adding " instead of ' and plus, this query will give you an error, I guess.

How should I write PHP $_POST vars in a mysql_query function?

In accessing my database, I have the user fill out a form, and in the target page, the posted values are used in the resulting MySQL query.
$query = mysql_query("SELECT pass FROM database WHERE user='$_POST[user]'");
However, for some reason or another, MySQL doesn't like my using a $_POST variable in the command, and it only works if I define (for example) $user = $_POST['user'];, and then put $user directly in the SQL command.
On the other hand, I can use $_POST values in INSERT statements where specific column names are not required:
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', '$_POST[user]'");
If I try an INSERT statement where attributes are defined (e.g. user='foo'), then the same problem appears.
What am I doing wrong in my SQL query that causes the command to error out when run, but works with the specific method of formatting an INSERT command?
Hopefully, it's not "tough luck, looks like you have to assign all of your posted values". Heh.
First of, watch out for SQL Injections!
Now, to answer your question try doing this instead:
$query = mysql_query("SELECT `pass` FROM `database` WHERE `user` LIKE '" . mysql_escape_string($_POST['user']) . "';");
You were doing a couple of things wrong:
using the = operator instead of LIKE operator
not enclosing the value in the SQL query with '
not enclosing the user index in the $_POST array with '
PS: You should use mysql_real_escape_string() instead of mysql_escape_string()!
You're simply inserting a variable into a string, so it shouldn't matter which command you're putting it into.
There are a few issues to point out.
One, you might want to use the {} format for array variables. You don't use quotes around the arrray key names in this format.
$query = mysql_query("SELECT pass FROM database WHERE user='{$_POST[user]}'")
Two, you'd never want to make a query like that because you are open to sql injection holes. Consider, what if $_POST['user'] was "cow';drop table database;--"?
You must either run mysql_real_escape_string on the POST input before putting it into your query, or check out using PHP PDO with prepared statements.
One way to do format your string which provides a bit of structure is to use sprintf.
$query=mysql_query(sprintf("SELECT pass FROM database WHERE user='%s'",mysql_real_escape_string($_POST['user'])));
Use PDO - it provides much better API to communicate with DB.
If you're using mysql_*() functions always remember to filter (mysql_real_escape_string()) any data that comes from untrusted source (like user)
Pay more attention to how your code looks like. Just compare the following listings:
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ", " . mysql_real_escape_string($_POST['user']) . ")");
$query = sprinf('INSERT INTO database VALUES ("foo", "bar", "%s", "%s", "%s")',
mysql_real_escape(...), ...);
Do I have to explain which one is better to read, modify or understand?
Why not check and see what mysql_error() has to say about it? If your query is invalid, mysql_error() will return a nice blob of text telling you exactly what went wrong.
As for MySQL not liking the POST var if you insert it directly for some runs, but not others, then you should make sure you're using consistent data and setups for each test. If some test are done using a GET, then your POST vars will be empty. If you're using different user names for each test, then see if what's consistent between the ones that fail.
And as mentioned above, read up about SQL injection and how your query is just begging to be subverted by a malicious user.
Try
$query = mysql_query("SELECT pass FROM database WHERE user=" . mysql_real_escape_string($_POST['user']));
and
$query = mysql_query("INSERT INTO database VALUES ('foo', 'bar', " . mysql_real_escape_string($_POST['user']) . ")");
Its always a good idea to sanitize anything received through $_GET or $_POST

Categories