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.
Related
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);
I'm currently developing a simple php/mysql website as an assignment.
I need to update a char column in a table by passing a php variable. Issue is I don't know how to pass the variable as a string.
$verify = $_POST['verification'];
"UPDATE Users SET account_status=1 WHERE verification_code= . $verify . ";
Above query is not working for me. Running the query manually on mysql does work;
UPDATE Users SET account_status=1 WHERE verification_code="XYz12"
so I think the problem is passing the variable as a string. I tried a couple of different things but couldn't manage it...
the field verification_code is a string, this must be between simple quote like:
$query = "UPDATE Users SET account_status=1 WHERE verification_code='$verify'";
"UPDATE Users SET account_status=1 WHERE verification_code='" . $verify . "'";
But of course this is very poor form. You need to ensure your variable has been properly escaped. I recommend using PDO prepared statements:
$stmt = $db->prepare("UPDATE Users SET account_status=1 WHERE verification_code=?");
$stmt->execute(array($verify));
The correct string for the query is as follows:
$query = "UPDATE Users SET account_status=1 WHERE verification_code=\"" . $verify . "\"";
With the \ char you scape the quotes char. Anyways this can be quite confusing so you can use simple quotes.
$query = "UPDATE Users SET account_status=1 WHERE verification_code='$verify'";
Note that you can make a reference to a php variable within quotes like above.
BTW. Your error is that you are using the concatenation characters inside a string. It should be used like my first example. Anyways you need to quote the value of the SQL if it is a string. You don't have to do it if the field is NOT a string.
If you are worried about SQL-Injection you can use Prepared Statements instead of plain queries. I recommend to you the PDO Class of PHP. You can give a try to MySQLi too.
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 website.
mysql_query("UPDATE Scholarships2 SET Requirements2 = '$requirements2'
WHERE scholarshipID = '$sID'")
or die("Insert Error1: ".mysql_error());
I read other Stackoverflow questions/answers on this subject but cannot find the reserved word I am using.
$sID is just an int while, $requirements2 is
$regex = '/<h4>Requirements<\/h4>([\n\n\n]|.)*?<\/table>/';
preg_match_all($regex,$data,$match);
$requirements2 = $match[0][0];
for the right syntax to use near 's website
This means it's complaining about the bit of your query that is 's website. "Where is that bit in your query?", I hear you ask.
Well, one of those variables in there contains something like Bob's website and the fact that you're blindly injecting that into your query will give you something like:
UPDATE Scholarships2 SET Requirements2 = 'Bob's website' ...
This particular query will not go down well with the SQL parser :-)
Other possibilities that don't immediately choke the parser will also not go down well with your customer base when little Bobby Tables steals or deletes your credit card database.
See this link for a fuller explanation and strategies for avoidance. In your case, that's probably going to involve mysql-real-escape-string.
In other words, you'll need something like:
mysql_query(
"UPDATE Scholarships2 SET Requirements2 = '" .
mysql_real_escape_string($requirements2) .
"' WHERE scholarshipID = '" .
mysql_real_escape_string($sID) .
"'"
) or die("Insert Error1: ".mysql_error());
As an aside, if $sID is just an integer (and not subject to injection attacks), you could probably remove the quotes from around it. I don't think it matters with MySQL (due to its "everything is a string" nature) but your query won't be portable to other DBMS'.
It depends on the values you have in your variables
Depending on the data type here is what you can do
$requirements2 = mysql_real_escape_string($requirements2); // escape string
$sID = (int)$sID; // force integer
the problem is if you have a string in your $requirement and it contains a single quote ' it will break your sql statement.
Here is something i often do to organize my code.
$sql = "UPDATE Scholarships2 SET Requirements2 = '%s'
WHERE scholarshipID =%d";
$sql = sprintf($sql,
mysql_real_escape_string($requirements2),
(int)$sID
);
Are you just taking form fields in from a POST or AJAX query? It sounds like you have a string containing 's website.
Make sure you run your code though mysqli_escape_string.
You need to escape whatever input you are getting in $requirements2
You can do this by
$req2=mysql_real_escape_string($requirements2);
mysql_query("UPDATE Scholarships2 SET Requirements2 = '$req2'
WHERE scholarshipID = '$sID'")
or die("Insert Error1: ".mysql_error());
This will escape any special characters like the apostrophe found in $requirements2
The problem is that your $requirements2 variable contains a single quote (the error message shows it when it says near 's website - presumably you're inserting something like welcome to Sal's website). When MySQL encounters this character, it's interpreting it as the termination of the entire string.
For example, if you substituted the phrase Welcome to Sal's website into your query where $requirements2 currently is, your query would look like this:
UPDATE Scholarships2 SET Requirements2 = 'Welcome to Sal's website'
As you can see, this results in a quoted string Welcome to Sal with the rest of the string hanging off the end not a part of anything. That's the part that the error is complaining about.
You really need to switch to PDO and prepared statements, otherwise you're leaving yourself wide open to these types of errors, including SQL injection which is a Very Bad Thing.
Prepared statements allow you to specify queries with placeholders where dynamic data can be placed. This extra data is then passed to PDO in a separate function where PDO/the database can determine the best way to sanitize it so that it doesn't get misinterpreted as part of the query structure itself.
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
$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.