I get this syntax on the internet and modified some parts. I would like to locate/search records in a table. this syntax ended up as "Search Query not found" I can't find the problem in this syntax. Can you give me a little help in finding errors? Here's the syntax.
<?php // Get the search variable from URL
if(!isset($_GET['q']))
die('Search Query not found');
$var = $_GET['q'];
$trimmed = trim($var); //trim whitespace from the stored variable
// rows to return
$limit=10;
// check for an empty string and display a message.
if ($trimmed == ""){
echo "<p>Please enter a search…</p>";
exit;
}
// check for a search parameter
if (!isset($var)){
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("localhost","user1","test123");
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("inventory") or die("Unable to select database");
// Build SQL Query
$query = ("SELECT * FROM client WHERE account_name LIKE \"%$trimmed%\" or maintenance_type like \"%$trimmed%\" or ma_status like \"%$trimmed%\" ma_contract_start like \"%$trimmed%\" ma_contract_end like \"%$trimmed%\" ma_reference_no like \"%$trimmed%\" ORDER BY account_name DESC");
// EDIT HERE and specify your table and field names for the SQL query
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, offer a google search as an alternative — this is optional
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: $trimmed returned zero results</p>";
// google
echo "<p><a href=\"http://www.google.com/search?q="
. $trimmed . "\" target=\"_blank\" title=\"Look up
" . $trimmed . " on Google\">Click here</a> to try the
search on google</p>";
}
// next determine if s has been passed to script, if not use ZERO (0) to Limit the output
if (empty($s)) {
$s=0;
}
// get results
$query = " limit $s,$limit";
$result = mysql_query($query) or die("Couldn’t execute query");
// display what the person searched for
echo "<p>You searched for: $var </p>";
// begin to show results set
echo "Results: <br/>";
$count = 1 + $s ;
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$name = $row['account_name'];
$mtype = $row['maintenance_type'];
$status = $row['ma_status'];
$start = $row['ma_contract_start'];
$end = $row['ma_contract_end'];
$reference = $row['reference_no'];
echo "$count.> $name $mtype $status $start $end $reference <br/>" ;
$count++ ;
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
// next we need to do the links to other results
if ($s>=1) {
// bypass PREV link if s is 0
$prevs=($s-$limit);
print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a> ";
}
// calculate number of pages needing links
$pages=intval($numrows/$limit);
// $pages now contains int of pages needed unless there is a remainder from division
if ($numrows%$limit) {
// has remainder so add one page
$pages++;
}
// check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
// not last page so give NEXT link
$news=$s+$limit;
echo " Next 10 >>";
}
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
?>
You have mentioned you are getting this error "Search Query not found". The code you have written clearly tells the parameter 'q' is not set in the url.
if(!isset($_GET['q']))
die('Search Query not found');
If this has to work, your url should be
www.example.com?q=some_value
Related
I am working on a university project, which is based on e-shopping, i tried this code to implement my result, this gives no error but it does not work when I press next page link or "button" please help any help would be appreciated
<?php
$con = mysqli_connect("localhost","root","","php184_proj_db");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $qry to be your query
$qry = "SELECT * FROM posts";
$result = mysqli_query($con,$qry);
$row = mysqli_num_rows($result);
//This is the number of results displayed per page
$page_rows = 5;
//This tells us the page number of our last page
$last = ceil($row/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1; //Pagination of MySQL Query Results Setting the Variables
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
$j=0;
$qry = "SELECT * FROM posts $max";
$result = mysqli_query($con,$qry);
while($row = mysqli_fetch_array($result))
{
$j++;
echo "<p>";
// This shows the user what page they are on, and the total number Query and Results of pages
echo " --Page $pagenum of $last--
<p>";
// First we check if we are on page one. If we are then we don't need a
//link to the previous page or the first page so we do nothing. If we aren't
//then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a
href='{$_SERVER['PHP_SELF']}?pagenum=1'>
<<-First</a>
";
echo " ";
$previous = $pagenum-1;
echo " <a
href='{$_SERVER['PHP_SELF']}?
pagenum=$previous'> <-Previous</a>
";
}
//just a spacer
echo " ---- ";
//This does the same as above, only checking if we are on the last page,
//and then generating the Next and Last links
if ($pagenum == $last)
{
}
else {
$next = $pagenum+1;
echo " <a
href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next
-></a> ";
echo " ";
echo " <a
href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last
->></a> ";
}
?>
If you visit this URL: http://example.com/somepage.php?key=val, you don't automatically get a variable $key inside PHP. Instead, you have to use $_GET['key'], which will hold the value. (in this case: 'val')
So, somewhere in the beginning of your code, add the following:
if (isset($_GET['pagenum']) && $_GET['pagenum'] >= 1) {
$pagenum = (int) $_GET['pagenum'];
} else {
$pagenum = 1;
}
Not only does this create the $pagenum variable and give it the value from the URL, it also makes sure that the value is a valid number. If not, or if the URL doesn't contain a pagenum, it is set to 1.
Possible scenario's:
pagenum contains not an integer, but a string (might even be a SQL injection attempt)
pagenum is a negative number, or 0
pagenum isn't set at all
In all of the above cases, pagenum is set to 1.
If pagenum contains a float (for instance 1.5.), the value will be cast to an integer. In the case of 1.5, pagenum will become 1.
Remember, always make sure you sanitize user input.
Updated with suggestion by others but still seem to be stuck.
I'm using this php code here to display info from my database using the ID. I created a link on my main page that looks like this.
<h1><?php echo $row_getDisplay['title']; ?></a></h1>
I have so when they click on the title of the article that it takes them to my php fiel which I named fetch.php and the code below is what is in there. I have built this around someone else's work. For some reason I can't get passed the first "else" statement. so I keep getting "you must select a valid location" I'm fairly new to php so I don't really understand why the code is failing.
<?php require_once('Connections/XXXXXX.php'); ?>
<?php
if (isset($_GET['id']) == false) // check if id has been set
{
echo "You must select a location"; // if not, display this error
exit;
} else {
$id = (int) $_GET['id'];
if (is_numeric($id) == false)
**{
echo "You must select a valid location.";
} else {**
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE post_id ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
Any help is appreciated. If you are able to find a better solution for me that would be great.
You shouldnt use $HTTP_GET_VARS its deprecated and unless its turned on it wont be populated. use $_GET instead.
if (isset($_GET['id']) == false)
Use $_GET for your if statement:
if (isset($_GET['id']) == false)
Also, you need to convert your $_GET value to an integer, because it is currently a string.
Right after that if statement above, in the else, put this:
$id = (int) $_GET['id'];
That way your is_numeric() will work properly.
Try this;
<?php
require_once('Connections/XXXXXX.php');
if (isset($_GET['id'])) // check if id has been set
{
$id = $_GET['id'];
if (is_numeric($id) == false)
{
echo "You must select a valid location.";
} else {
mysql_select_db($database_XXXXXX, $XXXXXX);
$query = MYSQL_QUERY("SELECT * FROM news WHERE locationid = 'news.post_id' ");
if (MYSQL_NUM_ROWS($query) == "1")
{
$fetch = MYSQL_FETCH_ARRAY($query); // set $fetch to have the values from the table
echo "Title: " . $fetch['title'] . "<BR>"; // output the info
echo "Blog: " . $fetch['blog_entry'] . "<BR>"; // etc...
echo "Author: " . $fetch['author'] . "<BR>"; // etc...
} else {
echo "No match in database found."; // if no match is found, display this error
}
}
}
else{
echo "You must select a location"; // if not, display this error
exit;
}
?>
Also, I need a clarification about news.post_id, from where are you grabbing this?
I have a PHP script which works with jQuery to provide search suggestions. It pulls results from a MySQL database. However, I only want 5 results to display at once for the letter the user has typed but it seems all of the results appear. Why could this be?
My code is:
<p id="searchresults"><?php
$db=new mysqli('localhost','username','password','database');
if(isset($_POST['queryString'])){
$queryString=$db->real_escape_string($_POST['queryString']);
if(strlen($queryString)>0){
$query = $db->query("SELECT * FROM search s WHERE name LIKE '%" . $queryString . "%'");
if($query){
while ($result = $query ->fetch_object()){
echo '<a href="/search/'.$result->name.'/1/">';
$name=$result->name;
echo ''.$name.'';
}
}
}
}
?></p>
I hope you can understand what I am trying to describe.
Change "SELECT * FROM search s WHERE name LIKE '%" . $queryString . "%'"
to "SELECT * FROM search s WHERE name LIKE '%" . $queryString . "%' LIMIT 5"
if you want to limit it to 5 results.
You need to add pagination code to your page:
There is the sample code:
<?php
// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("address") or die(mysql_error());
//This checks to see if there is a page number. If not, it will set it to page 1
if (!(isset($pagenum)))
{
$pagenum = 1;
}
//Here we count the number of results
//Edit $data to be your query
$data = mysql_query("SELECT * FROM topsites") or die(mysql_error());
$rows = mysql_num_rows($data);
//This is the number of results displayed per page
$page_rows = 4;
//This tells us the page number of our last page
$last = ceil($rows/$page_rows);
//this makes sure the page number isn't below one, or more than our maximum pages
if ($pagenum < 1)
{
$pagenum = 1;
}
elseif ($pagenum > $last)
{
$pagenum = $last;
}
//This sets the range to display in our query
$max = 'limit ' .($pagenum - 1) * $page_rows .',' .$page_rows;
//This is your query again, the same one... the only difference is we add $max into it
$data_p = mysql_query("SELECT * FROM topsites $max") or die(mysql_error());
//This is where you display your query results
while($info = mysql_fetch_array( $data_p ))
{
Print $info['Name'];
echo "<br>";
}
echo "<p>";
// This shows the user what page they are on, and the total number of pages
echo " --Page $pagenum of $last-- <p>";
// First we check if we are on page one. If we are then we don't need a link to the previous page or the first page so we do nothing. If we aren't then we generate links to the first page, and to the previous page.
if ($pagenum == 1)
{
}
else
{
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=1'> <<-First</a> ";
echo " ";
$previous = $pagenum-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$previous'> <-Previous</a> ";
}
//just a space
echo " -- ";
//This does the same as above, only checking if we are on the last page, and then generating the Next and Last links
if ($pagenum == $last)
{
}
else {
$next = $pagenum+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pagenum=$last'>Last ->></a> ";
}
?>
Source: www.twitter.com/ZishanAdThandar
i am a beginner. but I'm practicing a lot for few days with php mysql, and I am trying to use for loop to search an exploded string, one by one from mysql server.
Till now I have no results.
I'm giving my codes,
<?php
// Example 1
$var = #$_GET['s'] ;
$limit=500;
echo " ";
echo "$var";
echo " ";
$trimmed_array = explode(" ", $var);
echo "$trimmed_array[0]"; // piece1
echo " ";
$count= count($trimmed_array);
echo $count;
for($j=0;$j<$count;$j++)
{
e cho "$trimmed_array[$j]";;
echo " ";
}
echo " ";
for($i=0; $i<$count ; $i++){
$query = "select * from book where name like \"%$trimmed_array[$i]%\" order by name";
$numresults=mysql_query($query);
$numrows =mysql_num_rows($numresults);
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed_array[i] . "" returned zero results</p>";
}
if (empty($s)) {
$s=0;
}
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
echo "<p>You searched for: "" . $var . ""</p>";
echo "Results<br /><br />";
$count=1;
while ($row= mysql_fetch_array($result)) {
$name = $row["name"];
$publisher=$row["publisher"];
$total=$row["total"];
$issued=$row["issued"];
$available=$row["available"];
$category=$row["category"];
echo "<table border='1'><tr><td>$count)</td><td>$name </td><td>$publisher </td><td>$total </td><td>$issued </td><td>$available </td><td>$category </td></tr></table>" ;
$count++ ;
}
}
?>
In your case, you do for every record in your array ($trimmed_array) a new select. Thats not really good.
It would be better when you create just one select...
For example this:
// you need 1=1 for example when $i<count is false...
$baseQuery = "select * from book where 1=1";
$query = $baseQuery;
for($i=0; $i<$count ; $i++){
$query .= " OR name like ?";
}
// do your ordering:
$query.= " order by name";
But what does this "?" mean?
--> Do you know what sql-injection means? somebody could really easy put some information in this array wich could give any information about your database.. therefore you have to escape every userinput...
i like the mysqli package in php5. watch this example:
$query = "SELECT `id` FROM employees WHERE `name`=?";
// Setup parameter to be bound into query
$name = "Joey";
// Get instance of statement
$stmt = $mysqli->stmt_init();
// Prepare Query
if($stmt->prepare($query)){
// Bind Parameters [s for string]
$stmt->bind_param("s",$name);
// Execute statement
$stmt->execute();
// Bind result variables
$stmt->bind_result($employee_id);
// Fetch Value
$stmt->fetch();
// Echo results
echo "$name has an ID of $employee_id";
// Close Statement
$stmt->close();
}
Damn, your code really extremely crazy. Here you example about how to work with this:
<?php
$var = $_GET['s'];
$exp = explode(" ",$var);
$total = count($exp) - 1;
for($i = 0; $i <= $total; $i++) {
echo "Search for: " . $exp[$i] ."\n";
$sql = mysql_query("SELECT * FROM `book` WHERE `name` LIKE '%" . mysql_real_escape_string($exp[$i]) ."%'") or die(mysql_error());
if (mysql_fetch_num($sql) != 0) {
// Somthing found
}
}
?>
You have an error on line 25,
e cho "$trimmed_array[$j]";;
should be
echo "$trimmed_array[$j]";
Also, it seems that you are using $GET_[] variables, which are passed via the url string, which does not allow spaces. On line 15, you are splitting the array with explode(" ", $var);
I would also urge you, if you have not, look into sanitizing your database queries.
Okay, been thrashing around with this for longer than I care to think about!
I am trying to drag event data from mysql so that it displays the Event Name once and several products under that Event Name
For Example:
Event Name
product 1
product 2
product 3
What is currently happening is that the Event Name is displayed above each product, like this
Event Name
product 1
Event Name
product 2
Event Name
product 3
The PHP Code is:
<?php
// Get the search variable from URL
$var = #$_GET['q'] ;
$trimmed = trim($var); //trim whitespace from the stored variable
// rows to return
$limit=10;
// check for an empty string and display a message.
if ($trimmed == "")
{
echo "<p>Please enter a search...</p>";
exit;
}
// check for a search parameter
if (!isset($var))
{
echo "<p>We dont seem to have a search parameter!</p>";
exit;
}
//connect to your database ** EDIT REQUIRED HERE **
mysql_connect("xxxxxxxx","xxxxxxxx","xxxxx"); //(host, username, password)
//specify database ** EDIT REQUIRED HERE **
mysql_select_db("event_db") or die("Unable to select database"); //select which database we're using
// Build SQL Query
$query = "select * from event where event_name like \"%$trimmed%\"
order by event_name"; // EDIT HERE and specify your table and field names for the SQL query
$numresults=mysql_query($query);
$numrows=mysql_num_rows($numresults);
// If we have no results, offer a google search as an alternative
if ($numrows == 0)
{
echo "<h4>Results</h4>";
echo "<p>Sorry, your search: "" . $trimmed . "" returned zero results</p>";
// google
echo "<p><a href=\"http://www.google.com/search?q="
. $trimmed . "\" target=\"_blank\" title=\"Look up
" . $trimmed . " on Google\">Click here</a> to try the
search on google</p>";
}
// next determine if s has been passed to script, if not use 0
if (empty($s)) {
$s=0;
}
// get results
$query .= " limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
// display what the person searched for
echo "<p>You searched for: "" . $var . ""</p>";
// begin to show results set
echo "Results<br /><br />";
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
$title = $row["event_name"] . "<br />";
$title2 = $row["location"] . " - " . $row["style_name"] . "<br />";
echo "<b>$title</b>";
echo "$count $title2";
}
$currPage = (($s/$limit) + 1);
//break before paging
echo "<br />";
// next we need to do the links to other results
if ($s>=1) { // bypass PREV link if s is 0
$prevs=($s-$limit);
print " <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a>  ";
}
// calculate number of pages needing links
$pages=intval($numrows/$limit);
// $pages now contains int of pages needed unless there is a remainder from division
if ($numrows%$limit) {
// has remainder so add one page
$pages++;
}
// check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1) {
// not last page so give NEXT link
$news=$s+$limit;
echo " Next 10 >>";
}
$a = $s + ($limit) ;
if ($a > $numrows) { $a = $numrows ; }
$b = $s + 1 ;
echo "<p>Showing results $b to $a of $numrows</p>";
?>
Any thoughts would be greatly received.
simply use group_concat -> group_concat query performance
details -> http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
newbie including myself, please try google before posting the question
// now you can display the results returned
while ($row= mysql_fetch_array($result)) {
if($row["event_name"] != $lasteventname){
$title = $row["event_name"] . "<br />";
$lasteventname = $row["event_name"];
echo "<b>$title</b>";
}
$title2 = $row["location"] . " - " . $row["style_name"] . "<br />";
echo "$count $title2";
}