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 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
I generally understand the idea behind escaping quotes using backslashes and alternatively using backslashes to escape so that you can have backslashes in your strings and so forth, but I've run in to a problem trying to pass a query through odbc_exec() and using a table-valued function and I just cannot seem to get it to stop giving me
SQL error: [Microsoft][ODBC SQL Server Driver][SQL Server]Unclosed quotation mark after the character string '0000005'.
This is what it looks like when I hard code the variables:
$query = 'SELECT '.$csvCriteria.", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')";
This works fine. Note that $csvCriteria hasn't given me any problems. This is what I want it to look like:
$query = 'SELECT '.$csvCriteria.", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('".$stepNum."', '".$segMarker."', '".$prevDirection."', '".$rdNoA."', '".$re_1."', '".$re_2."', '".$directionA."')";
However I keep getting errors around $re_1 and $re_2 (the error I've put in at the top of this).
I've tried multiple variations of what I think may work, such as:
$query = 'SELECT '.$csvCriteria.", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('".$stepNum."','".$segMarker."','".$prevDirection."','".$rdNoA.'\',\''.$re_1.'\',\'00060091100B1P000030\',\'1\')';
But I am neither expertly proficient at this, nor do I know if I'm missing something blatantly obvious. Just absolutely stuck and need a hand!
I can not reproduce your error:
The SQL in question is:
SELECT csvcriteria,
googstep,
segment,
prevailingdirection
FROM jselectorcsvcreator('1', '1', 'northbound', '0006009',
'00000050370A2P000004', '00060041270B2P000070', '1');
Placing the data in variables such as:
$csvCriteria = 'csvCriteria';
$stepNum = 1;
$segMarker = 1;
$prevDirection = 'northbound';
$rdNoA = '0006009';
$re_1 = '00000050370A2P000004';
$re_2 = '00060041270B2P000070';
$directionA = 1;
Using the first line of code, which works and using the one that doesn't work both return the exact same thing:
$correct = 'SELECT ' . $csvCriteria . ", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')";
$query = 'SELECT ' . $csvCriteria . ", googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('" . $stepNum . "','" . $segMarker . "','" . $prevDirection . "','" . $rdNoA . "','" . $re_1 . "','" . $re_2 . "','" . $directionA . "')";
echo $correct . "\n";
echo $query . "\n";
var_dump($correct === $query);
The response is (CodePad):
SELECT csvCriteria, googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')
SELECT csvCriteria, googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('1','1','northbound','0006009','00000050370A2P000004','00060041270B2P000070','1')
bool(true)
My guess is that $csvCriteria or any of the variables at hand have errors.
I would highly recommend looking at the echoed query of $query in an SQL Formatter (Select MS ACCESS)
$query = 'SELECT '.$csvCriteria.", .....
should be
$query = 'SELECT '.$csvCriteria.', ......
Try using
$query = "SELECT $csvCriteria, googStep, Segment, PrevailingDirection FROM jSelectorCSVCreator('$stepNum','$segMarker','$prevDirection','$rdNoA','$re_1','00060091100B1P000030','1')";
This is much simpler without need of all the escapes.
As it turns out I was attempting to pass a string that looked like this "0000000\000X00X0\0000000" and it wasn't working so well. I decided to use stripslashes() so I could pass the variable more easily and work with it once it was in SQL. Turns out stripslashes() doesn't work like that. I used str_replace() instead and it now works fine.
I need to search a string in mysql with php. I get an error related to the spaces in the string. I an not fimilar with regex, I am not sure it that is my only choice.
example:
$ex="This and That";
$sql = 'SELECT
some_ID
FROM ' . atable. ' WHERE ' . strings. ' LIKE ' . $ex. ' AND visable=' . '1';
after executing I get an error like:
"near 'That AND visable=1' at line x"
so its probably not picking up the first two words, any suggestions?
Thanks in advance.
You are missing quotes around the string. They need to be encapsulated entirely for the query to execute properly.
Change this:
LIKE ' . $ex. ' AND
To this:
LIKE "' . $ex. '" AND
On a side note, make sure you are protecting your self against SQL injections AND make sure your query is properly escaped.
Basically i want to add wildcards to the the col value when searching...
Usually I do this the other way around like this:
WHERE cakes.cake_name LIKE '%$cake_search%'
however now i want it to match the inverse:
the user searches for 'treacle
sponge', i want this to match a row
where the cake_name column =
'sponge'.
is this possible?
WHERE '$cake_search' LIKE concat('%',cakes.cake_name, '%')
should work. It will need a full table scan but so will the inverse query. Have you looked into full text search for MySQL? It will likely make this sort of query more efficient.
Why not using MATCH?
MATCH(`cake_name`) AGAINST ('treacle sponge')
You would have to split the user supplied input on the space character and dynamically construct your query to check the column for those values:
$input = "treacle sponge";
$input_words = explode(' ', $input);
$sql_where = "WHERE cakes.cake_name IN('" . implode("','", $input_words) . "')"; // generates: WHERE cakes.cake_name IN('treacle','sponge')
In order to prevent SQL-Injection, I suggest using prepared statements.
$prepStmt = $conn->prepare('SELECT ... WHERE cakes.cake_name LIKE :cake_search
');
if($prepStmt->execute(array('cake_search'=>"%$cake_search%"))) {
...
}
Or, using full text search:
$prepStmt = $conn->prepare('SELECT ... WHERE MATCH (`cake_name`) AGAINST (:cake_search IN BOOLEAN MODE)');
if($prepStmt->execute(array('cake_search'=>$cake_search_words))) {
...
}
See JSON specialchars JSON php 5.2.13 for a complete example.. ;)