Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 7 of 7
  1. #1
    New Coder
    Join Date
    Sep 2012
    Posts
    89
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Help in Making My Search Page functional

    I have created a search.php file meant to receive input from a search form. The php in the search.php file (see below) should search for the inputted text in three columns on a table: Title, Post and Date. If it finds matches, it lists only the titles of the rows in which the word being searched has been found. If the searches are many, the first twenty appear on page 1, the next 20 on page 2 and so on. If no matches are found, the php code echoes "No matches found."

    I have tried coming up with the following code but it isn't working as I'd want it to. First, I excluded the Date column from the searchable areas because the code was generating errors when I included Date column. Secondly, the php is listing every title of rows in my table. Please help.

    Code:
    <?php
    
    if(isset($_POST['submit'])){
    if(isset($_GET['go'])){
    if(preg_match("/[A-Z | a-z]+/", $_POST['name'])){
    $name=$_POST['name'];
    
    // Include database connection settings
    include('config.inc'); 
    
    //-select the database to use
    $mydb=mysql_select_db("a3763404_posts");
    
    $Title =$row['Title'];
    $Post=$row['Post'];
    $Date=$row['Date'];
    $Index = $row['Index'];
    
    //-query the database table
    $sql="SELECT Title, Post FROM entries WHERE Title LIKE '%" . $Title . "%' OR Post LIKE '%" . $Post ."%'";
    
    //-run the query against the mysql query function
    $result=mysql_query($sql);
    
    //-count results
    
    $numrows=mysql_num_rows($result);
    
    echo "<p>" .$numrows . " Results found for " . stripslashes($name) . "</p>"; 
    
    //-create while loop and loop through result set
    while($row=mysql_fetch_array($result)){
    
    $Title =$row['Title'];
    $Post=$row['Post'];
    $Date=$row['Date'];
    $Index = $row['Index'];
    	
    //-display the result of the array
    
    echo "<ul>\n"; 
    echo '<li><a href="selected_post.php?Index='.$Index.'">' .$row['Title'] . '</a></li>';
    echo "</ul>";
    }
    }
    else{
    echo "<p>Please enter a search query</p>";
    }
    }
    }
    
    
    ?>

  • #2
    New Coder
    Join Date
    Sep 2012
    Posts
    89
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Question What's wrong with this code

    What's wrong with this searching functionality code? It is supposed to fetch the string to be searched through POST method. First, it checks whether there was an input. If not, it displays a message.

    If there was an input, it searches three database columns for matches. If no matches are found, it displays a message. If otherwise, it indicates the number of matches and shows the first twenty matches on Page 1, and another 20 in page 2, and so on.

    Code:
    <?php
    
    
    $name=$_POST['name'];
    if ($name="")
     {
      echo "Oops! You didn't type anything to search. Please insert something to search";
     }
    else
     {
      // Include database connection settings
    include('config.inc'); 
    
    //-select the database to use
    $mydb=mysql_select_db("a3763404_posts");
    
    $sql="SELECT * FROM entries
    WHERE Title LIKE '%". $name ."%' OR Post LIKE '% ". $name . "%' OR Date Like'%" . $name ."%'";
    //-run the query against the mysql query function
    $result=mysql_query($sql);
    
    //-count results
    
    $numrows=mysql_num_rows($result);
    
    echo "<p>" .$numrows . " Results found for " . stripslashes($name) . "</p>"; 
    
    $numberOfPages = 100;
    $resultsPerPage = 20;
    $startResults = ($page - 1) * $resultsPerPage;
    $numberOfRows = $numrows;
    $totalPages = ceil($numberOfRows / $resultsPerPage);
    
    $query = mysql_query("SELECT * FROM entries LIMIT $startResults, $resultsPerPage") or die ('Error: '.mysql_error ()); 
    
    while ($output = mysql_fetch_array($query))
    { 
        echo '<a href="selected_post.php?Index='.$output['Index'].'">' .$output['Title'].'</a><br>'; 
    }
    
    $halfPages = floor($numberOfPages / 2);
    $range = array('start' => 1, 'end' => $totalPages);
    $isEven = ($numberOfPages % 2 == 0);
    $atRangeEnd = $totalPages - $halfPages;
    
    if($isEven) $atRangeEnd++;
    
    if($totalPages > $numberOfPages)
    {
    	if($page <= $halfPages)
    		$range['end'] = $numberOfPages;
    	elseif ($page >= $atRangeEnd)
    		$range['start'] = $totalPages - $numberOfPages + 1;
    	else
    	{
    		$range['start'] = $page - $halfPages;
    		$range['end'] = $page + $halfPages;
    		if($isEven) $range['end']--;
    	}
    }
    
    if($page > 1)
    	echo '<a href="?page='.($page - 1).'">&laquo;</a>&nbsp';
    
    for ($i = $range['start']; $i <= $range['end']; $i++)
    {
    	if($i == $page)
    		echo '<strong>'.$i.'</strong>&nbsp;';
    	else
    		echo '<a href="?page='.$i.'">'.$i.'</a>&nbsp;';
    }
    if ($page < $totalPages)
    	echo '<a href="?page='.($page + 1).'">&raquo;</a>&nbsp;';
    }
    ?>

  • #3
    Regular Coder Arcticwarrio's Avatar
    Join Date
    May 2012
    Location
    UK
    Posts
    721
    Thanks
    20
    Thanked 84 Times in 84 Posts
    you have no LIMIT on your query again

    PHP Code:
    //-query the database table
    $sql="SELECT Title, Post FROM entries WHERE Title LIKE '%" $Title "%' OR Post LIKE '%" $Post ."%' LIMIT $startResults, $resultsPerPage"
    Last edited by Arcticwarrio; 03-23-2013 at 02:55 AM.
    There are 10 types of people on CodingForums,
    Those who understand Binary and those who dont.
    Get Cloud Hosting now from only£59 / month

  • #4
    Regular Coder Arcticwarrio's Avatar
    Join Date
    May 2012
    Location
    UK
    Posts
    721
    Thanks
    20
    Thanked 84 Times in 84 Posts
    p.s. Date is a reserved word you'll need backsticks when referencing it `date`
    There are 10 types of people on CodingForums,
    Those who understand Binary and those who dont.
    Get Cloud Hosting now from only£59 / month

  • #5
    New Coder
    Join Date
    Sep 2012
    Posts
    89
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Exclamation Why is this code still generating errors?

    I have created a search.php file meant to receive input from a search form. The php in the search.php file (see below) should search for the inputted text in three columns on a table: Title, Post and Date. If it finds matches, it lists only the titles of the rows in which the word being searched has been found. If the searches are many, the first twenty appear on page 1, the next 20 on page 2 and so on. If no matches are found, the php code echoes "No matches found."

    I have tried coming up with the following code but it isn't working as I'd want it to. First, I excluded the Date column from the searchable areas because the code was generating errors when I included Date column. Secondly, the php is listing every title of rows in my table.

    I have not understood Arcticwarrio statement that "Date is a reserved word you'll need backsticks when referencing it `date`". What am I meant to do with the Date word?

    Please help.

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <!-- saved from url=(0020)http://ngishili.com/ -->
    <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en-US"><head profile="http://gmpg.org/xfn/11"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    
    
    <title>Diary Polly</title>
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="style.css" type="text/css" media="screen">
    <link rel="alternate" type="application/rss+xml" title=" RSS Feed" href="http://ngishili.com/?feed=rss2">
    <link rel="pingback" href="http://ngishili.com/xmlrpc.php">
    
    <script type="text/javascript" src="./**** and Bull Stories_files/jquery.js"></script>
    <link rel="EditURI" type="application/rsd+xml" title="RSD" href="http://ngishili.com/xmlrpc.php?rsd">
    <link rel="wlwmanifest" type="application/wlwmanifest+xml" href="http://ngishili.com/wp-includes/wlwmanifest.xml"> 
    <meta name="generator" content="WordPress 3.4.2">
    
    	<!-- Clean Archives Reloaded v3.1.10 | http://www.viper007bond.com/wordpress-plugins/clean-archives-reloaded/ -->
    	<style type="text/css">.car-collapse .car-yearmonth { cursor: s-resize; } </style>
    	<script type="text/javascript">
    		/* <![CDATA[ */
    			jQuery(document).ready(function() {
    				jQuery('.car-collapse').find('.car-monthlisting').hide();
    				jQuery('.car-collapse').find('.car-monthlisting:first').show();
    				jQuery('.car-collapse').find('.car-yearmonth').click(function() {
    					jQuery(this).next('ul').slideToggle('fast');
    				});
    				jQuery('.car-collapse').find('.car-toggler').click(function() {
    					if ( 'Expand All' == jQuery(this).text() ) {
    						jQuery(this).parent('.car-container').find('.car-monthlisting').show();
    						jQuery(this).text('Collapse All');
    					}
    					else {
    						jQuery(this).parent('.car-container').find('.car-monthlisting').hide();
    						jQuery(this).text('Expand All');
    					}
    					return false;
    				});
    			});
    		/* ]]> */
    	</script>
    <style type="text/css" media="screen">
    ul li{
      list-style-type:none;
    }
    </style>
    </head>
    <body><div id="container">
      <div id="search">
         <form  method="post" action="search.php"  id="searchform"> 
          <input  type="text" name="name"> 
          <input type="submit" id="searchsubmit"  name = "submit" class="btnSearch" value="Find It »">
        </form>
         
      </div>
      <div id="menu-holder"><ul id="menu">
      <li id="archives"><a href="/archives.php"></a></li>
      <li id="subscribe"><a href="/subscribe.php"></a></li>
      <li id="about_me"><a href="/about_me.php"></a></li>
    </ul>
    </div>
      <div id="title">
        <h2><a href="./**** and Bull Stories_files/**** and Bull Stories.htm"></a></h2>
        </div>
    </div>
    <div id="content">
      <div class="col01">
            <div class="post" id="post-1479">
          <h3>
          Search Results
      
    </h3>
          <div class="post-inner">
            <div class="date-tab"><span class="month">
    
    </span><span class="day"></span></div>
            <div class="thumbnail"></div>
           <?php
    
    
    $name=$_POST['name'];
    if ($name="")
     {
      echo "Oops! You didn't type anything to search. Please insert something to search";
     }
    else
     {
      // Include database connection settings
    include('config.inc'); 
    
    //-select the database to use
    $mydb=mysql_select_db("a3763404_posts");
    
    //-query the database table
    $sql="SELECT Title, Post, Date FROM entries WHERE Title LIKE '%" . $name . "%' OR Post LIKE '%" . $name ."%' OR Date LIKE '%" . $name ."%'LIMIT $startResults, $resultsPerPage";  
    
    //-run the query against the mysql query function
    $result=mysql_query($sql);
    
    //-count results
    
    $numrows=mysql_num_rows($result);
    
    echo "<p>" .$numrows . " Results found for " . stripslashes($name) . "</p>"; 
    
    $numberOfPages = 100;
    $resultsPerPage = 20;
    $startResults = ($page - 1) * $resultsPerPage;
    $numberOfRows = $numrows;
    $totalPages = ceil($numberOfRows / $resultsPerPage);
    
    $query = mysql_query("SELECT * FROM entries LIMIT $startResults, $resultsPerPage") or die ('Error: '.mysql_error ()); 
    
    while ($output = mysql_fetch_array($query))
    { 
        echo '<a href="selected_post.php?Index='.$output['Index'].'">' .$output['Title'].'</a><br>'; 
    }
    
    $halfPages = floor($numberOfPages / 2);
    $range = array('start' => 1, 'end' => $totalPages);
    $isEven = ($numberOfPages % 2 == 0);
    $atRangeEnd = $totalPages - $halfPages;
    
    if($isEven) $atRangeEnd++;
    
    if($totalPages > $numberOfPages)
    {
    	if($page <= $halfPages)
    		$range['end'] = $numberOfPages;
    	elseif ($page >= $atRangeEnd)
    		$range['start'] = $totalPages - $numberOfPages + 1;
    	else
    	{
    		$range['start'] = $page - $halfPages;
    		$range['end'] = $page + $halfPages;
    		if($isEven) $range['end']--;
    	}
    }
    
    if($page > 1)
    	echo '<a href="?page='.($page - 1).'">&laquo;</a>&nbsp';
    
    for ($i = $range['start']; $i <= $range['end']; $i++)
    {
    	if($i == $page)
    		echo '<strong>'.$i.'</strong>&nbsp;';
    	else
    		echo '<a href="?page='.$i.'">'.$i.'</a>&nbsp;';
    }
    if ($page < $totalPages)
    	echo '<a href="?page='.($page + 1).'">&raquo;</a>&nbsp;';
    }
    ?>
    
    </div>
          
        </div>  
          
          
        
                  
            
            <div class="post-nav"><span class="previous"></span><span class="next"></span></div>
          </div>
      <div class="col02">
        <div class="recent-posts">
        	    <ul>
        <li>
        <?php 
     
                  // Include database connection settings
                  include('config.inc');
      
                  $result = mysql_query("SELECT * FROM entries order by Date DESC limit 0,8");    
      
                  while($row = mysql_fetch_assoc($result))  
                     {                 
                        $Index=$row['Index']; 
                        echo '<a href="selected_post.php?Index='.$Index.'">' .$row['Title'] . '</a>';
                         echo ' ' . $row['Date'] . '';
                     
                     }  
         
      
              ?>
        <br>
        <span class="listMeta"></span></a></li>
        </ul>
            <ul>
        <li><br>
        <span class="listMeta"></span></a></li>
        </ul>
            <ul>
        <li><br>
        <span class="listMeta"></span></a></li>
        </ul>
            <ul>
        <li><br>
        <span class="listMeta"></span></a></li>
        </ul>
            <ul>
        <li><br>
        <span class="listMeta"></span></a></li>
        </ul>
            <ul>
        <li><br>
        <span class="listMeta"></span></a></li>
        </ul>
            <ul>
        <li><br>
        <span class="listMeta"></span></a></li>
        </ul>
            <ul>
        <li><br>
        <span class="listMeta"></span></a></li>
        </ul>
            <ul>
        <li><br>
        <span class="listMeta"></span></a></li>
        </ul>
            <ul>
        <li><br>
        <span class="listMeta"></span></a></li>
        </ul>
            </div>
        <div class="postit-bottom"></div>
        <div class="categories-upper"></div>
    <div class="categories">
      <ul>
    	
    	<li></li>
    	<li></li>
    	<li></li>
    
    </ul>
    
    </div>
    <div class="categories-btm"></div>
    
    <div class="side-meta">
      <ul>
            <li>
          <a href="http://ngishili.com/wp-login.php"></a>    </li>
        <li><a href="http://validator.w3.org/check/referer" title="This page validates as XHTML 1.0 Transitional"> <abbr title="eXtensible HyperText Markup Language"></abbr></a></li>
        <li><a href="http://gmpg.org/xfn/"><abbr title="XHTML Friends Network"></abbr></a></li>
        <li><a href="http://wordpress.org/" title="Powered by WordPress, state-of-the-art semantic personal publishing platform."></a></li>
          </ul>
    </div>  </div>
      <br clear="all">
    </div>
    <div id="footer-holder">
      <div class="footer"></div>
      <div class="txt"> <p> <strong>Name:</strong> Thuita J. Maina<br>
            <strong>Nationality:</strong> Kenyan <br>
            <strong>Location:</strong> Kiserian, Rift Valley, Kenya<br>
            <strong>Says:</strong> I always try to remind myself of how special I am.</p>
          <p> <a href="contact.php" target="_blank"><strong>Click Here To Contact 
            Thuita</strong></a> </p>
              </div>
      <span class="smashing"><a href="http://jobs.smashingmagazine.com/">Smashing Magazine</a></span> <span class="rss"><a href="http://ngishili.com/?feed=rss2">RSS</a></span></div>
    </body>
    </html>

  • #6
    New Coder
    Join Date
    Sep 2012
    Posts
    89
    Thanks
    18
    Thanked 0 Times in 0 Posts

    Thumbs down Why this errors?

    I'm getting the following errors from my php file:

    Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /home/a3763404/public_html/search.php on line 102
    Error: 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 '-20, 20' at line 1
    The concerned PHP Code is:

    Code:
    <?php
    
    
    $name=$_POST['name'];
    if ($name="")
     {
      echo "Oops! You didn't type anything to search. Please insert something to search";
     }
    else
     {
      // Include database connection settings
    include('config.inc'); 
    
    //-select the database to use
    $mydb=mysql_select_db("a3763404_posts");
    
    //-query the database table
    $sql="SELECT Title, Post, Date FROM entries WHERE Title LIKE '%" . $name . "%' OR Post LIKE '%" . $name ."%' OR Date LIKE '%" . $name ."%'LIMIT $startResults, $resultsPerPage";  
    
    //-run the query against the mysql query function
    $result=mysql_query($sql);
    
    //-count results
    
    $numrows=mysql_num_rows($result);
    
    echo "<p>" .$numrows . " Results found for " . stripslashes($name) . "</p>"; 
    
    $numberOfPages = 100;
    $resultsPerPage = 20;
    $startResults = ($page - 1) * $resultsPerPage;
    $numberOfRows = $numrows;
    $totalPages = ceil($numberOfRows / $resultsPerPage);
    
    $query = mysql_query("SELECT * FROM entries LIMIT $startResults, $resultsPerPage") or die ('Error: '.mysql_error ()); 
    
    while ($output = mysql_fetch_array($query))
    { 
        echo '<a href="selected_post.php?Index='.$output['Index'].'">' .$output['Title'].'</a><br>'; 
    }
    
    $halfPages = floor($numberOfPages / 2);
    $range = array('start' => 1, 'end' => $totalPages);
    $isEven = ($numberOfPages % 2 == 0);
    $atRangeEnd = $totalPages - $halfPages;
    
    if($isEven) $atRangeEnd++;
    
    if($totalPages > $numberOfPages)
    {
    	if($page <= $halfPages)
    		$range['end'] = $numberOfPages;
    	elseif ($page >= $atRangeEnd)
    		$range['start'] = $totalPages - $numberOfPages + 1;
    	else
    	{
    		$range['start'] = $page - $halfPages;
    		$range['end'] = $page + $halfPages;
    		if($isEven) $range['end']--;
    	}
    }
    
    if($page > 1)
    	echo '<a href="?page='.($page - 1).'">&laquo;</a>&nbsp';
    
    for ($i = $range['start']; $i <= $range['end']; $i++)
    {
    	if($i == $page)
    		echo '<strong>'.$i.'</strong>&nbsp;';
    	else
    		echo '<a href="?page='.$i.'">'.$i.'</a>&nbsp;';
    }
    if ($page < $totalPages)
    	echo '<a href="?page='.($page + 1).'">&raquo;</a>&nbsp;';
    }
    ?>
    The PHP code meant to receive input from a search form. The php in the search.php file (see below) should search for the inputted text in three columns on a table: Title, Post and Date. If it finds matches, it lists only the titles of the rows in which the word being searched has been found. If the searches are many, the first twenty appear on page 1, the next 20 on page 2 and so on. If no matches are found, the php code echoes "No matches found."

    I have tried coming up with the following code but it isn't working as I'd want it to. First, I excluded the Date column from the searchable areas because the code was generating errors when I included Date column. Secondly, the php is listing every title of rows in my table.

    I have not understood Arcticwarrio statement that "Date is a reserved word you'll need backsticks when referencing it `date`". What am I meant to do with the Date word?

    Please help. Thank you.

  • #7
    Regular Coder
    Join Date
    Nov 2012
    Posts
    115
    Thanks
    7
    Thanked 12 Times in 12 Posts
    Error: 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 '-20, 20' at line 1
    This means you have a logical error somewhere. You are setting your result to be between -20 and 20, which can't be true. You'll have to start from 0.

    Code:
    $startResults = ($page - 1) * $resultsPerPage;
    if $page isn't set, it'll default to 0. 0-1 = -1. -1 * 20 = -20.

    Is that of any use to you?


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •