I try to make a search engine for profiles, but I stock with an error that "Division by zero" and and after I used var_dump(mysql_error()) it shows me "Query was Empty".
here is my query and php code:
$search_rs = dbq('SELECT * FROM users WHERE fname LIKE '%$_GET[query]%' LIMIT 0, OR fname LIKE '%$_GET[query]%'');
if($search_rs == false) {
var_dump(mysql_error());
}
elseif (db_num($search_rs) > 0) {
while ($results = db_next($search_rs)) {
echo('<li>
<a class="avatar" href="http://mysite/'.$results['pagekey'].'" target="_blank">
<img src="'.thumbnail($results['avatar'], 64, 64).'" />
</a>
<div class="info">
<a href="http://profiler.ir/'.$results['pagekey'].'" target="_blank">
<span class="fullname">'.$results['pre_name'].' '.$results['fname'].' '.$results['lname'].'</span>
</a>
</div>
</li> ');
}
}
else echo "not found !!!";
BUT When I remove LIKE '%$_GET[query]%'and make a simple query without LIKE , it return results.
Change your query from this:
'SELECT * FROM users WHERE fname LIKE '%$_GET[query]%' LIMIT 0, OR fname LIKE '%$_GET[query]%''
To this:
"SELECT * FROM users WHERE fname LIKE '%" . $_GET['query'] . "%'"
The issues you had were:
Using single quotes for the whole query string as well as the LIKE '%…%' values inside of them. So using double quotes now, concatenating the values.
You also had missing single quotes for your $_GET[query] so those are changed to $_GET['query'].
The placement of LIMIT 0, makes no sense so that is gone.
Also unsure why you had two fname LIKE '%" . $_GET['query'] . "%' in there. Removed the second one.
If you somehow need the LIMIT then this query should work:
"SELECT * FROM users WHERE fname LIKE '%" . $_GET['query'] . "%' LIMIT 0,100"
But I am just presuming you need 100 items, so change that 100 as well as the 0 offset to best match your needs.
The MySQL error is caused by malformed SQL text. The problem in the code is that the desired SQL text isn't being produced, due to the PHP syntax for interpreting/concatenating strings.
I recommend you use double quotes around the literal portions of the string, and use a dot operator to signify concatenation.
I also recommend you do the string manipulation as a separate step, so that the SQL text is available for inspection/debugging.
I also strongly recommend you use the mysql_real_escape_string function to reduce SQL injection vulnerabilities (when including user supplied data within the SQL text).
As an example:
$sql = "SELECT * FROM users WHERE fname LIKE '%" . mysql_real_escape_string($_GET[query]) . "%'";
#vardump($sql); # for inspecting/debugging issues with generating SQL text
$search_rs = dbq($sql);
Little Bobby Tables XKCD Exploits of a Mom
Related
I have a problem with queries that contains ' in names.
Select HTML:
<select id="list-skins" name = "specific_skins_list[]" multiple="multiple" style="width: 500px">
<?php
$get_all_skins_list= mysqli_query($conn, "SELECT * FROM skins_list");
while($row = mysqli_fetch_array($get_all_skins_list)) {
$skins_name = $row["skins_list"];
$skins_id = $row["id"];
$skins_name = str_replace("'", "’", $skins_name);
echo '<option value="'.$skins_name.'">'.$skins_name.'</option>';
}//END WHILE GET_ALL_REGIONS
?>
</select>
POST
if (isset($_POST["specific_skins_list"])) {
$query .= "
AND skins LIKE '%" . implode("%' or skins LIKE '%", $_POST['specific_skins_list']) ."%'
";
}
My problem is: in table skins_list, I have names like:
i'oan , v'asilivev etc...
These names contain a ' .
The query works fine if the names are normal without special characters. I found couple solutions in my search to use mysqli_real_escape_string.
I tried to do something like this:
if (isset($_POST["specific_skins_list"])) {
$skins = mysqli_real_escape_string($conn,$_POST["specific_skins_list"]) ;
$query .= "
AND skins LIKE '%" . implode("%' or skins LIKE '%", $skins) ."%'
";
}
but I get this error:
mysqli_real_escape_string() expects parameter 2 to be string, array given in... my page
And the query is like this :
SELECT *
FROM import_acc
WHERE available = 'YES' AND region = 'UVAS' AND st= 'Truex' AND skins LIKE '%%' "
Thank you for your time.
P.S. I think the only way i can fix this is to modified all table skins_list and add manulaly double '' to every name :D
You defined the fields as "specific_skins_list[]", so it produces an array instead of a string, and that's why you get the error. mysqli_real_escape_string only works on strings.
The simplest way to solve this is to loop on this array, calling mysqli_real_escape_string on each element, e.g:
$skins = [];
foreach($_POST["specific_skins_list"] as $skin)
$skins[] = mysqli_real_escape_string($conn,$skin);
Now your $skins variable contains properly formatted strings for an SQL query (probably).
Of course, in a real script you should do a lot more validation - you should make sure that $_POST["specific_skins_list"] is defined and is indeed an array (using isset and is_array), and that each element is a valid skin name or something (e.g. using preg_match).
Otherwise your script may generate lots of errors or your DB can be hacked if someone uses the script directly, bypassing your UI.
I am in search of a way to use wildcards with the following mysql query.
public function getSetsOnMonth($setsId, $setsDate, $offset, $count)
{
$sql = sprintf("SELECT * FROM " . $this->_prefix . "media_set AS f
INNER JOIN " . $this->_prefix . "media_set_sets_assoc AS fs
ON fs.set_id = f.set_id AND fs.sets_id = '%s'
WHERE f.posted LIKE '%s'
AND f.is_active = 1
ORDER BY f.set_id DESC
LIMIT %s, %s",
mysql_real_escape_string($setsId),
mysql_real_escape_string($setsDate),
mysql_real_escape_string($offset),
mysql_real_escape_string($count));
echo $sql; exit;
$rs = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_object($rs)) {
$rows[] = $row;
}
mysql_free_result($rs);
return new XXX_Model_RecordSet($rows, $this);
}
What i am looking to do is by month so that would be (where f.posted LIKE '%s') is located
I have tried using the % in various ways and it always errors.
For instance (where f.posted LIKE '%s %') returns this error (Warning: sprintf(): Too few arguments in..).
I have also tried to use (where f.posted LIKE '$setsDate%') this does not return a sql error, however it makes my query limit the same as the date and the single quote is removed after the % sign in the sql printout.
oddly if i reverse and put the percent sign in front of $setsDate (%setsDate) is cancels out everything after the % and shows everything.
any help would be appreciated.
UPDATED 9:35 EST 03/10
Here is the sql output ('%s %%'):
SELECT * FROM media_set AS f INNER JOIN media_set_sets_assoc AS fs ON fs.set_id = f.set_id AND fs.sets_id = '1' WHERE f.posted LIKE '201312 %' AND f.is_active = 1 ORDER BY f.set_id DESC LIMIT 0, 18
Here is SQL output ('%s%%'):
WHERE f.posted LIKE '201312%'
Notice no space between.
I believe you should be escaping the percentage sign for use in a LIKE statement, as such:
WHERE f.posted LIKE '%s %%'
Your problem is that sprintf treats % as a special character, so it gets confused when you want an actual % character. The solution for that is to use %% when you want the actual % character.
However, please do not insert values into your SQL with sprintf. That is an extremely bad practice and it is responsible for most of the security vulnerabilities in PHP code. Escaping your strings is not good enough. Use parameterized queries instead.
You should use the PDO or mysqli extensions, which support parameterized queries.
There are many articles explaining why you should not splice values into your SQL. Here is one: http://blog.codinghorror.com/give-me-parameterized-sql-or-give-me-death/
The way you should be doing it is discussed here: https://stackoverflow.com/a/60496/219155
I'm trying to retrieve all the data id from a database where their tags(array) is like a given value.
This is what I have done so far...
$new_string = 'nice phone';
$construct = mysql_query("SELECT tag_array, name, id FROM details
WHERE tag_array LIKE $new_string%")
or die("<p>died 20: $construct<br>" . mysql_error());
while($getThis = mysql_fetch_array($construct)){
echo $getThis['id'].'<br />';
echo stripslashes($getThis['name']).'<br />';
}
It doesn't work ATALL.
Could you please point me to the right direction?
I'm really struggling!!
You should put $new_string in quotes.
NOTE It is very bad practice and you should always escape all variables you are passing to SQL. You should really read up on SQL injection and other security issues.
Also if you want to match $new_string anywhere in tag_array (which you most likely want), you need to add dollar sign in front of it too. You can read up more at MySQL reference manual.
So in the end:
"SELECT tag_array, name, id FROM details WHERE tag_array LIKE '%" . mysql_real_escape_string($new_string) . "%'"
You should sanitise the data before putting it in the query like:
$new_string = "blah...; DROP TABLE tag_array; #";
$sql = mysql_real_escape_string($new_string);
$sql = "SELECT tag_array, name, id FROM details WHERE tag_array LIKE %'$sql'%"
This is not enough though it just helps preventing sql inject, consider using regular expressions to clean the data. If you don't yet know about regexp check out this site: regexp info. It helped me mutch.
Is there any way to check if a column is "anything"? The reason is that i have a searchfunction that get's an ID from the URL, and then it passes it through the sql algorithm and shows the result. But if that URL "function" (?) isn't filled in, it just searches for:
...AND column=''...
and that doesn't return any results at all. I've tried using a "%", but that doesn't do anything.
Any ideas?
Here's the query:
mysql_query("SELECT * FROM filer
WHERE real_name LIKE '%$searchString%'
AND public='1' AND ikon='$tab'
OR filinfo LIKE '%$searchString%'
AND public='1'
AND ikon='$tab'
ORDER BY rank DESC, kommentarer DESC");
The problem is "ikon=''"...
and ikon like '%' would check for the column containing "anything". Note that like can also be used for comparing to literal strings with no wildcards, so, if you change that portion of SQL to use like then you could pre-set the variable to '%' and be all set.
However, as someone else mentioned below, beware of SQL injection attacks. I always strongly suggest that people use mysqli and prepared queries instead of relying on mysql_real_escape_string().
You can dynamically create your query, e.g.:
$query = "SELECT * FROM table WHERE foo='bar'";
if(isset($_GET['id'])) {
$query .= " AND column='" . mysql_real_escape_string($_GET['id']) . "'";
}
Update: Updated code to be closer to the OP's question.
Try using this:
AND ('$tab' = '' OR ikon = '$tab')
If the empty string is given then the condition will always succeed.
Alternatively, from PHP you could build two different queries depending on whether $id is empty or not.
Run your query if search string is provided by wrapping it in if-else condition:
$id = (int) $_GET['id'];
if ($id)
{
// run query
}
else
{
// echo oops
}
There is noway to check if a column is "anything"
The way to include all values into query result is exclude this field from the query.
But you can always build a query dynamically.
Just a small example:
$w=array();
if (!empty($_GET['rooms'])) $w[]="rooms='".mysql_real_escape_string($_GET['rooms'])."'";
if (!empty($_GET['space'])) $w[]="space='".mysql_real_escape_string($_GET['space'])."'";
if (!empty($_GET['max_price'])) $w[]="price < '".mysql_real_escape_string($_GET['max_price'])."'";
if (count($w)) $where="WHERE ".implode(' AND ',$w); else $where='';
$query="select * from table $where";
For your query it's very easy:
$ikon="";
if ($id) $ikon = "AND ikon='$tab'";
mysql_query("SELECT * FROM filer
WHERE (real_name LIKE '%$searchString%'
OR filinfo LIKE '%$searchString%')
AND public='1'
$ikon
ORDER BY rank DESC, kommentarer DESC");
I hope you have all your strings already escaped
I take it that you are adding the values in from variables. The variable is coming and you need to do something with it - too late to hardcode a 'OR 1 = 1' section in there. You need to understand that LIKE isn't what it sounds like (partial matching only) - it does exact matches too. There is no need for 'field = anything' as:
{field LIKE '%'} will give you everything
{field LIKE 'specific_value'} will ONLY give you that value - it is not partial matching like it sounds like it would be.
Using 'specific_value%' or '%specific_value' will start doing partial matching. Therefore LIKE should do all you need for when you have a variable incoming that may be a '%' to get everything or a specific value that you want to match exactly. This is how search filtering behaviour would usually happen I expect.
Let's say I have a query:
" SELECT * FROM table
WHERE donor_id = " .$this->session->userdata('id') ."
GROUP BY rating"
However, it appears that I get a mysql syntax error here, citing that $this->session->userdata('id') gives me '25' for example, instead of 25. Are there any workarounds here to prevent $this->session->userdata('id') from being quoted?
Thanks.
In CI, I do this all the time:
$id = intval($this->session->userdata('id'));
$sql = " SELECT * ".
" FROM table ".
" WHERE donor_id = {$id} ".
"GROUP BY rating ";
//process $sql below
Creating query like this will make you easier to spot bug and prevent SQL injection. Use concatenation when you need to split query to multiple lines instead of make it a long multiple string is to prevent the actual query string got too long. Indent the SQL keyword is to make it easier spot logical and syntax bug.
intval($this->session->userdata('id'))
Assuming you mean that it is returning you a string instead of an integer you could always try using settype or intval:
$var = '2';
settype($var, "integer");
$var = intval($var);
However, if you mean that the quotes are for some reason hard-coded in, you could do a string replace, if you are sure that the value will not contain quotes:
ech str_replace("'", "", "'2'"); // prints 2