PHP - Search Form Not Working
I wrote the search form below to enable users search other users of a site based on certain criteria like age, race etc. Then I wrote the php script beneath, to execute that search. I decided to make the script very simple, searching only for one criterion for now (ethnicity). So even though I have several fields in the search form, I wrote the script to process only one of those fields(ethnicity). So basically, the script searches all records for members on the site from two tables called images and members(the members table has an "ethnicity column"), who meet the user's ethnicity preference and returns certain columns for all members who meet that preference. Well when I click the submit button, all I get is "Form not submitted". I added that form not submitted clause at the end of the script just after I had tweaked the script in every way possible but got nothing but a blank page every time I submitted the form. So take a look people and tell me what could be going wrong here. Appreciate any help. Code: [Select]
<form id="search_profiles_form" action= "profile_search.php"> Seeking A: <select name= "sex"> <option value= "man">Man</option> <option value= "woman">Woman</option> <option value= "both">Both</option> <select> <p> <tab> Age Range: <?php print '<select name= "min_age">'; for ($age = 18; $age <= 99; $age++) { print "\n<option value=\"$age\">$age</option>"; } print '</select>'; ?> </tab> <tab> and: <?php print '<select name= "max_age">'; for ($age = 18; $age <= 99; $age++) { print "\n<option value=\"$age\">$age</option>"; } print '</select>'; ?> </tab> </p> <p>Distance: <select name= "distance"> <option name="5">Within 5 Miles</option> <option name="10">Within 10 Miles</option> <option name="50">Within 50 Miles</option> <option name="100">Within 100 Miles</option> <option name="250">Within 250 Miles</option> <option name="any">Beyond 250 Miles</option> </select> </p> <p>Ethnicity: <select name= "ethnicity"> <option name="black">Black/African Descent</option> <option name="white">Caucasian?European Descent</option> <option name="latino">Hispanic Non White</option> <option name="asian">Asian Descent</option> <option name="native_american">Native American</option> <option name="pacific_islander">Pacific Islander</option> <option name="indian">Indian Descent</option> <option name="middle_east">Middle Eastern</option> <option name="other">Other</option> </select> </p> <p>Last Active: <select name= "last_active"> <option name="0">Online Now</option> <option name="1">1 Hr Ago</option> <option name="5">5 Hrs Ago</option> <option name="24">24 Hrs Ago</option> <option name="1wk">1 Week Ago</option> <option name="3wk">Over 3 Weeks Ago</option> </select> </p> <input type="hidden" name="submitted" value="TRUE"/> <p> <input type ="submit" value="Search!"/> </p> </form> And here goes the php script. Code: [Select] <?php //address error handling ini_set ('display_errors', 1); error_reporting (E_ALL & ~E_NOTICE); //authenticate user require('auth.php'); if (isset($_POST['submitted'])) { // Connect to the database. require_once ('config.php'); //Query the database. $sql = "SELECT * FROM members INNER JOIN images ON members.member_id = images_member_id WHERE members.ethnicity = '{$_POST['ethnicity']}' AND images.cartegory = 'main' "; $query = mysql_query($sql); //Check for success here. if(!$query) { trigger_error("SQL query $sql failed: " . mysql_error(), E_ERROR); // Handle as desired }else{ //If query is valid. if(mysql_num_rows($query) > 0){ while ($row = mysql_fetch_assoc($query)){ //Redirect to search results page. echo $_POST['ethnicity']; echo $row['member_id']; echo $_SESSION['id']; echo $row['image']; } }else {//No rows returned. echo 'No results match this search query.' ; } }//End of else if query is valid. }else{ echo "form not submitted";} ?> Similar Tutorialshello all, im running a search and it will work if i search one letter, but not anything more. any ideas? Code: [Select] <?php include("style.php"); //If we submitted the form if(isset($_POST['submitMe'])) { echo '<div id="musicinfo" align="center"> <table border="0" width="100%" cellspacing="0" cellpadding="0"> <tr> <td align="center"> <form action="" method="POST"> <center> <input type="text" name="name" size="24"> <input type="submit" value="Search" name="submitMe"> </form> </td> </tr> </table> </div>'; $hmm = simplexml_load_file('http://www.durhamit.ca:8181/1.0/?method=database.search&searcharg='.$_POST['name'] .''); foreach($hmm->tracks->track as $tracks) { $artist = $tracks->artist; $title = $tracks->title; $album = $tracks->album; $id = $tracks->id; echo '<table border="0" width="60%" align="center">'; echo '<tr>'; echo '<td width="25%">'.$artist.'</td>'; echo '<td width="25%">'.$title.'</td>'; echo '<td width="25%">'.$album.'</td>'; echo '<td width="25%"><a href="http://www.durhamit.ca:8181/1.0/?method=player.playDatabaseItem&id='.$id.'">Play</a></td>'; echo '</tr>'; echo '<tr>'; echo '<td colspan="4"><hr></td>'; echo '</tr>'; echo '</table>'; } } //If we haven't submitted the form else { ?> <form action="" method="POST"> <center> <input type="text" name="name" size="24"> <input type="submit" value="Search" name="submitMe"> </form> <? } ?> I'm not sure why, but once I added a search form in my nav menu, it made my other forms on the website such as login and signup form take them to where the search button would take them. any ideas??? I'm getting a blank screen when I run the following search script. The script should retrieve news entries from the db which contain the keyword and echo those entries with the keyword highlighted in yellow. Could anyone shed light on why the script isn't running as it should?... Thanks in advance if you can help. Code: [Select] <?php if($_SERVER['REQUEST_METHOD'] == 'POST') { // form submitted if(!empty($_POST['keywords'])) { // search term has been entered $keywords = trim($_POST['keywords']); $search_exploded = explode(" ", $keywords); include('includes/mysqli_connect.php'); // connect to db // execute query $q = "SELECT title, subtitle, news_entry FROM news WHERE title LIKE '%$keywords%' OR subtitle LIKE '%$keywords%' OR news_entry LIKE '%$keywords%' "; $r = mysqli_query($dbc, $q); // If results were found, output them $retrieved = mysqli_num_rows($r); if (@mysqli_num_rows($r) > 0) { echo "<h3>" . $retrieved . ' result(s) found, as follows:</h3>'; while ($row = mysqli_fetch_array($r)) { echo "<div class='news_borders_top_bottom'>" . '<h1>' . $row['title'] = str_replace($_POST['keywords'], "<div class='highlight'>{$_POST['keywords']}</div>", $row['title']); . '</h1>' . '<h2>' . $row['subtitle'] = str_replace($_POST['keywords'], "<div class='highlight'>{$_POST['keywords']}</div>", $row['subtitle']); . '</h2>' . '<p>' . $row['news_entry'] = str_replace($_POST['keywords'], "<div class='highlight'>{$_POST['keywords']}</div>", $row['news_entry']); . '</p>' . '<div class="created_on">Created on: ' . $row['created'] . '</div></div>'; } mysqli_close($dbc); echo "<p><a href='search_archive.php'>Search again</a></p>"; ?> </div> </div> <?php include('includes/footer.php'); exit(); } else { // no matches echo "No news entries were found which matched your search criteria."; } } else { // no search term entered echo "Please enter a search term."; } } else { // search button not yet clicked so show form ?> <h1>Search News Archive</h1> <form method="post" action="search_archive.php" id="searchform"> <p><input type="text" id="keywords" name="keywords"> </p> <p><input type="submit" name="submit" value="Search!"> </p> </form> </div> </div> <?php } ?> Could somebody help me with a little problem I am having, I havew spent the last two weeks trying different ways to search my database without success. What I want to do is have an input field that I can search only one column of my database. (it is a game collection) for example I want to search the game 'Medal of Honor' i type this in the search field and click submit button and it should find all the entries with that name in the database. I have tried a few online tutorials and nothing works.
here is some code that i tried. <?php $host = "localhost"; $user = "root"; $password =""; $database = "csv_db"; $id = ""; $game = ""; $year = ""; $platform = ""; mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // connect to mysql database try{ $connect = mysqli_connect($host, $user, $password, $database); } catch (mysqli_sql_exception $ex) { echo 'Error'; } // get values from the form function getPosts() { $posts = array(); $posts[0] = $_POST['id']; $posts[1] = $_POST['game']; $posts[2] = $_POST['year']; $posts[3] = $_POST['platform']; return $posts; } // Search if(isset($_POST['search'])) { $data = getPosts(); $search_Query = "SELECT * FROM games WHERE id = $data[0]"; $search_Result = mysqli_query($connect, $search_Query); if($search_Result) { if(mysqli_num_rows($search_Result)) { while($row = mysqli_fetch_array($search_Result)) { $id = $row['ID']; $game = $row['GAME']; $year = $row['YR']; $platform = $row['PLATFORM']; } }else{ echo 'No Data For This Id'; } }else{ echo 'Result Error'; } } // Insert if(isset($_POST['insert'])) { $data = getPosts(); $insert_Query = "INSERT INTO `games`(`Game`, `YR`, `PLATFORM`) VALUES ('$data[1]','$data[2]',$data[3])"; try{ $insert_Result = mysqli_query($connect, $insert_Query); if($insert_Result) { if(mysqli_affected_rows($connect) > 0) { echo 'Data Inserted'; }else{ echo 'Data Not Inserted'; } } } catch (Exception $ex) { echo 'Error Insert '.$ex->getMessage(); } } // Delete if(isset($_POST['delete'])) { $data = getPosts(); $delete_Query = "DELETE FROM `games` WHERE `ID` = $data[0]"; try{ $delete_Result = mysqli_query($connect, $delete_Query); if($delete_Result) { if(mysqli_affected_rows($connect) > 0) { echo 'Data Deleted'; }else{ echo 'Data Not Deleted'; } } } catch (Exception $ex) { echo 'Error Delete '.$ex->getMessage(); } } // Edit if(isset($_POST['update'])) { $data = getPosts(); $update_Query = "UPDATE `games` SET `GAMES`='$data[1]',`YR`='$data[2]',`PLATFORM`=$data[3] WHERE `ID` = $data[0]"; try{ $update_Result = mysqli_query($connect, $update_Query); if($update_Result) { if(mysqli_affected_rows($connect) > 0) { echo 'Data Updated'; }else{ echo 'Data Not Updated'; } } } catch (Exception $ex) { echo 'Error Update '.$ex->getMessage(); } } ?> <!DOCTYPE Html> <html> <head> <title>PHP INSERT UPDATE DELETE SEARCH</title> </head> <body> <form action="php_insert_update_delete_search.php" method="post"> <input type="number" name="id" placeholder="ID" value="<?php echo $id;?>"><br><br> <input type="text" name="game" placeholder="Game" value="<?php echo $game;?>"><br><br> <input type="text" name="year" placeholder="Year" value="<?php echo $year;?>"><br><br> <input type="number" name="platform" placeholder="Platform" value="<?php echo $platform;?>"><br><br> <div> <!-- Input For Add Values To Database--> <input type="submit" name="insert" value="Add"> <!-- Input For Edit Values --> <input type="submit" name="update" value="Update"> <!-- Input For Clear Values --> <input type="submit" name="delete" value="Delete"> <!-- Input For Find Values With The given ID --> <input type="submit" name="search" value="Find"> </div> </form> </body> </html> and here is the error i get. Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1 in H:\xampp\htdocs\php_insert_update_delete_search.php:41 Stack trace: #0 H:\xampp\htdocs\php_insert_update_delete_search.php(41): mysqli_query(Object(mysqli), 'SELECT * FROM g...') #1 {main} thrown in H:\xampp\htdocs\php_insert_update_delete_search.php on line 41 can anybody help me do I search engine for my database Hi, I've recently changed servers. I uploaded a website to the new server, imported the SQL etc etc all works fine apart from the search script. Question is, without posted the code at present, is there anything obvious that could prevent the php search script to stop working on the new server when everything else works fine, and it was working fine on the old server? I assume the PHP versions of both servers are version 5. Older server 1&1, new server eUKhost Many thanks on my site: http://www.retroandvintage.co.uk whne you login ast test/test teh search does not work?! search page code Code: [Select] <?php session_start(); include_once("config.php"); $ebits = ini_get('error_reporting'); error_reporting($ebits ^ E_NOTICE); // Check user logged in already: checkLoggedIn("yes"); ?> <!doctype html> <html> <head> <title>Pubs and bars in <? echo $Townsearch;?></title> <meta name="description" content="Pubs, bars and restuarants in <? echo $Townsearch;?>" /> <meta name="keywords" content="<? echo $Townsearch;?>, pubs, bars, food, drink, nightlife" /> <meta name="Content-Language" content="en-gb" /> <meta name="robots" content="FOLLOW,INDEX" /> <meta name="revisit-after" content="2 days" /> <meta name="copyright" content="jbiddulph.com" /> <meta name="author" content="John Biddulph - Professional web site design and development in the south of england mainly worthing and brighton" /> <meta name="distribution" content="Global" /> <meta name="resource-type" content="document" /> <link rel="stylesheet" type="text/css" href="css/reset.css" /> <link rel="stylesheet" type="text/css" href="css/style.css" title="default" /> <link rel="alternate stylesheet" type="text/css" href="css/style1.css" title="1" /> <link rel="alternate stylesheet" type="text/css" href="css/style2.css" title="2" /> <script type="text/javascript" src="js/stylechanger.js"></script> <script type="text/javascript" src="js/jquery-1.2.1.pack.js"></script> <script type="text/javascript"> function lookup(inputString) { if(inputString.length == 0) { // Hide the suggestion box. $('#suggestions').hide(); } else { $.post("rpc.php", {queryString: ""+inputString+""}, function(data){ if(data.length >0) { $('#suggestions').show(); $('#autoSuggestionsList').html(data); } }); } } // lookup function fill(thisValue) { $('#inputString').val(thisValue); setTimeout("$('#suggestions').hide();", 200); } </script> </head> <body> <?php if($messages) { displayErrors($messages); }?> <header> <div id="title"> <h1>My Pub Space <a href="#" onClick="setActiveStyleSheet('default'); return false;"><img src="images/0.gif" width="15" height="15" border="0" alt="css style" /></a> <a href="#" onClick="setActiveStyleSheet('1'); return false;"><img src="images/1.gif" width="15" height="15" border="0" alt="css style" /></a> <a href="#" onClick="setActiveStyleSheet('2'); return false;"><img src="images/2.gif" width="15" height="15" border="0" alt="css style" /></a> <span> <form method="post" class="textbox" action="search.php?rsTown=<? echo $Town ?>&rsCounty=<? echo $County ?>"> Town/City: <input type="text" size="26" class="searchbox" value="" name="rsTown" id="inputString" onKeyUp="lookup(this.value);" onBlur="fill();" /> <input type="hidden" value="<? echo $County ?>" name="rsCounty" id="inputString" onKeyUp="lookup(this.value);" onBlur="fill();" /> <div class="suggestionsBox" id="suggestions" style="display: none;"> <img src="images/upArrow.png" style="position: relative; top: -36px; left: 105px; z-index:1;" alt="upArrow" /> <div class="suggestionList" id="autoSuggestionsList"> </div> </div> <input type="image" src="images/go.png" height="30" with="30" value="GO" /> </form> </span> </h1> </div> </header> <nav> <ul> <li class="selected"><a href="#">Home</a></li> <li><a href="#">Pubs</a></li> <li><a href="#">Members</a></li> <li><a href="#">Events</a></li> <li><a href="#">Register</a></li> </ul> </nav> <section id="intro"> <header> <h2>Your social guide to going down the pub, online!</h2> </header> <p>Stuck in town with nowhere to go? Not sure if up the road or down the street is best? Need to be somewhere warm, cosy and friendly. Need a drink?....<br />You've come to the right place, mypubspace has it all!</p> <img src="images/pub.jpg" alt="pub" /> </section> <div id="content"> <div id="mainContent"> <section> <article class="blogPost"> <header> <h2>Pubs in <? echo $Town;?>, <? $_SESSION['county'];?></h2> <p>Posted on <time datetime="2009-06-29T23:31+01:00">June 29th 2009</time> by <a href="#">Mads Kjaer</a> - <a href="#comments">3 comments</a></p> </header> <?php $tableName="pubs"; $targetpage = "search.php"; $limit = 20; $query = "SELECT COUNT(*) as num FROM $tableName WHERE rsTown LIKE '$Town%'"; $total_pages = mysql_fetch_array(mysql_query($query)); $total_pages = $total_pages['num']; $stages = 3; $page = $_GET['page']; if($page){ $start = ($page - 1) * $limit; }else{ $start = 0; } // Get page data $query1 = "SELECT * FROM $tableName WHERE rsTown LIKE '$Town%' LIMIT $start, $limit"; $result = mysql_query($query1); // Initial page num setup if ($page == 0){$page = 1;} $prev = $page - 1; $next = $page + 1; $lastpage = ceil($total_pages/$limit); $LastPagem1 = $lastpage - 1; $paginate = ''; if($lastpage > 1) { $paginate .= "<div class='paginate'>"; // Previous if ($page > 1){ $paginate.= "<a href='$targetpage?page=$prev&rsTown=$Town'>previous</a>"; }else{ $paginate.= "<span class='disabled'>previous</span>"; } // Pages if ($lastpage < 7 + ($stages * 2)) // Not enough pages to breaking it up { for ($counter = 1; $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter&rsTown=$Town&rsCounty=$County'>$counter</a>";} } } elseif($lastpage > 5 + ($stages * 2)) // Enough pages to hide a few? { // Beginning only hide later pages if($page < 1 + ($stages * 2)) { for ($counter = 1; $counter < 4 + ($stages * 2); $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter&rsTown=$Town&rsCounty=$County'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1&rsTown=$Town&rsCounty=$County'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage&rsTown=$Town&rsCounty=$County'>$lastpage</a>"; } // Middle hide some front and some back elseif($lastpage - ($stages * 2) > $page && $page > ($stages * 2)) { $paginate.= "<a href='$targetpage?page=1&rsTown=$Town&rsCounty=$County'>1</a>"; $paginate.= "<a href='$targetpage?page=2&rsTown=$Town&rsCounty=$County'>2</a>"; $paginate.= "..."; for ($counter = $page - $stages; $counter <= $page + $stages; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter&rsTown=$Town&rsCounty=$County'>$counter</a>";} } $paginate.= "..."; $paginate.= "<a href='$targetpage?page=$LastPagem1&rsTown=$Town&rsCounty=$County'>$LastPagem1</a>"; $paginate.= "<a href='$targetpage?page=$lastpage&rsTown=$Town&rsCounty=$County'>$lastpage</a>"; } // End only hide early pages else { $paginate.= "<a href='$targetpage?page=1&rsCounty=$County'>1</a>"; $paginate.= "<a href='$targetpage?page=2&rsCounty=$County'>2</a>"; $paginate.= "..."; for ($counter = $lastpage - (2 + ($stages * 2)); $counter <= $lastpage; $counter++) { if ($counter == $page){ $paginate.= "<span class='current'>$counter</span>"; }else{ $paginate.= "<a href='$targetpage?page=$counter&rsTown=$Town&rsCounty=$County'>$counter</a>";} } } } // Next if ($page < $counter - 1){ $paginate.= "<a href='$targetpage?page=$next&rsTown=$Town&rsCounty=$County'>next</a>"; }else{ $paginate.= "<span class='disabled'>next</span>"; } $paginate.= "</div>"; } echo $total_pages.' Results'; // pagination echo $paginate; ?> <ul> <?php while($row = mysql_fetch_array($result)) { echo '<li>'.$row['rsPubName'].', '.$row['rsTown'].', '.$row['rsCounty'].'</li>'; } $_SESSION['county'] = $row['rsCounty']; ?> </ul> </article> </section> <section id="comments"> <h3>Comments</h3> <article> <header> <a href="#">George Washington</a> on <time datetime="2009-06-29T23:35:20+01:00">June 29th 2009 at 23:35</time> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut.</p> </article> <article> <header> <a href="#">Benjamin Franklin</a> on <time datetime="2009-06-29T23:40:09+01:00">June 29th 2009 at 23:40</time> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut.</p> </article> <article> <header> <a href="#">Barack Obama</a> on <time datetime="2009-06-29T23:59:00+01:00">June 29th 2009 at 23:59</time> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut.</p> </article> </section> <form action="" method="POST" method="post"> <h3>Post a comment</h3> <p> <label for="name">Name</label> <input name="name" id="name" type="text" required /> </p> <p> <label for="email">E-mail</label> <input name="email" id="email" type="email" required /> </p> <p> <label for="website">Website</label> <input name="website" id="website" type="url" /> </p> <p> <label for="comment">Comment</label> <textarea name="comment" id="comment" required></textarea> </p> <p> <input type="submit" value="Post comment" /> </p> </form> </div> <aside> <section> <header> <h3>Members Login Area</h3> </header> <h4>Welcome <? print($_SESSION["rsUser"]); ?></h4> <ul> <li><a href="#">Sign up</a></li> <li><a href="#">Forgot Password</a></li> </ul> </section> <section> <header> <h3>Archives</h3> </header> <ul> <li><a href="#">December 2008</a></li> <li><a href="#">January 2009</a></li> <li><a href="#">February 2009</a></li> <li><a href="#">March 2009</a></li> <li><a href="#">April 2009</a></li> <li><a href="#">May 2009</a></li> <li><a href="#">June 2009</a></li> </ul> </section> </aside> </div> <footer> <div> <section id="about"> <header> <h3>About</h3> </header> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco <a href="#">laboris nisi ut aliquip</a> ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p> </section> <section id="blogroll"> <header> <h3>Blogroll</h3> </header> <ul> <li><a href="#">NETTUTS+</a></li> <li><a href="#">FreelanceSwitch</a></li> <li><a href="#">In The Woods</a></li> <li><a href="#">Netsetter</a></li> <li><a href="#">PSDTUTS+</a></li> </ul> </section> <section id="popular"> <header> <h3>Popular</h3> </header> <ul> <li><a href="#">This is the title of a blog post</a></li> <li><a href="#">Lorem ipsum dolor sit amet</a></li> <li><a href="#">Consectetur adipisicing elit, sed do eiusmod</a></li> <li><a href="#">Duis aute irure dolor</a></li> <li><a href="#">Excepteur sint occaecat cupidatat</a></li> <li><a href="#">Reprehenderit in voluptate velit</a></li> <li><a href="#">Officia deserunt mollit anim id est laborum</a></li> <li><a href="#">Lorem ipsum dolor sit amet</a></li> </ul> </section> </div> </footer> </body> </html> Hi there, new to the forum
Ok so i have a crm and i'm trying to add bits, been pretty succesful at most of it, however i've added a new field "status" and i want to be able to search this field, i've tried copying and changing the existing code, but it doesn't seem to be grabbing it.
So here's some exisiting code (that works and searches the field marked "Address"
'address' => array( 'title' => _l('Address:'), 'field' => array( 'type' => 'text', 'name' => 'search[address]', 'value' => isset($search['address'])?$search['address']:'', 'size' => 15, ) ), 'status' => array( 'title' => _l('Status:'), 'field' => array( 'type' => 'text', 'name' => 'search[status]', 'value' => isset($search['status'])?$search['status']:'', 'size' => 15, ) ),I thought a simple name change like above would work, but it doesn't pull anything through, anyone got any ideas? This is for a faux stock photo website. When I only use the $query string to search for $searchSubject, everything goes golden. Once I put everything else in there though, the search function will not work at all. Any help will be greatly appreciated. I've been staring at this for too long and it's starting to give me a headache. PS. This is my first post here. Seems like a great community! <?php $searchSubject = $_POST['searchSubject']; $searchPhotoname = $_POST['searchPhotoname']; $searchLocation = $_POST['searchLocation']; if (isset($_POST['search'])) { //Select records from the database $query = "SELECT * FROM `photos` WHERE `subject` LIKE '%" . $searchSubject . "%' OR `name` LIKE '%" . $searchPhotoname . "%' OR `location` LIKE '%" . $searchLocation . "%' "; } else { $query = "SELECT * FROM photos"; } $result = mysql_query($query); // count the number of rows in the database $num = mysql_num_rows($result); ?> If I leave it at this: $query = "SELECT * FROM `photos` WHERE `subject` LIKE '%" . $searchSubject . "%'"; Then everything works perfect. Hi I'm working on a database search for a product but the products can be narrowed down to the client will get exactly what they're after, i've got a good amount of it working and sorted but the thing i'm stuck on is that you can get the products in an alternate finish, so you can get Brass, Nickel, Stainless Steel and what i have will only work if the database only has one option within the field value in the MySQL, but if i have Brass, Nickel in the value and search Brass it won't bring it back, i'm a little bit stuck on how to fix this. Here is the code i've got for that like i say works if there is only one field in the MySQL, any help would be good. Thanks <?php include_once("mysql.php"); if (isset($_GET['Code_Of_Installation'])){ $Code_Of_Installation = $_GET['Code_Of_Installation']; $Gland_Material = $_GET['Gland_Material']; $Application_Category = $_GET['Application_Category']; $Cable_Type = $_GET['Cable_Type']; $Sealing_Configiration = $_GET['Sealing_Configiration']; $Approvals = $_GET['Approvals']; $Onshore_Offshore = $_GET['Onshore_Offshore']; $where = array(); if ($Code_Of_Installation != '') $where['Code_Of_Installation'] = $Code_Of_Installation; if ($Gland_Material != '') $where['Gland_Material'] = $Gland_Material; if ($Application_Category != '') $where['Application_Category'] = $Application_Category; if ($Cable_Type != '') $where['Cable_Type'] = $Cable_Type; if ($Sealing_Configiration != '') $where['Sealing_Configiration'] = $Sealing_Configiration; if ($Approvals != '') $where['Approvals'] = $Approvals; if ($Onshore_Offshore != '') $where['Onshore_Offshore'] = $Onshore_Offshore; $GLOBALS['r'] = smart_select('*','Search',$where); include("search-results.php"); } else { include("search-form.php"); } Hi, I have been trying for 2 days to get this to work. I am trying to put in a list of search keywords in the form, run a LIKE query on the database, and echo out all of the matching terms. Please if someone could please show me how to echo out this information I would be very grateful. Thank you. Code: [Select] <?php $host = ""; $database = ""; $username = ""; $password = ""; $tbl_name = "users"; $conn = mysql_connect($host, $username, $password) or die("Could not connect: " . mysql_error()); mysql_select_db($database); include('bouncer.php'); $currentUser = $_SESSION['myusername']; if(isset($_POST['submit'])) { $first = mysql_real_escape_string( $_POST['first']); $last = mysql_real_escape_string( $_POST['last']); $dob = mysql_real_escape_string( $_POST['dob']); $gender = mysql_real_escape_string( $_POST['gender']); $ethnic = mysql_real_escape_string( $_POST['ethnic']); $country = mysql_real_escape_string( $_POST['country']); $state = mysql_real_escape_string( $_POST['state']); $town = mysql_real_escape_string( $_POST['town']); $zip = mysql_real_escape_string( $_POST['zip']); $email = mysql_real_escape_string( $_POST['email']); $hobbies = mysql_real_escape_string( $_POST['hobbies']); $job = mysql_real_escape_string( $_POST['job']); $business = mysql_real_escape_string( $_POST['business']); $religion = mysql_real_escape_string( $_POST['religion']); $social = mysql_real_escape_string( $_POST['social']); $political = mysql_real_escape_string( $_POST['political']); $affiliations = mysql_real_escape_string( $_POST['affiliations']); $buying = mysql_real_escape_string( $_POST['buying']); $selling = mysql_real_escape_string( $_POST['selling']); $likes = mysql_real_escape_string( $_POST['likes']); $dislikes = mysql_real_escape_string( $_POST['dislikes']); $links = mysql_real_escape_string( $_POST['links']); //THE SEARCH FUNCTION $result = mysql_query ( "SELECT * FROM users WHERE dob LIKE '%$dob%' OR gender LIKE '%$gender%' OR race LIKE '%$ethnic%' OR job LIKE '%$job%' OR country LIKE '%$country%' OR state LIKE '%$state%' OR town LIKE '%$town%' OR zip LIKE'%$zip%' OR hobbies LIKE'%hobbies%' OR business LIKE '%$business%' OR religion LIKE'%$religion%' OR social_groups LIKE '%$social%' OR political_groups LIKE'%$political%' OR other_affiliations LIKE ' %$affiliations%' OR buying LIKE '%$buying%' OR selling LIKE '%$selling%' OR links LIKE '%$links%' OR likes LIKE '%$likes%' OR dislikes LIKE'%$dislikes%'"); if (!$result) { echo 'Could not run query: ' . mysql_error(); exit; } $row = mysql_fetch_row($result); echo $row[0]; echo $row[1]; // I HAVE NO IDEA WHERE TO GO FROM HERE. } ?> <html> <body> <p>Login Successful</p> <p> </p> <form action="login_success6.php" method="post"> <p> <input type="text" name="first" size="20" /> First name<br /> <input type="text" name="last" size="20" /> Last name<br /> <input name="dob" type="text" size="20" id="dob" /> Date of Birth<br /> <input type="text" name="gender" size="20" id="gender" /> Gender <br /> <input type="text" name="ethnic" size="20" id="ethnic" /> Ethnicity <br /> <input type="text" name="country" size="20" id="country" /> Country<br /> <input type="text" name="state" size="20" id="state" /> State<br /> <input type="text" name="town" size="20" id="town" /> Town<br /> <input type="text" name="zip" size="20" id="zip" /> Zip Code<br /> <br /> <input type="text" name="email" size="40" id="email" /> Email<br /> <textarea name="job" cols="40" id="job"></textarea> Job<br /> <textarea name="business" cols="40" id="business"></textarea> Business<br /> <input type="text" name="religion" size="60" id="religion" /> Religion</p> <p><br /> <textarea name="social" cols="100" id="social"></textarea> Social Groups<br /> <textarea name="political" cols="100" id="political"></textarea> Political groups<br /> <textarea name="affiliations" cols="100" id="affiliations"></textarea> Other Affiliations<br /> <textarea name="buying" cols="100" id="buying"></textarea> Items I am buying<br /> <textarea name="selling" cols="100" id="selling"></textarea> Items I am selling<br /> <textarea name="likes" cols="100" id="likes"></textarea> My likes <br /> <textarea name="dislikes" cols="100" id="dislikes"></textarea> My dislikes <br /> <textarea name="links" cols="100" id="links"></textarea> My links <br /> <input type="submit" name="submit" value="Store in database and search" /> <input type="reset" value="Reset fields" /> </p> </p> </form> </body> </html> Hey guys for a project im making a search filter function. Only one filter seems to be working and that's the genre filter :(
This is my code:
function filterFilms(){ global $conn; $loop = 0; if(isset($_POST['titel']) && !empty($_POST['titel'])){ $titel = sanatize($_POST['titel']); } if(isset($_POST['genre']) && !empty($_POST['genre'])){ $genre = sanatize($_POST['genre']); } $sql = "SELECT TOP 20 * From Movie Inner Join Movie_Director On Movie_Director.movie_id = Movie.movie_id Inner Join Movie_Genre On Movie_Genre.movie_id = Movie.movie_id Inner Join Person On Movie_Director.person_id = Person.person_id"; if(isset($titel) && !empty($titel)){ if($loop == 0){ $sql .= " WHERE ( title = ':titel' OR title like ':titel')"; $loop++; } else{ $sql .= " AND ( title = ':titel' OR title like ':titel')"; } } if(isset($genre) && !empty($genre)){ if($loop == 0){ $sql .= " WHERE genre_name = :genre"; $loop++; } else{ $sql .= " AND genre_name = :genre"; } } $query = $conn->prepare($sql); if(isset($titel) && !empty($titel)){ $query->bindValue('titel', $titel,PDO::PARAM_STR); } if(isset($genre) && !empty($genre)){ $query->bindParam('genre', $genre,PDO::PARAM_STR); } $query->execute(); $rows = $query->fetchAll(); return $rows; }
Anyone any idea??
Hi all, I am having trouble in getting my search facility to work on a web server. Currently when I run the website on my local server using WAMP it works fine and retrieves all the results contained in the database but it does not retrieve any results when uploaded to a web server. I'm currently using Heart Internet if this helps. Below is the code I have used for the search facility: Code: [Select] <?php // this script searches for matches on the posted search string in courses, modules tables. $searchstr = $_POST['search']; $trimmedstr = trim($searchstr); //trim whitespace from the stored variable echo "<h2 id='homecol'>Searching for... "".$trimmedstr.""</h2><hr class='homecols' />"; //Build SQL search queries //search courses table $queryProd = "SELECT * FROM courses WHERE courseTitle LIKE \"%$trimmedstr%\" OR courseDescription LIKE \"%$trimmedstr%\" OR courseCode LIKE \"%$trimmedstr%\"ORDER BY courseTitle"; $numresultsProd=mysql_query($queryProd); $numrowsProd=mysql_num_rows($numresultsProd); // echo "results found for courses: ".$numrowsProd."<br>"; // test code //search modules table $queryCat = "SELECT * FROM modules WHERE moduleTitle LIKE \"%$trimmedstr%\" OR moduleSummary LIKE \"%$trimmedstr%\" OR moduleCode LIKE \"%$trimmedstr%\"ORDER BY moduleTitle"; $numresultsCat=mysql_query($queryCat); $numrowsCat=mysql_num_rows($numresultsCat); // echo "results found for modules: ".$numrowsCat."<br>"; //test code // If no results found, offer google search as alternative or back to home page if ($numrowsProd + $numrowsCat == 0) { echo "<h3>Results:</h3><br>"; echo "<p>Sorry, we could not find any results for: "".$trimmedstr.""</p>"; echo "<p><a href=\"http://www.google.com/search?q=".$trimmedstr."\" target=\"_blank\" title=\"Look up".$trimmedstr." on Google\"> Click here to search on google instead</a> or Return to our <a href='../home.php'>Home Page</a></p>"; } else //list search results { if($numrowsProd >0) // list results fromcourses { $resultProd = mysql_query($queryProd) or die("Couldn't execute query"); // begin ordered list echo "<h3><strong>Results from Courses:</strong></h3><p><ol>"; $countProd = 1; // display the results returned while ($rowProd= mysql_fetch_array($resultProd)) { $courseCode = $rowProd["courseCode"]; $title = $rowProd["courseTitle"]; $prodID = $rowProd["courseID"]; $descProd = $rowProd["courseDescription"]; echo "<p><li><a href='../department/courseselect.php?pid=$prodID'>$title</a> - $descProd</li></p>"; $countProd++ ; } echo "</ol></p>"; } if($numrowsCat >0) // and/or list results from modules { $resultCat = mysql_query($queryCat) or die("Couldn't execute query"); // begin ordered list echo " <h3>Results from Modules:</h3><p><ol>"; $countCat = 1; // display the results returned while ($rowCat= mysql_fetch_array($resultCat)) { $moduleCode = $rowCat["moduleCode"]; $catName = $rowCat["moduleTitle"]; $catID = $rowCat["moduleID"]; $descCat = $rowCat["moduleSummary"]; echo "<p><li><a href='../department/module_detail.php?pid=$catID'>$catName</a> - $descCat</li></p>"; $countCat++ ; } echo "</ol></p>"; } echo "<p>Please click on either the course or module to view further information</p>"; } ?> If anyone has any ideas please let me know. Thanks This is what I was using for including an url with parameter <?php if ($fh = fopen('http://www.domain.com/search.php?query=test', 'r') ) { fpassthru($fh); fclose($fh); } ?> It's not working anymore after the hosting company did an upgrade. By the way. Alle scripts are accessible locally. What is my alternative?? I want to know how to display results from mysql database by filling in a form. but i have found a tutorial which shows typing in a text box which displays results. if i follow this tutorial will it help me to understand and create php coding to display results for my form? I Have been working on this search for for a while which is working but lacks a few feature i wanna add. 1st is if the make/model/price is empty i want to search the whole db I have attached the php file Also each card has a image and need help adding these to the search. the images are located in a uploads folder Iv grafted hard on this and need some help Also is this the correct way to process a form search? I just changed around my database and as such I need to update my search form. The way it used to work was a user could use the search bar to look for actors. In changing my database there in no longer a actor column, there are how ever actor_1, actor_2 ... until actor_7. What I am trying to do it set it up so my form looks the same but the back end will look in all the actor columns for the name. So when a user selects actor from the drop down menu it will look in all 7 actor columns. Here is what i had before that worked. for the search bar Code: [Select] <form action="/search.php" method="post"> <span class="rulesub">Search: </span><input type="text" name="search"> <select size="1" name="dropdown"> <option value="" selected>Search by...</option> <option value="title">Title</option> <option value="actors">Actors</option> <option value="difficulty">Difficulty 1-5</option> </select> <input type="Submit" value="Search" name="Submit"> </form> for the search page Code: [Select] $connect = mysql_connect('localhost', $username, $password) or die ("Unable to connect to host"); mysql_select_db($database) or die ("Unable to connect to database"); $search = empty($_POST['search'])? die ("Please enter search criteria.") : mysql_escape_string($_POST['search']); $dropdown = empty($_POST['dropdown'])? die ("Please select from search criteria.") : mysql_escape_string($_POST['dropdown']); $query = mysql_query("SELECT * FROM movie WHERE $dropdown Like '%$search%'") or die (mysql_error()); if(mysql_num_rows($query) == 0) { printf("Could not find $search while looking in $dropdown, please try again."); //exit; } else{ $num=mysql_numrows($query); mysql_close($connect); ?> Output thanks I have a search form and have set up php, but at the moment its not making the correct searches, what am i doing wrong. Help is appreciated. heres my php code: Code: [Select] <?php $server = ""; // Enter your MYSQL server name/address between quotes $username = ""; // Your MYSQL username between quotes $password = ""; // Your MYSQL password between quotes $database = ""; // Your MYSQL database between quotes $con = mysql_connect($server, $username, $password); // Connect to the database if(!$con) { die('Could not connect: ' . mysql_error()); } // If connection failed, stop and display error mysql_select_db($database, $con); // Select database to use // Query database $result = mysql_query("SELECT * FROM Properties"); // Set up our error check and result check array $error = array(); $results = array(); // First check if a form was submitted. // Since this is a search we will use $_GET if (isset($_GET['search'])) { $searchTerms = trim($_GET['search']); $searchTerms = strip_tags($searchTerms); // remove any html/javascript. if (strlen($searchTerms) < 10) { $error[] = "Search terms must be longer than 10 characters."; }else { $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection. } // If there are no errors, lets get the search going. if (count($error) < 1) { $searchSQL = "SELECT sid, sbody, stitle, sdescription FROM simple_search WHERE "; // grab the search types. $types = array(); $types[] = isset($_GET['images'])?"`simages` LIKE '%{$searchTermDB}%'":''; $types[] = isset($_GET['Location'])?"`sLocation` LIKE '%{$searchTermDB}%'":''; $types[] = isset($_GET['Number of bedrooms'])?"`snumberofbedrooms` LIKE '%{$searchTermDB}%'":''; $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked) if (count($types) < 1) $types[] = "`simages` LIKE '%{$searchTermDB}%'"; // use the body as a default search if none are checked $andOr = isset($_GET['matchall'])?'AND':'OR'; $searchSQL .= implode(" {$andOr} ", $types) . " ORDER BY `sLocation`"; // order by title. $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}"); if (mysql_num_rows($searchResult) < 1) { $error[] = "The search term provided {$searchTerms} yielded no results."; }else { $results = array(); // the result array $i = 1; while ($row = mysql_fetch_assoc($searchResult)) { $results[] = "{$i}: {$row['sLocation']}<br />{$row['sNumberofbedrooms']}<br />{$row['sbody']}<br /><br />"; $i++; } } } } function removeEmpty($var) { return (!empty($var)); } if (!$result) { echo "Error running query:<br>"; trigger_error(mysql_error()); } elseif(!mysql_num_rows($result)) { // no records found by query. echo "No records found"; } else { $i = 0; echo '<div class="container" style="float:left;">'; while($row = mysql_fetch_array($result)) { // Loop through results $i++; echo '<div class="imageholder" style="float:left;">'; echo '<img class="image1" src="'. $row['images'] .'" />'; //image echo '</div>'; echo '<div class="textholder" style="font-family:helvetica; font-size:13px; float:left; padding-top:10px;">'; echo "<span style=\"color:green;\"><b>Displaying record $i<br>\n</b><br></span>"; echo "<b>" . $row['id'] . "</b><br>\n"; // Where 'id' is the column/field title in the database echo "Location: ". $row['Location'] . "<br>\n"; // Where 'location' is the column/field title in the database echo "Property Type: ". $row['Property_type'] . "<br>\n"; // as above echo "Bedrooms: ". $row['Number_of_bedrooms'] . "<br>\n"; // .. echo "Purchase Type: ". $row['Purchase_type'] . "<br>\n"; // .. echo "Price: ". $row['Price_range'] . "<br>\n"; // .. echo '</div>'; echo '<div style="clear:both"></div>'; } echo '</div>'; } mysql_close($con); // Close the connection to the database after results, not before. ?> Hi, I was wondering could anyone help me here please, I'm pretty stuck and not sure what's wrong. I have also posted this topic on Daniweb if that is OK as I'm kind of stuck for time on this (If I'm not allowed post on multiple forums this can be deleted). I have a database that contains files and I want to be able to search those files by putting in a ID number into a textbox on my homepage of a website I'm working on. In my databse my doc_id is the primary key, and I want the user to be able to enter a document ID and have all the information returned to them. Can anyone help me here as I don't understand why it isn't working? Here is the code as it is at the moment - Code: [Select] <?php include 'connect_db.php'; include 'newheader.php'; function sanitize_data($data) { $data = array_map('trim',$data); $data = array_map('strip_tags',$data); $data = array_map('htmlspecialchars',$data); $data = array_map('mysql_real_escape_string',$data); return $data; } $post = sanitize_data($_POST); if (isset($_POST['searchID'])) { $find = $_POST['find']; $find = strtoupper($find); $find = strip_tags($find); $find = trim ($find); $field = $_POST['field']; $data = mysql_query("SELECT * FROM tc_tool.forms WHERE upper(".$field.") LIKE'%$find%'") or die(mysql_error()); while ($result = mysql_fetch_array( $data )) { echo $result['doc_number']; echo " "; echo $result['doc_title']; echo " "; echo "<br>"; echo "<br>"; } ?> The error returned to me is this - Incorrect parameter count in the call to native function 'upper' Here is the code to my button too if it is any use - Code: [Select] <body onLoad = "documentNumber.focus()"> <input type= "text" id= "documentNumber" name= "searchbyequipmenttype" class= "eSearchFormInput"/> <input type= "submit" name= "searchID" value="Search By Doc ID" /><br /> And I have no idea why it is, can anyone help if possible? I have tried it a few ways so if needed I'll post the other ways I've tried it. Thanks if anyone can help hi im new to these stuff and appreciate any help.
im creating a simple form with 1 textbox and a search button. when the button is pressed a select query should run and check the mysql database and list that result on that same page. For example, lets say there is a textbox named Lastname, then the search button should search mysql and list down the last name matching that name.
Form code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Search</title> </head> <body> <form action="post.php" method="GET"> <input type="text" name="query" /> <input type="submit" value="Search" /> </form> </body> </html>Any help? I need to show the result right bellow the button, and if no match found it should display an error : no match found thanks Hello!To search in a table from my database i use this: mysql_connect ("localhost", "","") or die (mysql_error()); mysql_select_db (""); $key = $_POST['key']; $sql = mysql_query("select * from internet_securitate where nume_produs like '%$key%'"); while ($row = mysql_fetch_array($sql)){ echo 'Produs ID: '.$row['internet_securitateID']; echo '<br/> Denumire Produs: '.$row['nume_produs']; echo '<br/> Descrie '.$row['descriere']; echo '<br/> Disponibilitate: '.$row['disponibilitate_produs']; echo '<br/><br/>'; } can i expand this to searh in 3 tables? :-? |