I need to display the results of this query :
SELECT * FROM projects WHERE PrestaCmd LIKE '% A - CREP - DPE - %'
but in PHP, this query doesn't work :s
This is my code :
$req = "SELECT * FROM ".$table." WHERE PrestaCmd LIKE '%".$ch."%'";
echo $req; //returns : SELECT * FROM jos_projectlog_projects WHERE PrestaCmd LIKE '% A - CREP - DPE - %'
$results = mysql_query($req);
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
print_r($row);
}
I think the problem is coming from the '$ch' variable.
But when I put an echo of the query, it's correct, and when I put a query like this :
$req = "SELECT * FROM jos_projectlog_projects WHERE PrestaCmd LIKE '% A - CREP - DPE - %'";
echo $req;
$results = mysql_query($req);
while ($row = mysql_fetch_array($results, MYSQL_ASSOC)) {
print_r($row);
}
it works :s
#Bahumat100, if you think you have to make space which is causing problem, then use html_entity_decode and do it like this:
$req = "SELECT * FROM ".$table." WHERE PrestaCmd LIKE '%".html_entity_decode($ch)."%'";
Related
$query = "SELECT * FROM posts WHERE language='$lang' AND (title LIKE '%$search%' OR author LIKE '%$search%' OR year LIKE '%$search%')";
This does exactly what it should do. But what I'd like to do is having "title" as a priority. But as it looks now (every search is in a dropdown of html) it simple show's it without an priority. So the title can be at the very bottom, and the author at the top. Wrong order. I'd like to somehow always have the title at top.
How?
$output = '';
$lang = $_SESSION["lang"];
$search = $_POST["query"];
$query = "SELECT * FROM posts WHERE language='$lang' AND (title LIKE '%$search%' OR author LIKE '%$search%' OR year LIKE '%$search%')";
$result = mysqli_query($connect, $query);
$output = '<ul class="list-unstyled">';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '<li>'.$row["book"].'</li>';
}
}
else
{
$output .= 'Not found.';
}
$output .= '</ul>';
echo $output;
You can split up the query.
$output = '';
$lang = $_SESSION["lang"];
$search = $_POST["query"];
$query2 = "SELECT * FROM posts WHERE language='$lang' AND title LIKE '%$search%'";
$result2 = mysqli_query($connect, $query2);
$output = '<ul class="list-unstyled">';
if(mysqli_num_rows($result2) > 0)
{
while($row = mysqli_fetch_array($result2))
{
$output .= '<li>'.$row["book"].'</li>';
}
}
else
{
$output .= 'Not found.';
}
$query = "SELECT * FROM posts WHERE language='$lang' AND (author LIKE '%$search%' OR year LIKE '%$search%')";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '<li>'.$row["book"].'</li>';
}
}
else
{
$output .= 'Not found.';
}
$output .= '</ul>';
echo $output;
ORDER BY should do the trick for you here:
http://www.w3schools.com/sql/sql_orderby.asp
$query = "
SELECT book
, title
, url
FROM posts
WHERE language='$lang'
AND (
title LIKE '%$search%'
OR
author LIKE '%$search%'
OR
year LIKE '%$search%'
)
ORDER BY title ASC
, author ASC
, book ASC
";
I've added an optional order by 'author' and 'book' too (the priority of ordering starts with 'title', then 'author' and finally 'book') - you can change this to whatever you need though in ASC (ascending) or DESC (descending) order.
I'd also recommend you consider using bind params rather than passing in variables directly into your SQL to prevent SQL Injection.
Mysqli Bind Param Documentation
http://php.net/manual/en/mysqli-stmt.bind-param.php
Really good SO post here with help and more info about SQL Injection
How can I prevent SQL injection in PHP?
Also - try to avoid using SELECT * FROM... where possible, and only SELECT out the information you need. You'll be able to INDEX it better this way too (meaning quicker retrieval of data from the database).
You could use a scoring system to give each match a score and then sort by the match score. So a match for title gets a higher score and a match for author gets the next highest and so on. I'll rewrite just the query here:
SELECT *,
(
CASE
WHEN title LIKE '%$search%' THEN 100
WHEN author LIKE '%$search%' THEN 10
WHEN year LIKE '%$search%' THEN 1
END
) AS matchScore
FROM posts
WHERE
language='$lang' AND
(title LIKE '%$search%' OR author LIKE '%$search%' OR year LIKE '%$search%')
ORDER BY matchScore DESC
I am creating simple searching script with LIKE clause.
Below is the simple query with LIKE clause using php.
$rows = mysql_query("select * from description where tags like '%{$keyword}%'");
This above query work successfully. But LIKE clause not working with $wpdb->prepare(). Below is the code for that
$rows = $wpdb->get_results($wpdb->prepare("select * from description where tags like '%{%s}%'",$keyword));
What I am missing in this?
You need to escape the % character,
try this:
$param = "%{$keyword}%";
$stmt = $db->prepare("SELECT * FROM description WHERE tags LIKE ?");
$stmt->bind_param("s", $param);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)) {
foreach ($row as $r) {
print "$r ";
}
print "\n";
}
I usually use sprintf, and do something similar to this.
global $wpdb;
$querystr = sprintf(
"SELECT * FROM description WHERE tags LIKE '%%%$s%%'"
mysql_real_escape_string($s)
)
$rows = $wpdb->get_results($querystr, OBJECT);
echo "</pre>"; print_r($rows); echo "</pre>";
The following code works well, but I couldn't find a way to limit the number of results. Any ideas please?
$q = "some keywords for search"; // always escape
$keys = explode( " ",$q );
$query = "SELECT * FROM table WHERE para LIKE '%$q%' ";
foreach($keys as $k)
{
$query .= " OR para LIKE '%$k%'";
}
$result = $mysqli->query($query);
while( $row = $result->fetch_assoc())
{
if ($row != 0) {
$title = $row['title'];
}
}
Any help while be appreciated.
Note: the $q holds the search keywords, and then the code explode it, and search for the keywords in 2 steps:
1- as one sentence using ($q as it is).
2- it searches for each keyword as an array after exploding the $q (here is the part that the "foreach" does).
After that the code loops using "while" to find all results match the search request.
Use LIMIT after completing your query.
Also, if you want to get results sorted by some fields in your table, you could also say " ORDER BY fieldname ASC|DESC"
As follows:
$q = "some keywords for search"; // always escape
$keys = explode( " ",$q );
$query = "SELECT * FROM table WHERE para LIKE '%$q%' ";
foreach($keys as $k)
{
$query .= " OR para LIKE '%$k%'";
}
$query .= " LIMIT 10"; //<<<<<<<<<<<<<<<
$result = $mysqli->query($query);
while( $row = $result->fetch_assoc())
{
if ($row != 0) {
$title = $row['title'];
}
Use LIMIT.
SELECT * FROM table WHERE para LIKE '%$q%' LIMIT 2
You can limit the number of results in your MySQL query, like so:
$query = "SELECT * FROM table WHERE para LIKE '%$q%' LIMIT 5";
this will limit it to 5 results. If you want 10, change it to 10
I am trying to query a mysql table using some "likes". But it doesn't work at all.
This is my code:
$color_base1 = $row[color_base1];
$color_base2 = $row[color_base2];
$result2 = mysql_query("SELECT * FROM item_descr WHERE (color_base1 LIKE
'%$color_base1%' OR color_base2 LIKE '%$color_base1%' OR color_base1
LIKE '%$color_base2%' OR color_base2 LIKE '%$color_base2%')
AND id_item != $itemId");
if (mysql_fetch_array($result2) == 0)
{
$result2 = mysql_query("SELECT * FROM item_descr WHERE (keywords LIKE
'%$keywords%') AND id_item != $itemId LIMIT 3");
}
else
{
$row2 = mysql_fetch_array($result2);
echo "<div class='similarTitle'>YOU MAY ALSO LIKE</div>";
while ($row2 = mysql_fetch_array($result2))
{
echo "<div class='similarItems'>";
echo "<img class='similarImage' src='images/{$row2[thumb1]}.jpg'>";
echo "<div class='similarItemsText'>".$row2[name]."</div></div>";
}
}
Thanks!
try changing your queries into these:
Query1:
SELECT *
FROM item_descr
WHERE (color_base1 LIKE CONCAT('%' , $color_base1, '%') OR
color_base2 LIKE CONCAT('%' , $color_base1, '%') OR
color_base1 LIKE CONCAT('%' , $color_base2, '%') OR
color_base2 LIKE CONCAT('%' , $color_base2, '%')) AND
id_item != $itemId
Query 2:
SELECT *
FROM item_descr
WHERE keywords LIKE CONCAT('%' , $keywords, '%') AND
id_item != $itemId
LIMIT 3
Try escaping your variables inside the query
mysql_query("select ... like '%" . $var . "%' ...");
$color_base1 = $row['color_base1']; // <- index NOT constant
$color_base2 = $row['color_base2'];
$result2 = mysql_query("SELECT * FROM item_descr WHERE (color_base1 LIKE '%$color_base1%' OR color_base2 LIKE '%$color_base1%' OR color_base1 LIKE '%$color_base2%' OR color_base2 LIKE '%$color_base2%') AND id_item != $itemId");
if(mysql_num_rows($result2) == 0) // <- check for NO RESULTS
{
$result2 = mysql_query("SELECT * FROM item_descr WHERE (keywords LIKE '%$keywords%') AND id_item != $itemId LIMIT 3");
}
$row2 = mysql_fetch_array($result2);
echo "<div class='similarTitle'>YOU MAY ALSO LIKE</div>";
while ($row2 = mysql_fetch_array($result2))
{
Your array referencing is done incorrectly. $row['color_base1'] is not the same as $row[color_base1]
Your code gets an array from the search results (first row) and checks it against 0. I believe you mean to check the number of results returned and if there were none then check for suggestions.
If your second query is executed, it does nothing with the results
When you process your results to produce output, you are looping through the results from row 2 onwards (see point 2)
DEBUG:
if you do $sql="..."; then you can debug by echo-ing $sql and then checking the results manually by putting them into phpmyadmin
do lots of echo "I am at line:".__ LINE __; to check which path your logic is going in.
compare your phpmyadmin results with a var_dump($row); inside your loop to see if your skipping rows.
myql_query($sql) or die(mysql_error()); // will stop if your query is bad
etc.....
I am using LIKE to do my searching, i try it in phpMyAdmin and return the result but when i use it in php it return empty result.
$search = "ip";
$start = 0;
$query = "SELECT * FROM product WHERE product_name LIKE '%$search%' LIMIT $start,30";
$result = mysql_query($query);
if(empty($result))
$nrows = 0;
else
$nrows = mysql_num_rows($result);
It will return result when i using phpMyAdmin to run this query but when i use it in php, it return empty.
Update:
Sorry guys,
I just found out the problem is i didn't connect database as well. anyway, thanks for helping.
Try This
$query = "SELECT * FROM `product` WHERE `product_name` LIKE '%".$search."%' LIMIT 0, 30";
And if the sole purpose of your code is to get the number of products with the searched-for name, use SELECT COUNT(*) instead of doing a mysql_num_rows() on all your data. It will decrease your querytime and the amount of data that is (unnecessarily) fetched.
I am not sure why this is not working, as the query seems to be correct to me. I would like to suggest you writing query this way
$query = <<<SQL
SELECT * FROM product WHERE product_name LIKE "%$search%" LIMIT $start,30
SQL;
please note that there should not be any space or any character after SQL;
$query = "SELECT * FROM product WHERE product_name LIKE '%" . $search . "%' LIMIT " . (int) $start. ",30";
you can use directly mysql_num_rows()
but here is right code
$query = "SELECT * FROM product WHERE product_name LIKE '%".$search."%' LIMIT $start,30";
$search = "ip";
$start = '0';
$query = "SELECT * FROM product WHERE product_name LIKE '%".$search."%' LIMIT $start,30";
$result = mysql_query($query)or die(mysql_error());
if(mysql_num_rows($result) == 0){
$nrows = 0;
} else{
$nrows = mysql_num_rows($result);
}
//use mysql_num_rows($result) instead of empty($result) because in this situation $result is every time not empty so use inbuilt PHP function mysql_num_rows($result);