This is probably a very trivial question but I've been struggling with it for a while and also tried finding answers online and still getting errors.
Trying to write a simple UPDATE query for a PHP/MySql form:
$sql="UPDATE mytable SET numericValue = '".$someid."', description = '".$sometext."' WHERE id='".$myid."' ";
Whilst all numeric values are being passed and updated fine, I can't get the description right. The description column is a VARCHAR and $sometext is a string and I cant get it escaped / wrapped with quotes correctly.
You should make use of sprintf, it avoids string confusion by providing placeholders (%d for decimals, %s for strings). See the manual for more.
$sql= sprintf("UPDATE mytable SET numericValue = %d, description = '%s' WHERE id = %d", $someid, $sometext, $myid);
If $someText is coming from GET/POST/.. you should wrap a mysql_real_escape_string() around it to prevent SQL injection (or use PDO prepared statements).
$sql="UPDATE mytable SET numericValue = '$someid' , description = '$sometext' WHERE id='$myid' ";
I think you have to worry about sql injection.
Related
The following code is returning no results where I use the variable in the code of $dep if I manually put the value in of 1 it returns the expected result. I have tried it with no quotes single quotes and double quotes. I have looked though loads of examples and I cannot see what I am doing wrong
$dep = 1;
if (!$names) {
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM '.TOPIC_TABLE
. ' WHERE dept_id='$dep' ORDER BY `sort`";
$res = db_query($sql);
I'm pretty sure your error is related to wrong quotes used.
In your code, you write
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM '.TOPIC_TABLE
. ' WHERE dept_id='$dep' ORDER BY `sort`";
After FROM, you are using single-quotes('), but your whole query has been enclosed into double-quotes("), so that creates the issue.
It should be:
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM ".TOPIC_TABLE
. " WHERE dept_id='$dep' ORDER BY `sort`";
EDIT: Forgot to point out you should seriously use PDO or any other SQL Injection prevention methods. If, under any circumstance, your $dep variable could be sent via a public form, you could end up by having your DB dumped in the best case.
There's a syntax error in the second line of the query - if you want single-quotes in the query, then you need to enclose it all in double-quotes:
$sql = "SELECT topic_id, topic_pid, ispublic, isactive, topic, dept_id FROM ' .TOPIC_TABLE
. " WHERE dept_id='$dep' ORDER BY `sort`";
By the way, building a query like this, using string concatenation, is a REALLY BAD IDEA and leaves you open to SQL injection attacks - you should use prepared statements and parameters instead.
First as Fred -ii says make sure the if statement is executing properly. Then if dept_id is an integer value then you should not need the single quotes as scaisEdge says. Otherrwise the SQL looks fine. Make sure that there are in deed records in the database for the dept_id that is being passed in.
I am having this piece of code:
$result = mysqli_query($con , 'SELECT * FROM messages WHERE group = "'.$_POST['group'].'" ORDER BY date '.$_POST['order'].'');
I don't understand why it is always returning me false. The variables $_POST['group'] and $_POST['order'] aren't empty .
$_POST['group']='PHP'
$_POST['order']='DESC'
The conecction to the database is corect too.
GROUP is a mysql reserved word and needs to be quoted using backticks;
SELECT * FROM messages WHERE `group` = ...
You're also wide open to SQL injection, you should never add un-validated/un-escaped POST data in string format to your SQL. The safest way to do queries with user data is using prepared statements, or - as a less secure alternative - escape the data using mysqli_real_escape_string.
$result = mysqli_query($con , "SELECT * FROM messages WHERE group = '".mysqli_real_escape_string($_POST['group'])."' ORDER BY date '".mysqli_real_escape_string($_POST['order'])."'";
Try formatting the query like this and see if it helps your result. I also added mysqli_real_escape_string() to escape your input, as your query was wide open to SQL injection.
http://php.net/manual/en/mysqli.real-escape-string.php
So I have been using prepared statements for a while and for a number of projects and it has been a really good clean way to interact with the MySQL db, but today I have come across a strange problems.
My prepared statement has started adding extra ' to the sql statements and for the life of me I have no idea why...
so here is the code:
<?php
$sortby="ORDER BY submit_date DESC";
$offset = 3;
$sql = "SELECT img_id, img_name, submit_date FROM tbl_images WHERE img_active='y' :sortby LIMIT :offset, 9";
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":sortby", $sortby, PDO::PARAM_STR);
$stmt->bindParam(":offset", $offset, PDO::PARAM_INT);
$stmt->execute();
?>
so the above doesnt return anything, so looking at the database logs, this is what the query looks like
SELECT img_id, img_name, submit_date FROM tbl_images WHERE img_active='y' 'ORDER BY submit_date DESC' LIMIT 3, 9
it seems to have put an extra set of ' ' around the "ORDER BY submit_date DESC", but yet hasnt around the offset?
Can anyone spot the problem as its driving me mad :)
Thank you in advance!
Solution, thanks to the guys that posted, you were correct, I split the fields out to parts and works like a charm. Code solution below:
<?php
$sortfield="submit_date";
$sortway="DESC"
$offset = 3;
$sql = "SELECT img_id, img_name, submit_date FROM tbl_images WHERE img_active='y' ORDER BY :sortfield :sortway LIMIT :offset, 9";
$stmt = $this->_db->prepare($sql);
$stmt->bindParam(":sortfield", $sortfield, PDO::PARAM_STR);
$stmt->bindParam(":sortway", $sortway, PDO::PARAM_STR);
$stmt->bindParam(":offset", $offset, PDO::PARAM_INT);
$stmt->execute();
?>
Have a look at the documentation for mysqli_stmt::prepare:
The markers are legal only in certain places in SQL statements. For example, they are allowed in the VALUES() list of an INSERT statement (to specify column values for a row), or in a comparison with a column in a WHERE clause to specify a comparison value.
Basically, anything structural to the query is not allowed to be a bound parameter. Only data can be sent in this way.
PDO's prepared statements work in effectively the same way. In your case, however, PDO is a bit stupid, because it's running in "emulate prepares" mode (which is the default, but you should turn it off to get the most from PDO). It basically does all the substitution itself, rather than sending the query and the data to the server separately. It sees that the data is a string and thinks "aha, a string: I need to put quotes around this." You therefore end up with your malformed query.
The solution is not to build up structural parts of your query with bound parameters. Either substitute them in yourself with concatenation, or (and this is better) have alternative query strings for different settings. This is the most secure way: anything involving concatenation is a recipe for insecurity.
Oh, and turn PDO emulate prepares off!
With PDO you shouldn't use prepared statement binding variable substitution outside the WHERE clause or an ON clause. If you do they--any string--will get quoted (as they should). While the $offset integer binding might work, you shouldn't do it. You should just substitute the value with a string (after comparing it to a whitelist array of valid values).
$sql = "SELECT img_id, img_name, submit_date FROM tbl_images WHERE img_active='y' $sortby LIMIT $offset, 9";
You want to string interpolate $sortby, rather than bind it as an escaped and quoted SQL literal.
(But take care not to interpolate untrusted SQL fragments!)
Parameter binding is for the substitution of literal values into queries, by which we usually mean plain numbers or strings. Parameters are not for SQL identifiers (like table or column names) nor for syntactic elements.
PDO is interpreting $sortby as a literal string, which is what you asked it to do:
SELECT ... WHERE image_active='y' 'literal string substituted here' ...
You're certainly generating a syntax error with that query.
Confusing matters somewhat is that MySQL does allow placeholders for arguments to LIMIT clauses. This is quite convenient, but surprising to those familiar with other RDBMSs.
What is wrong with this query?
$query3 = "INSERT INTO Users
('Token','Long','Lat')
VALUES
('".$token."','".$lon1."','".$lat."')";
You have several issues with this.
Column names should be backtick escaped, not quoted (also LONG is a datatype in MySQL hence it's reserved and must be backtick-escaped).
You have SQL injection problems if those arguments aren't escaped.
You should provide us with the result of mysql_error() if it's not working.
Try running this code:
$token = mysql_real_escape_string($token);
$lon1 = mysql_real_escape_string($lon1);
$lat = mysql_real_escape_string($lat);
$query3 = "INSERT INTO `Users` (`Token`, `Long`, `Lat`)
VALUES ('{$token}', '{$lon1}', '{$lat}')";
$result3 = mysql_query($query3) or die("Query Error: " . mysql_error());
If that still doesn't work, give us the error message that's produced.
Long is the mysql reserved word and reserved words needs to be enclosed in backticks
$query3 = "INSERT INTO Users
(`Token`,`Long`,`Lat`)
VALUES
('".$token."','".$lon1."','".$lat."')";
You're using single quotes around your field names. This isn't valid in any SQL variant I know of. Either get rid of them or quote the field names in the correct way for your SQL flavor.
Your code likely has an SQL injection vulnerability, unless you left out the code that escapes $token etc
You shouldn't be putting values into the SQL string like that. This isn't the 1990s - we have parametrized queries now.
The mysql_ functions make it a bit difficult to do queries properly. Switch to either mysqli or PDO.
Im writing a php script that is used to update a database but it is giving errors when i tries to run the query it returns an error along the lines of
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 'id=15"' at line 1
Where it says "To use near" seems to display part of the query after there is a space in the data. Im assuming i need to put single quotes around where the data to the query from the php variables but when i try to put them in (even escaping the quotes) i get parse errors from the script
The SQL Query is
mysql_query("UPDATE Videos SET Title=".$_POST['Title'].", Preacher=".$_POST['Preacher'].", Date=".$_POST['Date'].", Service=".$_POST['Service'].", File=".$_POST['File'].", Description=".$_POST['Description']."WHERE id=".$_GET['vid_id']."\"") or die(mysql_error());
Thank in advance for any help
mysql_real_escape_string() and sql injections have already been mentioned.
But right now your script (painstakingly) has to mix the sql statement with the data/parameters and in the next step the MySQL server has to separate the data from the statement.
Using (server-side) prepared statements both "parts" of your query are sent separately and the sql parser (of your MySQL server) can never get "confused" about where the statement ends and the data begins.
The php-mysql module doesn't know prepared statements but php-mysqli and PDO do.
$pdo = new PDO('mysql:host=localhost;dbname=test', '...', '...');
$pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$stmt = $pdo->prepare('
UPDATE
Videos
SET
Title=:title ,
Preacher=:preacher ,
Date=:date ,
Service=:service ,
File=:file ,
Description=:description
WHERE
id=:id
');
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':preacher', $_POST['preacher']);
$stmt->bindParam(':date', $_POST['date']);
$stmt->bindParam(':service', $_POST['service']);
$stmt->bindParam(':file', $_POST['file']);
$stmt->bindParam(':description', $_POST['description']);
$stmt->bindParam(':id', $_GET['id']); // really _GET?
$stmt->execute();
May seem a lot of bloat if you use $stmt for only one operation. But consider that otherwise you have to call mysql_real_escape_string() for each parameter.
You need to escape the variables properly and surround them by single quotes:
mysql_query("UPDATE
Videos
SET
Title = '".mysql_real_escape_string($_POST['Title'])."',
Preacher = '".mysql_real_escape_string($_POST['Preacher'])."',
Date = '".mysql_real_escape_string($_POST['Date'])."',
Service = '".mysql_real_escape_string($_POST['Service'])."',
File = '".mysql_real_escape_string($_POST['File'])."',
Description = '".mysql_real_escape_string($_POST['Description'])."'
WHERE
id = '".mysql_real_escape_string($_GET['vid_id'])."'")
or die(mysql_error());
Without escaping your variables properly, you are making yourself vulnerable to SQL injection attacks.
EDIT
To simplify the above, you can do a few tricks:
// Apply mysql_escape_string to every item in $_POST
array_map('mysql_real_escape_string', $_POST);
// Get rid of $_POST, $_POST['Title'] becomes $p_Title
extract($_POST, EXTR_PREFIX_ALL, 'p_');
// Use sprintf to build your query
$query = sprintf("UPDATE
Videos
SET
Title = '%s',
Preacher = '%s',
Date = '%s',
Service = '%s',
File = '%s',
Description = '%s'
WHERE
id = '%s'",
$p_Title,
$p_Preacher,
$p_Service,
$p_File,
$p_Description,
mysql_real_escape_string($_GET['vid_id']));
mysql_query($query) or die(mysql_error());
Note that mixing $_POST and $_GET variables is not encouraged. You should supply the update ID through an hidden input field in the form.
As you are using DB API directly (no DB abstraction level) the best solution is to use DB escape function.
Just use mysql_real_escape_string().
<?php
// Your query
$query = sprintf("UPDATE Videos SET Title='%s', preacher='%s', Date='%s', "
."Service='%s', File='%s', Description='%s' WHERE id='%s'",
mysql_real_escape_string($_POST['Title']),
mysql_real_escape_string($_POST['Preacher']),
mysql_real_escape_string($_POST['Date']),
mysql_real_escape_string($_POST['Service']),
mysql_real_escape_string($_POST['File']),
mysql_real_escape_string($_POST['Description']),
mysql_real_escape_string(($_GET['vid_id']));
?>
As a bonus you'll get a really improved security against SQL INJECTION attacs your previous code was prone.
In the case you would simply escape slashes you have, again, to use php/mysql functions addslashes() will do the job in this case.
Why are you putting a \" right at the end, this puts a " on to the end of your SQL but you don't have one at the start?
Try this:
mysql_query("UPDATE Videos SET Title=".$_POST['Title'].", Preacher=".$_POST['Preacher'].", Date=".$_POST['Date'].", Service=".$_POST['Service'].", File=".$_POST['File'].", Description=".$_POST['Description']."WHERE id=".$_GET['vid_id']) or die(mysql_error());
REMOVE \", from:
id=".$_GET['vid_id']."\""