I'm working on a new search script for my website that contains multiple dictionaries. First let me show you the problem piece of code and then explain....
$sql = mysql_query("SELECT * FROM $tbl_name WHERE $field = '%$trimmed%' ORDER BY $field ".$sort." LIMIT ".$limits.", $max")or die(mysql_error());
$count = mysql_result(mysql_query("SELECT COUNT($field) FROM $tbl_name WHERE $field = '%$trimmed%'"),0);
if ($count < 1){
$sql = mysql_query("SELECT * FROM $tbl_name WHERE $field LIKE '%$trimmed%' ORDER BY $field ".$sort." LIMIT ".$limits.", $max")or die(mysql_error());
$count = mysql_result(mysql_query("SELECT COUNT($field) FROM $tbl_name WHERE $field LIKE '%$trimmed%'"),0);
}
Okay, in theory, the first query should select results that are exact and display them without displaying the "LIKE" results. However, it does not do that. It simply always shows the LIKE results.
And when I remove all of that, and leave the first query - no results are returned - even though they are in the database.
For example, with everything after "if ($count <1 ) {" included, I can search "SHE" or "I" and get results - however it includes words like "informal", "singular", etc. But when I remove this, I can search "SHE" and "I" and get no result at all, even though they're in the database.
Any help would be greatly appreciated.
Remove the '%' characters around "$trimmed" in the first query.
See if that fixes it.
Related
I downloaded some code that utilizes PDO, which I'm not too familiar with - I generally use mysqli_ statements, but I'm trying to learn how to use PDO as well.
In the following bit of code, a user begins to type a part number into a field, and the system returns any value from the database'squotePartNumberfield that is LIKE what they're typing in.
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT DISTINCT quotePartNumber from allparts where quotePartNumber LIKE (:keyword) LIMIT 0,10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
// put in bold the written text
$country_name = str_replace(strtoupper($_POST['keyword']), '<b>'.$_POST['keyword'].'</b>', $rs['quotePartNumber']);
// add new option
echo '<li onclick="set_mainPartNumber(\''.str_replace("'", "\'", $rs['quotePartNumber']).'\')">'.$country_name.'</li>';
}
This works perfectly... I've been playing around with the code for about two hours trying to figure out how to get it to ALSO pull the fieldsupplier, which is also in this same table.
When the user starts typing in a part number, I also want the supplier that matches up with that same row's part number to be returned. I can't figure out how to do it though...
any ideas?
It should be as simple as changing the select statement.
$sql = "SELECT DISTINCT quotePartNumber, supplier from allparts where quotePartNumber LIKE (:keyword) LIMIT 0,10";
Then you could display it by updating the echo statement.
echo '<li onclick="set_mainPartNumber(\''.str_replace("'", "\'", $rs['quotePartNumber']).'\')">'.$country_name.' - '.$rs['supplier'].'</li>';
My problem is this: I found a easy and fast way to get random row in my table. First, i am using query, which counts my ids from my table. Second, i generate random number from 1 to result of count query. Third, i am selecting row from my table where id is equal to my random generated number. Everything works fine, but the problem is that sometimes query displays me blank page with no information given, with no error given.
here is my code:
$viso = $stmt = $db->query("select count(id) from intropage")->fetchColumn();
$min=1;
$max= $viso;
$lopas=rand($min,$max);
$stmt = $db->query('SELECT * FROM intropage WHERE id='.$lopas.'');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
... }
How can i fix this "blank page" issue?
Thanks to all of you for any answers!
It's not fast method, because you are using double request to db AND you are exposed to SQL injection. Try:
$query = $db->prepare('SELECT * FROM intropage ORDER BY RAND() LIMI 1');
$query->execute();
$results = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
/* */
}
I think it will fix your blank page error too. If not, turn on error reporting and tell us what error you get.
Is error_reporting activated ?
Your query is wrong so an error is throw and you probably cannot see it
$db->query("SELECT * FROM intropage WHERE id='".$lopas."'");
Also, a better way to have random row, is to use RAND()
$db->query("SELECT * FROM intropage ORDER BY RAND() LIMIT 1");
I have small question on mysql search query i need to make a search query php scripting with displaying all similar name , eg: if 100 similar names are found in the results the 100 results must show.
Here is my script of search query system.
$result = mysql_Query("SELECT user FROM `UserData` WHERE user LIKE '%$username%'") or die(mysql_error());
$fetch = mysql_num_rows($result);
if( $fetch > 0 )
{
$resultgg = mysql_Query("SELECT user FROM `theusers` WHERE user LIKE '%$username%' ORDER BY `user` ASC LIMIT 500") or die(mysql_error());
$row = mysql_fetch_row($resultgg);
$users = $row[0];
echo "$users";
}
}
else
{
echo "<br><b>Please Enter Valid Username!</b>";
}
Please Help me.
mysql_fetch_row()
returns only 1 column of the resultset (see PHP docs). You need to iterate through the rows.
Visit the PHP documentation for mysql_fetch_row
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.
MY SQL QUERY:
$q = mysql_query("SELECT * FROM `ads` WHERE keywords LIKE '%$key%' ORDER BY RAND()");
RESULTS: KEYWORD123
This query searches and results in one random row but i want to show 2 random rows.
How to do that?
any solution?
how??
im grabbing it using this
$row = mysql_fetch_array($q); if ($row
<= 0){ echo 'Not found'; }else{ echo
$row['tab']; }
That query (as-is) will return more than one row (assuming more than one row is LIKE %$key%). If you're only seeing one record, it's possible you're not cycling through the result set, but rather pulling the top response off the stack in your PHP code.
To limit the response to 2 records, you would append LIMIT 2 onto the end of the query. Otherwise, you'll get every row that matches the LIKE operator.
//Build Our Query
$sql = sprintf("SELECT tab
FROM ads
WHERE keyword LIKE '%s'
ORDER BY RAND()
LIMIT 2", ('%'.$key.'%'));
// Load results of query up into a variable
$results = mysql_query($sql);
// Cycle through each returned record
while ( $row = mysql_fetch_array($result) ) {
// do something with $row
echo $row['tab'];
}
The while-loop will run once per returned row. Each time it runs, the $row array inside will represent the current record being accessed. The above example will echo the values stored in your tab field within your db-table.
Remove your order by and add a LIMIT 2
That happens after the execution of the SQL.
Right now you must be doing something like
$res = mysql_query($q);
$r = mysql_fetch_array($res);
echo $r['keywords'];
what you need to do
$q = mysql_query("SELECT * FROM ads WHERE keywords LIKE '%$key%' ORDER BY RAND() LIMIT 2");
$res = mysql_query($q);
while($r = mysql_fetch_array($res)){
echo "<br>" . $r['keywords'];
}
Hope that helps
This query will return all rows containing $key; if it returns only one now this is simply by accident.
You want to add a LIMIT clause to your query, cf http://dev.mysql.com/doc/refman/5.0/en/select.html
Btw both LIKE '%... and ORDER BY RAND() are performance killers