I have a table with 4 record.
Records: 1) arup Sarma
2) Mitali Sarma
3) Nisha
4) haren Sarma
And I used the below SQL statement to get records from a search box.
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%$q' LIMIT 5";
But this retrieve all records from the table. Even if I type a non-existence word (eg.: hgasd or anything), it shows all the 4 record above. Where is the problem ? plz any advice..
This is my full code:
$q = ucwords(addslashes($_POST['q']));
$sql = "SELECT id,name FROM ".user_table." WHERE name LIKE '%".$q."' LIMIT 5";
$rsd = mysql_query($sql);
Your query is fine. Your problem is that $q does not have any value or you are appending the value incorrectly to your query, so you are effectively doing:
"SELECT id,name FROM ".user_table." WHERE name LIKE '%' LIMIT 5";
Use the following code to
A - Prevent SQL-injection
B - Prevent like with an empty $q
//$q = ucwords(addslashes($_POST['q']));
//Addslashes does not work to prevent SQL-injection!
$q = mysql_real_escape_string($_POST['q']);
if (isset($q)) {
$sql = "SELECT id,name FROM user_table WHERE name LIKE '%$q'
ORDER BY id DESC
LIMIT 5 OFFSET 0";
$result = mysql_query($sql);
while ($row = mysql_fetch_row($result)) {
echo "id: ".htmlentities($row['id']);
echo "name: ".htmlentities($row['name']);
}
} else { //$q is empty, handle the error }
A few comments on the code.
If you are not using PDO, but mysql instead, only mysql_real_escape_string will protect you from SQL-injection, nothing else will.
Always surround any $vars you inject into the code with single ' quotes. If you don't the escaping will not work and syntax error will hit you.
You can test an var with isset to see if it's filled.
Why are you concatenating the tablename? Just put the name of the table in the string as usual.
If you only select a few rows, you really need an order by clause so the outcome will not be random, here I've order the newest id, assuming id is an auto_increment field, newer id's will represent newer users.
If you echo data from the database, you need to escape that using htmlentities to prevent XSS security holes.
In mysql, like operator use '$' regex to represent end of any string.. and '%' is for beginning.. so any string will fall under this regex, that's why it returms all records.
Please refer to http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html once. Hope, this will help you.
Related
After years of reading it's time to ask first question :)
My problem is that after migrating the code from mySQLi to PDO we have got a problem as it seems PDO adds the apostrophes to the query.
PHP code goes like that:
$sort = $_GET['sort']; << table column name (mySQL VARCHAR only columns)
....
$query = 'SELECT * FROM table WHERE xxx > 0';
$query .= ' ORDER BY :sort ASC ;';
$qry_result= $db->prepare($query);
$qry_result->execute(array(':sort'=>$sort));
mysqli version went smoothly but now queries (mysql log file) looks like this:
SELECT * FROM table where xxx > 0 ORDER BY 'SORT_VAR_VALUE' ASC;
^ 2 problems ^
So the table is NOT sorted, as sort order (from mySQL point of view) is wrong.
phpinfo() does not get any results for search on "magic" nor "quotes" btw.
Any idea ??
The placeholders in PDO statements are for values only. If you want to add actual SQL to the query you need to do it another way.
First, you should sanitize $sort and surround it with backticks in the query.
$sort = preg_replace('/^[a-zA-Z0-9_]/', '', $sort);
Then you could double quote the query string and PHP will replace $sort with it's value for you:
$query = "SELECT * FROM table WHERE xxx > 0 ORDER BY `$sort` ASC";
Or you could replace it with preg_replace like so:
$query = 'SELECT * FROM table WHERE xxx > 0 ORDER BY `:sort` ASC';
$query = preg_replace('/:sort/', $sort, $query, 1);
I would use the preg_replace method because it allows you to reuse the query if you assign the results from preg_replace to another variable instead of overwriting the original variable.
by default pdo binds values as strings.
To fix this you will want to check that the column is actually a valid name and then add it to the query, you can do it the following way:
function validName($string){
return !preg_match("/[^a-zA-Z0-9\$_\.]/i", $string);
}
if(validName($sort)){
$db->prepare("SELECT * FROM table where xxx > 0 ORDER BY $sort ASC");
}
With PDO it's not possible to bind other things that variables in the WHERE statement. So you have to hard code the names of the columns you order by.
See How do I set ORDER BY params using prepared PDO statement?
or Can PHP PDO Statements accept the table or column name as parameter? for further explanations.
I am trying to do a query in PHP PDO where it will grab a simple result. So like in my query I need it to find the row where the column group is 'Admin' and show what ever is in the group column. I know that we already know what it should be [Should be admin] but just need to get the query to work. Its only grabbing 1 row from my table, so will I need forsearch?
If I change WHERE group = 'Admin' to WHERE id = '1' it works fine. But I need it so it can be where group = 'admin'
$sql2 = "SELECT * FROM groups WHERE group = 'Admin'";
$stm2 = $dbh->prepare($sql2);
$stm2->execute();
$users2 = $stm2->fetchAll();
foreach ($users2 as $row2) {
print ' '. $row2["group"] .' ';
}
Thanks
group is a reserved word in MySQL, that's why it's not working. In general it's a bad idea to use reserved words for your column and table names.
Try using backticks around group in your query to get around this, so:
$sql2 = "SELECT * FROM groups WHERE `group` = 'Admin'";
Also you should really use placeholders for values, because you're already using prepared statement it's a small change.
Edit: just to clarify my last remark about the placeholders. I mean something like this:
$sql2 = "SELECT * FROM groups WHERE `group` = ?";
$stm2->execute(array('Admin'));
try to use wildcard in your WHERE Clause:
$sql2 = "SELECT * FROM groups WHERE group LIKE '%Admin%'";
Since the value in your table is not really Admin but Administrator then using LIKE and wildcard would search the records which contains admin.
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 8 years ago.
I looked mostly everywhere on Stackoverflow for adding multiple WHERE instances but none of them seem to work.
My Select query:
$result = mysql_query("SELECT * FROM $tableName WHERE user = $user AND column = 1"); //query
I tried IN and some other ways but I dont know why it wont get the column. If I take out the user column it works, but I want it to also restrict to the column as well..
Any help will be appreciated!
column is reserved word in mysql. You have to use ` around that kind of column_name and use ' single quotes around string data '$user'
SELECT * FROM $tableName WHERE user = '$user' AND `column` = 1
You need to wrap the username in single-quotes & as mentioned by Yogesh column is a reserved keyword in MySQL. Try this:
user = '$user' AND `column` = 1
So the whole statement becomes:
$result = mysql_query("SELECT * FROM $tableName WHERE user = '$user' AND `column` = 1");
Also, you should be using mysqli or PDO with prepared statements instead.
Rewrite your query. Use the below code:
$result = mysql_query("SELECT * FROM `".$tableName."` WHERE user = '".$user."' AND `column` = 1");
And here I am missing that what is column in query is it name of column?
And you need to give the value in single quota and table name in ` till mark.
try this one:
$sql = 'SELECT * FROM $tableName WHERE user = "'.$user.'" AND `column` = 1';
I'm having trouble using variables in my SQL WHERE clause. I'm getting this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL
result resource
The code is:
$sql3= mysql_query("SELECT COUNT($ww) FROM data WHERE $".$ww." = ".$weeknumber." ");
What am I doing wrong?
Why don't you count the table column by putting the columns name in your COUNT(column_name)?
Like so:
$sql3= mysql_query("SELECT COUNT(week_num) as wknum FROM data WHERE '$ww' = '$weeknumber'");
$counted_weeks["week_num"]
// $counted_weeks["week_num"] will output your sum
//week_num would be a column name from your "data" table
I recommend looking at this link. As #Crontab mentioned I am not sure why you have a dollar sign in front of your where clause.
A couple other things to point out:
As it says in the link, you will need to make sure the query text is properly escaped. Also, If I'm not mistaken (not familiar with PHP) do you need to explicitly concatenate the text instead of just using quotes? (i.e. instead of "SELECT ... " ... " do you need to do "SELECT ... " + " ... ")
php string formatting is perfect here, take your messy confusing concat string and make it clean and readable!
$sql3= mysql_query(sprintf("SELECT COUNT(%s) FROM data WHERE %s=%d", $ww, $ww, $weeknumber));
Assuming that $ww is a valid column name and $weekNumber is an integer, this should work:
$query = "SELECT COUNT(*) AS cnt FROM data WHERE $ww = '$weekNumber'";
$rs = mysql_query($query);
$r = mysql_fetch_assoc($rs);
echo "Count: {$r['cnt']}";
I am guessing $ww is referring to a column name. $weekNumber is obviously the value. In that case, your SQL query should look like this:
$sql3= mysql_query("SELECT COUNT(".$ww.") FROM data WHERE ".$ww." = ".$weeknumber." ");
I'm not a PHP guy, but I'm assuming you have the correct PHP syntax.
I created a user defined sql query that doesn't work. Users are supposed to be able to enter search strings in an input field, submit then see the results of their search but everytime I enter a search for something that I know is in the database I get the unknown column "x" in "where clause" error message.
Would you please help me fix the problem? Here's the code that i wrote for it so far...
...
mysql_select_db("mydb", $c);
$search = $_POST['search'];
$rslt = mysql_query("SELECT * FROM mytable
WHERE 'mycolumn' RLIKE $search");
while($row = mysql_fetch_array($rslt))
{
echo $row['myrow'];
echo "<br />";
}
if (!$row)
{
die('uh oh: ' . mysql_error());
}
?>
Change the code to this:
1) Convert quotes to backticks around column name.
2) Surround $search with single qoutes to make it a string.
$rslt = mysql_query("SELECT * FROM mytable WHERE `mycolumn` RLIKE '{$search}'");
This helps for sure
just change the variable $search to be read as a string i.e $search
so it will be like this
$rslt = mysql_query("SELECT * FROM mytable WHERE mycolumn RLIKE '$search'");
I would like to add a few about security and performance.
It is unsafe to put user input (any GET, POST or cookie data) directly into the SQL query. This is a serious security issue called SQL injection. To avoid it, use mysql_real_escape_string() function.
Also, SELECT * FROM mytable ... is not a good practice. It is recommended to explicitly list all the columns needed even if they all are:
SELECT col1, col2, col3, col4, col5 FROM mytable ...