Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 11-28-2012, 06:19 AM   PM User | #1
darkangel2001lv
New to the CF scene

 
Join Date: Feb 2012
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
darkangel2001lv is an unknown quantity at this point
Help need with search and pagination script

hello everyone I have been working on this script for the better half of two weeks and can not figure out what is wrong.
Error tracking is set to E_ALL and nothing trips error.

PHP Code:
// check for a search parameter
if (!isset($_GET['SearchTerms'])) {
                echo 
"OOPS!!! It seems that you did not enter a search term. Please use your browsers back button and try your search again.";
                exit;
                
} else {
                
$var $_GET['SearchTerms'];
                
                echo 
"<p>You searched for: &quot;" $var "&quot;</p>"// for testing will be removed later. Checking to see if search term was submitted because no errors are being tripped.
                
                
$trimmed trim($var);
//trim whitespace from the stored variable


if ($trimmed == "") { // check for an empty string
                
                
exit;
                
} else {
                
$s $trimmed;
}


if (
strlen($s) < 2) {
                echo 
"Search terms must be longer than 2 characters. Please try your search again. "; { // Checking Search Term Length
                                
                                
                                // Checking SearchTerm for disallowed search terms
                                
if ($s == "bread") {
                                                echo 
"<p>Your search term is too broad. Please enter a more specific search term. ";
                                }
                                
                                if (
$s == "white") {
                                                echo 
"<p>Your search term is too broad. Please enter a more specific search term. ";
                                }
                                
                                if (
$s == "wheat") {
                                                echo 
"<p>Your search term is too broad. Please enter a more specific search term. ";
                                }
                                
                                if (
$s == "rye") {
                                                echo 
"<p>Your search term is too broad. Please enter a more specific search term. ";
                                }
                                
                }
}

$limit 10// rows to return


require_once('includes/connections/nfacts.php'); // Connect to the database.    

// Build SQL Query  
$query "SELECT link, keywords FROM products WHERE keywords like \"%$trimmed%\"  
    order by keywords"
;

$numresults mysql_query($query);

$numrows mysql_num_rows($numresults);

if (
$numrows == 0) {
                echo 
"<h4>Results</h4>";
                
                echo 
"<p>Sorry, your search: &quot;" $trimmed "&quot; returned zero results.Please try again. If you need help please <a href='../help/search-help.php'>click here.</a></p>";
}



// get results
$query .= " limit $s,$limit";

$result mysql_query($query) or die("There has been a system error. Please try your search again. If you keep getting this error please contact the webmaster of this site via our contact page or by clicking <a href='contact-webmaster.php'>here</a>");

// display what the person searched for
echo "<p>You searched for: &quot;" $var "&quot;</p>";

// begin to show results set
echo "Results";

$count $s;

// now you can display the results returned
while ($row mysql_fetch_array($result)) {
                
$title $row["link"];
                
                echo 
"$count.)$title";
                
                
$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);
                
                echo 
"<a href=\"$PHP_SELF?s=$prevs&SearchTerm=$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) {
                
$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 
"<a href=\"$PHP_SELF?s=$news&SearchTerm=$var\">Next 10 </a>";
}

$a $s + ($limit);
if (
$a $numrows) {
                
$a $numrows;
}

$b $s 1;

echo 
"<p>Showing results $b to $a of $numrows</p>"
Problem is script fails at query here and this message is displayed
PHP Code:
$query .= " limit $s,$limit";

$result mysql_query($query) or die("There has been a system error. Please try your search again. If you keep getting this error please contact the webmaster of this site via our contact page or by clicking <a href='contact-webmaster.php'>here</a>"); 
darkangel2001lv is offline   Reply With Quote
Old 11-28-2012, 08:35 AM   PM User | #2
Thyrosis
New Coder

 
Join Date: Nov 2012
Posts: 72
Thanks: 4
Thanked 11 Times in 11 Posts
Thyrosis is on a distinguished road
Can you change your $result line to

PHP Code:
$result mysql_query($query) or die(mysql_error() . "Full query: .".$query); 
This will display mysql's error message and give you the full query that's being tried. It will probably give you more details. My guess is the 'keywords like "%$trimmed%\"' bit, that doesn't seem quite right for some reason but can't put my finger on it.
Thyrosis is offline   Reply With Quote
Old 11-28-2012, 01:14 PM   PM User | #3
darkangel2001lv
New to the CF scene

 
Join Date: Feb 2012
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
darkangel2001lv is an unknown quantity at this point
Quote:
Originally Posted by Thyrosis View Post
My guess is the 'keywords like "/%$trimmed%\"' bit, that doesn't seem quite right for some reason but can't put my finger on it.
Same here just can not put my finger on it..... thank you for the help on viewing error will give that a try and see what happens.
darkangel2001lv is offline   Reply With Quote
Old 11-28-2012, 01:33 PM   PM User | #4
darkangel2001lv
New to the CF scene

 
Join Date: Feb 2012
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
darkangel2001lv is an unknown quantity at this point
Update


Changed this
PHP Code:
$result mysql_query($query) or die("There has been a system error. Please try your search again. If you keep getting this error please contact the webmaster of this site via our contact page or by clicking <a href='contact-webmaster.php'>here</a>"); 
to this to see what was going on
PHP Code:
$result mysql_query($query) or die(mysql_error() . "Full query: .".$query); 
Output was this
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'rolls,10' at line 2 Full query: .SELECT link, keywords FROM products WHERE keywords like 'rolls' order by keywords limit rolls,10
darkangel2001lv is offline   Reply With Quote
Old 11-28-2012, 01:38 PM   PM User | #5
Thyrosis
New Coder

 
Join Date: Nov 2012
Posts: 72
Thanks: 4
Thanked 11 Times in 11 Posts
Thyrosis is on a distinguished road
There you have it.

PHP Code:
if ($trimmed == "") { // check for an empty string 
                 
                
exit; 
                 
} else { 
                
$s $trimmed

$s is already set to rolls via $trimmed which is $_GET['searchTerms']. I'm guessing what you need is probably a $page = $_GET['s'], assuming $s is supposed to be $_GET['s']?
Thyrosis is offline   Reply With Quote
Old 11-28-2012, 02:51 PM   PM User | #6
darkangel2001lv
New to the CF scene

 
Join Date: Feb 2012
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
darkangel2001lv is an unknown quantity at this point
Quote:
Originally Posted by Thyrosis View Post
There you have it.

PHP Code:
if ($trimmed == "") { // check for an empty string 
                 
                
exit; 
                 
} else { 
                
$s $trimmed

I'm guessing what you need is probably a $page = $_GET['s'], assuming $s is supposed to be $_GET['s']?
problem was with typo being created in search query its self. am returning results now however same results are being displayed regardless what page your are on.

Here is the Updated script.

PHP Code:
// check for a search parameter
if (!isset($_GET['SearchTerms'])) {
    echo 
"OOPS!!! It seems that you did not enter a search term. Please use your browsers back button and try your search again.";
    exit;
    
} else {
    
$var $_GET['SearchTerms'];
    
    echo 
"<p>You searched for &quot;" $var "&quot;</p>"// for testing will be removed later. Checking to see if search term was submitted because no errors are being tripped.
    
    
$trimmed trim($var); //trim whitespace from the stored variable
    
}
if (
$trimmed == "") { // check for an empty string
    
    
exit;
    
} else {
    
$s $trimmed;
}


if (
strlen($s) < 2) {
    echo 
"Search terms must be longer than 2 characters. Please try your search again. "; { // Checking Search Term Length
        
        
        // Checking SearchTerm for disallowed search terms
        
if ($s == "bread") {
            echo 
"<p>Your search term is too broad. Please enter a more specific search term. ";
        }
        
        if (
$s == "white") {
            echo 
"<p>Your search term is too broad. Please enter a more specific search term. ";
        }
        
        if (
$s == "wheat") {
            echo 
"<p>Your search term is too broad. Please enter a more specific search term. ";
        }
        
        if (
$s == "rye") {
            echo 
"<p>Your search term is too broad. Please enter a more specific search term. ";
        }
        
    }
}

$limit 10// rows to return


require_once('includes/connections/nfacts.php'); // Connect to the database.    

// Build SQL Query  
$query "SELECT link, keywords FROM products WHERE keywords like \"%$trimmed%\" order by keywords";

$numresults mysql_query($query);

$numrows mysql_num_rows($numresults);

if (
$numrows == 0) {
    echo 
"<h4>Results</h4>";
    
    echo 
"<p>Sorry, your search: &quot;" $var "&quot; returned zero results. Please try again. If you need help please <a href='../help/search-help.php'>click here.</a></p>";
}



// get results
$query .= " limit $limit";

$result mysql_query($query) or die(mysql_error() . " Full query: ".$query);


// display what the person searched for
echo "<p>You searched for: &quot;" $var "&quot;</p>";

// begin to show results set
echo "Your Results";


// now you can display the results returned
while ($row mysql_fetch_array($result)) {
    
$title $row["link"];
    
    echo 
"<br /> $title";
    
}

$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);
    
    echo 
"<br /> <br /> <a href=\"$results.php?s=$prevs&SearchTerms=$var\"> See Prev 10 Results</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) {
    
$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 
"<br /> <br /> <a href=\"results.php?s=$news&SearchTerms=$var\">See Next 10 Results</a>";
}

$a $s + ($limit);
if (
$a $numrows) {
    
$a $numrows;
}

$b $s 1;

echo 
"<p>Showing results $b to $a of $numrows</p>"
darkangel2001lv is offline   Reply With Quote
Old 11-28-2012, 03:04 PM   PM User | #7
Thyrosis
New Coder

 
Join Date: Nov 2012
Posts: 72
Thanks: 4
Thanked 11 Times in 11 Posts
Thyrosis is on a distinguished road
Okay, I'm probably being blind here, but...

Where are you pulling $s as the page from the $_GET variable? The only $s I see in your code is being set to $trimmed. Which renders
PHP Code:
$prevs = ($s $limit); 
useless, as you are saying that $prevs = breadrolls (or any other searchTerm) - 10.

By the way, a limit should be set as "LIMIT x, y" (where x = from and y = to). Currently it only says "LIMIT y" which is the same as "give me the first 10 results".

From the MySQL manual at http://dev.mysql.com/doc/refman/5.5/en/select.html
Code:
SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows
SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15
SELECT * FROM tbl LIMIT 95,18446744073709551615; #retrieves all rows from the 96th row to the last:

Last edited by Thyrosis; 11-28-2012 at 03:15 PM.. Reason: added MySQL manual link
Thyrosis is offline   Reply With Quote
Old 11-30-2012, 05:15 AM   PM User | #8
c1lonewolf
Regular Coder

 
Join Date: Sep 2002
Posts: 216
Thanks: 0
Thanked 11 Times in 11 Posts
c1lonewolf is an unknown quantity at this point
Question...does php really run this?
Code:
if (strlen($s) < 2) {
    echo "Search terms must be longer than 2 characters. Please try your search again. "; { // Checking Search Term Length
I mean the semicolon ends the line so why the next brace? There's no if statement etc....Just wondering.
__________________
NO Limits!!
c1lonewolf is offline   Reply With Quote
Old 11-30-2012, 06:14 PM   PM User | #9
darkangel2001lv
New to the CF scene

 
Join Date: Feb 2012
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
darkangel2001lv is an unknown quantity at this point
latest update have redone whole search script work in progress and have changed over to PDO which is brand new to me

have a few issues

Issue 1

Error report states that search_result is not defined however it is defined a few line before
Error1
Quote:
An error occurred in script '/home/content/84/8829884/html/test/results.php' on line 269:
<br />Undefined variable: search_result
<br />Date/Time: 11-30-2012 11:05:19
<br />
<pre>Array
(
[GLOBALS] => Array
*RECURSION*
[_POST] => Array
(
)

[_GET] => Array
(
[SearchTerms] => rolls
[submit] => Search
)

[_COOKIE] => Array
(
[__utma] => 107246494.1524893141.1353092377.1354224105.1354293727.26
[__utmz] => 107246494.1353095668.2.2.utmcsr=mysite.com|utmccn=(referral)|utmcmd=referral|utmcct=/
[_pk_id_1_caea] => d685a9a208592d3e.1353339832.19.1354298751.1354294016.
[__utmb] => 107246494.21.10.1354293727
[__utmc] => 107246494
[_pk_ses_1_caea] => *
)

[_FILES] => Array
(
)

[live] => 1
[email] => error@mysite.com
[errors] => Array
(
[0] => There was a database error. Please contact the Webmaster of this site via our contact page if this problem persists,
)

[feedback] => Array
(
)

[s] => rolls
[word_check] => Array
(
[0] => bread
[1] => white
[2] => wheat
[3] => rye
)

[limit] => 10
[host] => mysite.com
[dbname] => nfacts
[dsn] => mysql:dbname=nfacts;host=mysitecom
[db] => PDO Object
(
)

[count_stmt] => PDOStatement Object
(
[queryString] => SELECT COUNT(*) AS rowcount FROM products WHERE keywords like :search
)

[stmt] => PDOStatement Object
(
[queryString] => SELECT link, keywords FROM products WHERE keywords like :search ORDER BY keywords LIMIT ffset, :count
)

[count_params] => Array
(
[search] => rolls
)

[params] => Array
(
[search] => rolls
[offset] => 10
[count] => 20
)

[err] => There was a database error. Please contact the Webmaster of this site via our contact page if this problem persists
)
</pre>
<br />
Issue 2

Error2
Quote:
An error occurred in script '/home/content/84/8829884/html/test/results.php' on line 269:
<br />Invalid argument supplied for foreach()
<br />Date/Time: 11-30-2012 11:05:19
<br /><pre>Array
(
[GLOBALS] => Array
*RECURSION*
[_POST] => Array
(
)

[_GET] => Array
(
[SearchTerms] => rolls
[submit] => Search
)

[_COOKIE] => Array
(
[__utma] => 107246494.1524893141.1353092377.1354224105.1354293727.26
[__utmz] => 107246494.1353095668.2.2.utmcsr=mysite.com|utmccn=(referral)|utmcmd=referral|utmcct=/
[_pk_id_1_caea] => d685a9a208592d3e.1353339832.19.1354298751.1354294016.
[__utmb] => 107246494.21.10.1354293727
[__utmc] => 107246494
[_pk_ses_1_caea] => *
)

[_FILES] => Array
(
)

[live] => 1
[email] => error@mysite.com
[errors] => Array
(
[0] => There was a database error. Please contact the Webmaster of this site via our contact page if this problem persists,
)

[feedback] => Array
(
)

[s] => rolls
[word_check] => Array
(
[0] => bread
[1] => white
[2] => wheat
[3] => rye
)

[limit] => 10
[host] =>MYSITE.com
[dbname] => nfacts
[dsn] => mysql:dbname=nfacts;host=mysite.com
[db] => PDO Object
(
)

[count_stmt] => PDOStatement Object
(
[queryString] => SELECT COUNT(*) AS rowcount FROM products WHERE keywords like :search
)

[stmt] => PDOStatement Object
(
[queryString] => SELECT link, keywords FROM products WHERE keywords like :search ORDER BY keywords LIMIT ffset, :count
)

[count_params] => Array
(
[search] => rolls
)

[params] => Array
(
[search] => rolls
[offset] => 10
[count] => 20
)

[err] => There was a database error. Please contact the Webmaster of this site via our contact page if this problem persists,
)
</pre>
<br />
see next post

Last edited by darkangel2001lv; 11-30-2012 at 08:03 PM..
darkangel2001lv is offline   Reply With Quote
Old 11-30-2012, 06:28 PM   PM User | #10
darkangel2001lv
New to the CF scene

 
Join Date: Feb 2012
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
darkangel2001lv is an unknown quantity at this point
Full Script
PHP Code:
 <?php


# I like collecting errors throughout the page to provide feedback
# Same with other feedback, although I keep them separate
$errors   = array();
$feedback = array();

/* First off, I'd try to get as many checks as possible into one single
 * For example, instead of checking both "no input" and "less than 3 characters" and informing
 * user of each one separately, just check string length and inform user: has to be at least 3 chars
 *
 * Also note that $_GET['SearchTerms'] will always be set if the form was posted properly,
 * even if the field was left empty. Thus, in the original case of !isset($_GET['SearchTerm'])
 * it would have been better with !empty($_GET['SearchTerm'])
 */

# To make sure the array element is set, using the ternary operator ?:
# Works like this
# (is this value true) ? (then return this value) : (else return this value)
$_GET['SearchTerms'] = !isset($_GET['SearchTerms']) ? '' trim($_GET['SearchTerms']);

# Now that we've trimmed the search, check for string length using mb_strlen (you are using utf-8 aren't you?)
if (mb_strlen($_GET['SearchTerms']) < 2) {
        
$errors[] = "<p>Search terms must be longer than 2 characters. Please try your search again. ";
        
        
} else {
        
$s $_GET['SearchTerms'];
        
        
// Checking SearchTerm for disallowed search terms
        # Easier way to check for these values in a more condensed form
        
$word_check = array(
                
'bread',
                
'white',
                
'wheat',
                
'rye'
        
);
        if (
in_array($s$word_check)) {
                
$feedback[] = "<p>Your search term is too broad. Please enter a more specific search term. ";
        }
        
        
$limit 10// rows to return
        
        
        // Build SQL Query
        
        
        # Connecting to the DB using PDO 
        
$host   'mysite.com';
        
$dbname 'nfacts';
        
$dsn    "mysql:dbname=$dbname;host=$host";
        
$db     = new PDO($dsn'user''password');
        
        
        
$count_stmt $db->prepare('SELECT COUNT(*) AS rowcount FROM products WHERE keywords like :search');
        
# The query fetching the product links will also need "LIMIT offset, count"
        
$stmt       $db->prepare('SELECT link, keywords FROM products WHERE keywords like :search ORDER BY keywords LIMIT :offset, :count');
        
        
# search here will replace :search in the query
        
$count_params = array(
                
'search' => $s
        
);
        
# I put in fixed values for offset and count, leaving for you to deal with the pagination :)
        
$params       = array(
                
'search' => $s,
                
'offset' => 10,
                
'count' => 20
        
);
        
        
# Then you use matching name, other_name (with or without :) as array keys to pass the data
        
if (!$stmt->execute($params)) {
                
$errors[] = 'There was a database error. Please contact the Webmaster of this site via our contact page if this problem persists';
                
                
        } else {
                
# This returns all selected rows into an associative array
                
$search_result $stmt->fetchAll(PDO::FETCH_ASSOC);
                
                
                
///// define $search_result here??? /////
                
$rows = array(
                        
$search_results
                
);
                
                
                
                
$count_stmt->execute($params);
                
# Whereas fetchAll fetches all rows at once, fetch fetches one row at the time
                # and here we only have one row anyway
                
$row      $count_stmt->fetch(PDO::FETCH_ASSOC);
                
$rowcount $row['rowcount'];
                
                
# Add search result number independently if that was 0 or any other number
                
$feedback[] = sprintf('Your search found %d results'$numrows);
                
                if (
$numrows == 0) {
                        
$feedback[] = sprintf('Sorry, your search: "%s" returned zero results. Please try again. If you need help please <a href="%s">click here.</a></p>'$sBASE HELPDIR 'search-help.php');
                        
                        
                        
                        
                }
        }
}

# But before you get to actual content, let's give the user errors and feedback, if any
# Which ought to start with errors
foreach ($errors as $err) {
        echo 
$err "<br />";
}
foreach (
$feedback as $f) {
        echo 
$f "<br />";
}


// now you can display the results returned


foreach ($rows as $row) {
        
printf($row['link']);
}



#  followed by pagination 
# echo "here..." ;



?>

Last edited by darkangel2001lv; 11-30-2012 at 07:58 PM..
darkangel2001lv is offline   Reply With Quote
Old 11-30-2012, 06:30 PM   PM User | #11
Thyrosis
New Coder

 
Join Date: Nov 2012
Posts: 72
Thanks: 4
Thanked 11 Times in 11 Posts
Thyrosis is on a distinguished road
I've never worked with PDO I'm afraid, so someone else will have to take over... Sorry!
Thyrosis is offline   Reply With Quote
Old 11-30-2012, 07:12 PM   PM User | #12
darkangel2001lv
New to the CF scene

 
Join Date: Feb 2012
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
darkangel2001lv is an unknown quantity at this point
Quote:
Originally Posted by Thyrosis View Post
I've never worked with PDO I'm afraid, so someone else will have to take over... Sorry!
Me either lol, which is why i am having issues lol
darkangel2001lv is offline   Reply With Quote
Old 12-03-2012, 04:42 PM   PM User | #13
darkangel2001lv
New to the CF scene

 
Join Date: Feb 2012
Posts: 9
Thanks: 0
Thanked 0 Times in 0 Posts
darkangel2001lv is an unknown quantity at this point
Anyone willing to help me with PDO?
darkangel2001lv is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 05:14 AM.


Advertisement
Log in to turn off these ads.