I have a MySQL table that looks like this:
index | tag | posts
-------------------------
1 | cats | 9,10
2 | a cat | 9,10
3 | kitty | 9,10
4 | meow | 9,10
I am trying to just return the row that matches a search query.
I passed the search parameter using a simple ?search=cats.
This is the PHP that I'm using:
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '$search'");
echo(mysql_num_rows($query));
$result = mysql_fetch_array($query);
$print = $result['posts'];
echo($print);
However the mysql_num_rows($query) prints 0 and the $print returns NULL. I can check it with ($print == ""), it evaluates to TRUE and mysql_num_rows($query) returns 4.
I tried setting the search query to something that wasn't in the table and it retuned FALSE as expected. I also tried removing the WHERE tag = '$search' and it returns the table like it should.
Is there something I'm overlooking?
Edit
Took everyone's advice and the code I'm using now is:
$search = mysql_real_escape_string($_GET['search']);
var_dump($search); //prints string(4) "cats" just like it should
$queryText = "SELECT * FROM tags WHERE tag = '%".$search."%'";
echo($queryText); //SELECT * FROM tags WHERE tag = '%cats%'
$query = mysql_query($queryText) or die(mysql_error()); //no error
$rows = mysql_num_rows($query); //this returns 0 and I know it should match 1 row
echo('rows: '.$rows);
$result = mysql_fetch_array($query);
$print = $result['posts'];
echo($print); //empty
Still have the same problem. The mysql_query is retuning NULL instead of the row or FALSE if it doesn't match.
(in the future I will use the mysqli API, but I would like to finnish this project in mysql. thanks for your suggestions and advice)
Try this code now.
Remeber when you want to debug something in PHP the faster way is var_dump not echo. Also you should avoid mysql_api because they are deprecated, use PDO instead PDO on PHP.net
var_dump($_GET); // Just for debuggin if as something
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '".mysql_real_escape_string($search)."'");
// echo(mysql_num_rows($query));
$result = mysql_fetch_array($query);
var_dump($result);
//$print = $result['posts'];
//echo($print);
Ok so after referring to the above edit you made, here is the solution
Use "LIKE" instead of "=" when using wildcard "%"
So your query now should be
$queryText = "SELECT * FROM tags WHERE tag LIKE '%" . $search . "%'";
[I created the exact same db on my local system and ran the same code you gave, After making the above changes, It runs as expected]
$search = $_GET['search'];
echo $select_query="SELECT * FROM tags WHERE tag = '".mysql_real_escape_string($search)."'";
$query = mysql_query($select_query);
echo(mysql_num_rows($query));
while($result = mysql_fetch_array($query))
{
print_r($result);
}
Note:
$search = $_GET['search'];
$query = mysql_query("SELECT * FROM tags WHERE tag = '$search'");
That is very dangerouse: It allow sql incersion code to your database. You must always escape all what you get from the client.
$search = mysql_real_escape_string($_GET['search']); //It require open database connection.
Note2:
mysql_query is obsolete, use mysqli instead ;-)
Answer:
If you have not answer, you probable has an error in an other part.
Try
//1) Look if your search has a correct value
var_dump($search);
//2) Replace the query with (just for debugging):
$query = mysql_query("SELECT * FROM tags WHERE tag = 'cats';");
You may also use "tag like '%cats%'" if you want a more flexible search.
If you remove the WHERE tage = '$search', it cannot return the table like it should because your mysql_fetch_array is not in a while loop... but that aside...
// make sure before you execute the code to check that $_GET['search'] is not empty
// start with escaping the search-value (for mysql-injection)
$search = msyql_real_escape_string($_GET['search']);
// changed the query so it searches for tags containing the search value.
// if you would have records with tags "blue cat" and "red cat" it shows them both
// when searching for "cat"
$query = mysql_query("SELECT * FROM tags WHERE tag LIKE '%".$search."%'");
// put the number of rows in a var
$num = mysql_num_rows($query);
// check this var if it's not 0
if ($num != '0'){
while ($row = mysql_fetch_array($query){
echo $row['posts'];
// etc...
}
} else {
// 0 rows found
echo "nothing found";
}
Related
I have a query that returns all the data while running at MSSQL, but when I try to get the result with php code it returns null
SELECT:
$query = "SELECT DISTINCT (E080SER.desser) as desser,
E080SER.CODFAM codfam, e085cli.apecli apecli,
E085CLI.CODCLI codcli, E085CLI.NOMCLI nomeCli
FROM
E160CTR,
E160CVS, e080ser,
E085CLI,
E070EMP,
E070FIL
WHERE
e070emp.nomemp like '%Gestão tech%' and
e080ser.codser = e160cvs.codser and
e080ser.codser like ('%manw%') and (E160CTR.CODEMP = 1) and
((E160CTR.CODEMP = E070FIL.CODEMP) AND (E160CTR.CODFIL =
E070FIL.CODFIL) AND
(E160CTR.CODCLI = E085CLI.CODCLI) AND (E160CVS.CODEMP =
E160CTR.CODEMP) AND
(E160CVS.CODFIL = E160CTR.CODFIL) AND (E160CVS.NUMCTR =
E160CTR.NUMCTR)) AND
(E160CTR.SITCTR = 'A') and e080ser.sitser = 'a' and
E080SER.CODEMP IN (1, 9)
order by e080ser.desser";
PHP CODE:
$sql = sqlsrv_query($conn, $query);
while($item = sqlsrv_fetch_array($sql)){
var_dump($item);
}
Sometimes it's necessary to fetch all result sets with sqlsrv_next_result() to get your data. You may try with this:
<?php
...
$sql = sqlsrv_query($conn, $query);
do {
while($item = sqlsrv_fetch_array($sql)){
var_dump($item);
}
} while (sqlsrv_next_result($sql));
...
?>
There is an extra semicolon after the while loop, i.e. the body of the loop is empty. Then the result you try to read is after the last row, that's why you don't get what you expected.
I've found the problem
The problem was the encoding, I put the $query inside of utf8_encode(), and now it is returning the results.
Thank you all for your time.
<?php
include"configration.php";
?>
<?php
$query = $_GET['query'];
$min_length = 1;
//echo $query;exit();
if (strlen($query) >= $min_length) { // if query length is more or equal minimum length then
//echo "success";exit();
$query = htmlspecialchars($query);
$query = mysqli_real_escape_string($conn, $query);
$sql = "SELECT * FROM table2
WHERE title LIKE '%".$query."%' order by date DESC";
$raw_results = mysqli_query($conn, $sql) or die(mysql_error());
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($res = mysqli_fetch_array($raw_results)) { ?>
<?php echo $res['title'] ?> // Place where result comes ..
<?php }
}
}
?>
This is code works fine but search in this way
For Example Title is: you are vary nice boy but lazy
When I search by:
You are vary ............. result shows ..
vary nice boy ............. result shows ..
vary lazy, or boy lazy or vary lazy .. result not shows ..
Plz some one help me in this and how to show searched query in title ..
<title> Searched Query ...</title>
LIKE '%boy lazy%' will show the Of the cases where anything can be before boy lazy and anything can be after boy lazy, but boy lazy will be together.
In your case, one approach can be, you can explode your $query, and then use multiple LIKE queries to create sql query. Example:
<?php
//$conn = mysqli_connect("localhost","your user","your pass","db");
$query = $_GET['query'];
$min_length = 1;
//echo $query;exit();
if (strlen($query) >= $min_length) { // if query length is more or equal minimum length then
//echo "success";exit();
$query = htmlspecialchars($query);
$query = mysqli_real_escape_string($conn, $query);
$searchKeys = explode(' ',$query);
$sql = "SELECT * from table2 where title ";
foreach ($searchKeys as $key) {
$sql.= "LIKE '%".$key."%' AND title ";
}
$sql = substr($sql, 0, -10);
//$sql.="ORDER BY date DESC;";
$raw_results = mysqli_query($conn, $sql) or die(mysql_error());
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($res = mysqli_fetch_assoc($raw_results)) {
echo $res['title']."\n";
}
}
}
When you search title LIKE "%vary lazy%", you will get records that contain the string "vary lazy" preceeded and followed by any other or no character sequences. If you want to match strings that contain the words - I should better say, the character sequences - "vary" and "lazy" in that specific order you should use:
title LIKE "%vary%lazy%"
However, this will also match "varylazy", "varying lazytown characters".
Assuming you generally intend to use queries as you mentioned, i.e. each word is separated by a space character and you want to see if those words appear in a text in specifically that order, you could write something like this:
$query = $_GET["query"];
$query = '%'.str_replace(' ', '%', $query).'%';
//... MySQL stuff
Please be aware that the code above is very specific to your needs. I wouldn't use it as a general purpose approach for processing query strings, e.g. having multiple spaces between words would result in multiple consequent % in your SQL query - I'm not even sure if that is allowed. However, under the constraints described, this code should work just fine.
i've a problem with a search form. It works only if I use all the 4 fields, but if a leave a field empty the while loop echoes out all the table's records.
Can someone please help me?
This is my php code for the search function
<?php
if (isset($_POST['cerca'])){
$cerca_tt = $_POST['tt_carrier'];
$cerca_risorsa = $_POST['risorsa_cerca'];
$cerca_team = $_POST['team_cerca'];
$cerca_linea = $_POST['linea_cerca'];
$sql_cerca = "SELECT * FROM normal WHERE
tt LIKE '%".$cerca_tt."%'
OR risorsa LIKE '%".$cerca_risorsa."%'
OR team LIKE '%".$cerca_team."%'
OR linea LIKE '%".$cerca_linea."%'";
if($sql_cerca) {
$trovati = mysql_query($sql_cerca); ?>
if the POST is blank then the variable is blank thus everything will match like '%%'
for example if $cerca_tt is blank. your query would be
"SELECT * FROM normal WHERE tt like '%%'"
that matches everything.
create the query based on the POST response.
$sel = "SELECT * from normal";
//You will need to deal with the WHERE part of the query.
if (!empty($cerca_tt)){
$sel .= " OR tt like '%".$cerca_tt."'";
}
etc....///
If you only provide one search parameter and the rest are empty strings, which you wrap with %, you are effectively searching everything. You need to build up your query. For example (simple):
$sqlParts = [];
if(isset($_POST['tt_carrier'])) {
$sqlParts[] = "tt LIKE '%".$cerca_tt."%'";
}
if(isset($_POST['risorsa_cerca'])) {
$sqlParts[] = "risorsa LIKE '%".$cerca_risorsa."%'";
}
if(isset($_POST['team_cerca'])) {
$sqlParts[] = "team LIKE '%".$cerca_team."%'";
}
if(isset($_POST['team_cerca'])) {
$sqlParts[] = "linea LIKE '%".$linea_cerca."%'";
}
if(!empty($sqlParts)) {
$sql = "SELECT * FROM normal WHERE " . implode(' OR ', $sqlParts);
}
I am a beginner in php.
I visualize in my html page the results obtained with this php code, and now I want to paginate the results and limit your search to 6 items per page. How can I get this? My php code is as follows:
<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM table_name WHERE ";
$i = 0;
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
// connect
mysql_connect("hostname","databaseUser","databasePassword");
mysql_select_db("databaseName");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
echo "<p><strong>Totale: {$numrows} risultati trovati</strong></p></br>";
if ($numrows > 0){
while ($row = mysql_fetch_assoc($query)){
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
$date = $row['date'];
$caption = $row['caption'];
echo "<h4><a href='$link'>$title</a></h4>";
echo "<em>$description</em></br></br>";
echo "$caption</br>";
echo "$link</br></br>";
echo "<em>$date</em></br></br>";
}
}
else
echo "NO result found for \"<p><strong>$k</strong></p>\"";
// disconnect
mysql_close();
?>
Pagination is a problem that most of us have tried to solve over the years.
You can build your own library to do this but you'll almost definitely be re-inventing the wheel and might not spot/handle some of the special cases.
If you're using a framework I'd suggest using the built in paginator, if not you could look at using something like http://pear.php.net/package/Pager which is a PEAR package.
You need to add a page variable into your code. The easiest way to to this is via $_GET, just like you grabbed keywords, so your url should look something like this:
foo.php?k=keywords%20here&p=1
Where p is the current page number.
Then you just need to add a limit to your search results so that you only grab 6, and the correct 6 at that. Something like this:
$query .= ' LIMIT '.(6*($pageNum - 1)).' 6';
This statement tells SQL to start at the first entry for the given page, and grab 6 results. We subtract 1 from the page number so that page 1 starts at entry 0 instead of entry 6.
The result of this code:
page | statement | Rows Grabbed
---------------------------------
1 | LIMIT 0 6 | 1-6
2 | LIMIT 6 6 | 7-12
3 | LIMIT 12 6 | 13-18
---------------------------------
and so on...
You might need to check that $_GET['p'] is an integer before you put it in $pageNum, so that you don't run into runtime issues trying to multiply a string by 6.
If you ever want to change the results per page, simply replace the 6's in that statement with the desired number of results per page, e.g.
$query .= ' LIMIT '.($numResults*($pageNum - 1)).' '.$numResults;
That way you can set your desired number of results with another variable, say $_GET['n'] or something similar, and have even better control.
EDIT:
You should probably add error checking:
$pageNum = (is_numeric($_GET['p']) ? intval($_GET['p']) : 1);
which says if GET[p] is numeric, set pageNum to the integer value of GET[p]. Otherwise, set pageNum to 1.
Also, You have a few errors in the way that you put variables into strings. There are two ways to join a variable into a string, you can either use double quotes and curly braces, like so:
$string = "this string has {$variable} in it";
Or you can concatenate with periods, using either single or double quotes likes so:
$string = 'this string has ' . $variable . " in it";
You have this problem in your foreach loop when you append the query, and also further down where you output your results.
I face a problem with the str_replace function, see the code below :
$query = "SELECT title FROM zakov WHERE chnt='$atd_nad'";
$str = str_replace("Example.com_", "","$query");
$result = mysql_query($str) or die('Errant query: '.$str);
What I want is to replace the word " Example.com_ " with nothing "" but it did not work for me ! I do not know why.
In the row 'title' you can find something like this " Example.com_nameofsmthng "
So what I want is to keep just the word "nameofsmthng" and also to keep the begining of each word of it in capital letter to have finally somethin like "NameOfSmthng"
$atd_nad = 'Foobar Example.com_nameofsmthng Bazbat';
$query = 'SELECT title FROM zakov WHERE chnt="' . $atd_nad . '"';
$str = str_replace('Example.com_', '', $query);
echo $str; // SELECT title FROM zakov WHERE chnt="Foobar nameofsmthng Bazbat"
This works fine. Try it quickly. My assumption is that you mistyped $atd_nad or the value is incorrect.
Edit: hmm i think I misunderstood the example your trying to replace the string in the query string instead of the database?
You could make mysql do the replacement for you which should be faster then making php do it.
$query = "SELECT REPLACE(title, 'Example.com_', '') as newtitle FROM zakov WHERE chnt='$atd_nad'";
$resultset = mysql_query($query) or die('Errant query: '.$query);
$result = mysql_fetch_assoc($query);
echo $result['newtitle'];
Or you could replace all occurrences in the database with an update and then just select the title.
UPDATE zakov SET title = REPLACE(title, 'Example.com_', '');
Hope this helps.
while($row = mysql_fetch_assoc($result)) {
$title = str_replace("something", "", $row['title']);
}
Is what I believe you're looking for. Your code is trying to replace it in the query, which doesn't make sense. You need to replace it in the actual records. This will replace "something" with "". Alternatively, if you've already stored them in an an array or something you would just loop over the array and do the replacement. Basically: operate on the records, not on the query.