PHP - Simple Database Search
i have enters some data using form which submit data in sql table1 like this,
Fields name in table -->> id First name Lastname Date data saved -->> 1 user 1 2011-05-10 2 user 2 2011-05-11 3 user 3 2011-05-12 now i dont want to duplicate date in database let say while inserting data using form, Firstname : ____________ Lasename : ____________ Date : ____________ (i dont want this date to b save if the date alredy exist in database, it should prompt user "Date already exist and to edit click here (this will be the link to that date which is already exist so that we can edit) " ) SAVE i user files , form.php , insert.php(so insert values in database) , so tell me what function should i use to solve my problem.... Similar Tutorialsugh... I'm a total PHP nub and I'm having trouble with: Code: [Select] $search_by = $_POST['search_by']; $search = $_post['search']; $dbc = mysqli_connect('xx', 'artofwarsomerset', 'xx', 'artofwarsomerset') or die ('Error connecting to MySQL server'); $query = "SELECT * FROM players WHERE '$search_by' = '$search' "; $result = mysqli_query($dbc,$query) or die("Error: ".mysqli_error($dbc)); echo "<table><tr><td>Player</td><td>city</td><td>alliance</td><td>x</td><td>y</td><td>other</td><td>porters</td><td>conscripts</td><td>Spies</td><td>HBD</td><td>Minos</td><td>LBM</td><td>SSD</td><td>BD</td><td>AT</td><td>Giants</td><td>Mirrors</td><td>Fangs</td><td>ogres</td><td>banshee</td></tr>" ; while ($row = mysqli_fetch_array ($result)) { echo '<tr><td> $row['player'] </td>'; echo '<td> . $row['city']</td>'; echo '<td> . $row['alliance']</td>'; echo '<td> . $row['x']</td>'; echo '<td> . $row['y']</td>'; echo '<td> . $row['other']</td>'; echo '<td> . $row['porter']</td>'; echo '<td> . $row['cons']</td>'; echo '<td> . $row['spy']</td>'; echo '<td> . $row['hbd']</td>'; echo '<td> . $row['mino']</td>'; echo '<td> . $row['lbm']</td>'; echo '<td> . $row['ssd']</td>'; echo '<td> . $row['bd']</td>'; echo '<td> . $row['at']</td>'; echo '<td> . $row['giant']</td>'; echo '<td> . $row['fm']</td>'; echo '<td> . $row['ft']</td>'; echo '<td> . $row['ogre']</td>'; echo '<td> . $row['banshee']</td></tr></table>'; } ?> Error shows up on line 35 but I'm not sure what I've done... Also, the xx's on my dbc statement were on purpose. Current error is: Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in /home/content/64/4940664/html/artofwar/browse.php on line 35, I can't figure out where the hell it wants a ;... I am developing a intranet forum in Php and MySQL and I am using ajax to display searched results on the same page but right now I am using query LIKE text% to search in database which is slower. but I want to make it fast search engin which can parse *,+ and show result. Since I am using ajax i am not able to use free search engin,so if possible pls provide a complete solution I have code to search a database of members, I can search by lastname but having a little problem. I want to be able to search by lastname starting with the first letter. (ie: a or b or c or d and so on). As it is right now I can only search by first letter of last name if I add % to the search (ie: a% b% c%) will give me all members with the last names starting with the approiate letter designation. I'm not sure how to handle this, any help would be appreciated. Thanks. Code: [Select] <!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <center><table cellspacing="10" cellpadding="10" width="750" border="0"> <h4>Search</h4> <form name="search" method="post" action="<?php $PHP_SELF?>"> Seach for: <input type="text" name="find" /> in <Select NAME="field"> <Option VALUE="lname">Last Name</option> <input type="hidden" name="searching" value="yes" /> <input type="submit" name="search" value="Search" /> </form> <?php // check to see if anything is posted if (isset($_POST['find'])) {$find = $_POST['find'];} if (isset($_POST['searching'])) {$searching = $_POST['searching'];} if (isset($_POST['field'])) {$field = $_POST['field'];} //This is only displayed if they have submitted the form if (isset($searching) && $searching=="yes") { echo "<h4>Results</h4><p>"; // If they did not enter a search term we give them an error if (empty($find)) { echo "<p>You forgot to enter a search term"; exit; } // Otherwise we connect to our Database mysql_connect("localhost", "root", "1910") or die(mysql_error()); mysql_select_db("cmc_member") or die(mysql_error()); // We preform a bit of filtering $find = strtoupper($find); $find = strip_tags($find); $find = trim ($find); // Now we search for our search term, in the field the user specified $results = mysql_query("SELECT * FROM members WHERE upper($field) LIKE'$find'"); // And we display the results if($results && mysql_num_rows($results) > 0) { $i = 0; $max_columns = 3; while($row = mysql_fetch_array($results)) { // make the variables easy to deal with extract($row); // open row if counter is zero if($i == 0) echo "<tr>"; // make sure we have a valid product ALIGN='CENTER' if($fname != "" && $fname != null) echo "<td ALIGN='CENTER'><FONT COLOR='red'><b>$fname $lname</b></FONT><br> $address <br> $city $state $zip <br>$phone<br><a href=\"mailto: $email\">$email</a><br></td>"; // increment counter - if counter = max columns, reset counter and close row if(++$i == $max_columns) { echo "</tr>"; $i=0; } // end if } // end while } // end if results // clean up table - makes your code valid! if($i < $max_columns) { for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; } //This counts the number or results - and if there wasn't any it gives them a little message explaining that $anymatches = mysql_num_rows($results); if ($anymatches == 0) { echo "Sorry, but we can not find an entry to match your query<br><br>"; } //And we remind them what they searched for echo "<b>Searched For:</b> " .$find; } ?> </tr> </table></center> </body> </html> OK, I am new to PHP I am wanting to create a property search using drop down boxes. I have a database with 4 main fields to search: Bedrooms (beds), Area (area), Price Range (price) and Type (type) Here is the code so far, can someone please correct it. Thanks... ****************************** When I run it it says: Warning: trim() expects at most 2 parameters, 4 given in C:\wamp\www\search222.php on line 8 Warning: mysql_query() expects parameter 1 to be string, resource given in C:\wamp\www\search222.php on line 45 Couldn't execute query +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ <?php // Get the search variable from URL $var1 = @$_GET['beds'] ; $var2 = @$_GET['area'] ; $var3 = @$_GET['price'] ; $var4 = @$_GET['type'] ; $trimmed = trim($var1, $var2, $var3, $var4); // rows to return $limit=10; // check for an empty string and display a message. if ($var1 == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var1)) { echo "<p>We dont seem to have a search parameter!</p>"; exit; } $host = "localhost"; $username = "root"; $password = ""; //connect to your database ** EDIT REQUIRED HERE ** $link = mysql_connect($host, $username, $password) or die("Unable to connect to SQL Server"); //(host, username, password) $db = "property_db"; //specify database ** EDIT REQUIRED HERE ** mysql_select_db($db, $link) or die("Unable to select database"); //select which database we're using // Build SQL Query $results = mysql_query("SELECT * FROM house_src", $link); $numresults = mysql_num_rows($results); // get results $result = mysql_query($results) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: ". $var4 . "property, with ". $var1 . " bedrooms, in the " . $var2 . "area, with a price range of " . $var3 .""; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["1st_field"]; 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); 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 " <a href=\"$PHP_SELF?s=$news&q=$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>"; ?> OK, I am new to PHP I am wanting to create a property search using drop down boxes. I have a database with 4 main fields to search: Bedrooms (beds), Area (area), Price Range (price) and Type (type) Here is the code so far, can someone please correct it. Thanks... +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ <?php // Get the search variable from URL $var1 = @$_GET['beds'] ; $var2 = @$_GET['area'] ; $var3 = @$_GET['price'] ; $var4 = @$_GET['type'] ; $trimmed = trim($var1, $var2, $var3, $var4); // rows to return $limit=10; // check for an empty string and display a message. if ($var1 == "") { echo "<p>Please enter a search...</p>"; exit; } // check for a search parameter if (!isset($var1)) { echo "<p>We dont seem to have a search parameter!</p>"; exit; } $host = "localhost"; $username = "root"; $password = ""; //connect to your database ** EDIT REQUIRED HERE ** $link = mysql_connect($host, $username, $password) or die("Unable to connect to SQL Server"); //(host, username, password) $db = "property_db"; //specify database ** EDIT REQUIRED HERE ** mysql_select_db($db, $link) or die("Unable to select database"); //select which database we're using // Build SQL Query $results = mysql_query("SELECT * FROM house_src", $link); $numresults = mysql_num_rows($results); // get results $result = mysql_query($results) or die("Couldn't execute query"); // display what the person searched for echo "<p>You searched for: ". $var4 . "property, with ". $var1 . " bedrooms, in the " . $var2 . "area, with a price range of " . $var3 .""; // begin to show results set echo "Results"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["1st_field"]; 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); 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 " <a href=\"$PHP_SELF?s=$news&q=$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>"; ?> Hello all. First of all, if this isn't the right place for this topic, please excuse me and may the moderators/admins move it where it should belong. Second, I'm trying to make a mysql search - Everything works, but if say, a user searches for 34 it displays all numbers that have the number 34 in them. I want the results to be exact - if a user searches for 34, to display only 34, not 334, 5034 or 3401 (like it happens now). Here's the code: Code: [Select] <?php mysql_connect ("**************", "*******","*****") or die (mysql_error()); mysql_select_db ("********"); $term = $_POST['term']; $sql = mysql_query("select * FROM countries WHERE cocode LIKE '%$term%'"); while ($row = mysql_fetch_array($sql)){ echo '<br/> Code: '.$row['cocode']; echo '<br/> Country: '.$row['coname']; echo '<br/><br/>'; } ?> If you have any questions, you're welcome to ask them in the thread. Thank you in advance Hi i am an absolute PHP/MYSQL Novice but i guess we all gotta start somewhere. I have a table in my database with names and addresses, f_name, s_name, street, zip_code, city etc etc etc What i want to do is display a drop down of all cities in my database then click on any city in the list to display all the details of people in that city, showing all fields. So i have got this far .. Code: [Select] $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'cities_wrdp1'; mysql_select_db($dbname); $sql = "SELECT DISTINCT City FROM PBM"; $result = mysql_query($sql); echo "<select name='City'>"; while ($row = mysql_fetch_array($result)) { echo "<option value='" . $row['City'] . "'>" . $row['City'] . "</option>"; } echo "</select>"; This produces the nice drop down list of cities from the database ... Now on click i would like to return results similar to this Code: [Select] $conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql'); $dbname = 'cities_wrdp1'; mysql_select_db($dbname); $query = sprintf("SELECT * FROM PBM"); $result = mysql_query($query); if (!$result) { $message = 'Invalid query: ' . mysql_error() . "\n"; $message .= 'Whole query: ' . $query; die($message); } echo "<br />"; echo "<table border='0'>"; while ($row = mysql_fetch_assoc($result)) { echo "<tr><td>"; echo "<a href=\"" .$row['profileURL'] . "\"> <img src=\"" . $row['faviconURL'] . "\" border=0 alt=\"" . $row["Thumbnail"] . "\"> </a>"; echo "</td><td align='center'>"; echo $row['f_name']; echo "</td><td align='center'>"; echo $row['s_name']; echo "</td><td align='center'>"; echo $row['number']; echo "</td><td align='center'>"; echo $row['street']; echo "</td><td align='center'>"; echo $row['zip']; echo "</td><td align='center'>"; echo $row['city']; echo "</td><td align='center'>"; echo $row['Country']; echo "</td><td align='center'>"; echo $row['email_address']; echo "</td><td align='center'>"; echo $row['fb']; echo "</td><td align='center'>"; echo $row['web_site']; echo "</td><td align='center'>"; echo $row['phone']; echo "</td><td align='center'>"; echo $row['land']; echo "</td><td align='center'>"; echo $row['age']; echo "</td></tr>"; } echo "</table>"; mysql_free_result($result); So my question is .. how do i make the first piece of code selectable to produce similar results to the second piece of code based on the city selected ? Thanks for any help .. and please excuse my ignorance .. Thank you for writing this script. It has been most helpful in doing a search for a website I manage. Everything is working fine but I would like some help in modifying the "$results[] = " line. For instance, I would like to show or hide the address of a business if a data value is set to 1 if set to 0 then hide. Same for the business web address. if ( $row_memberrs['WebAddress'] != NULL ) { echo <a href=\"{$row['WebAddress']}\" target=_blank>Visit our website</a>; } I am a newbie to php and would appreciate any help you can give me. Here is a link to the search page http://www.wildwoodba.org/searchsite.php If it is not too much trouble I would like to hide the check boxes and make it search the body, title or disc for the words entered. Thank you for your help. Hey all, I need your help! So, I am the web designer for a small company, but I use that term loosely as I for the most part am limited to design through Dreamweaver and Muse. I know a decent amount of HTML off the top of mey head, but when it comes to PHP, yikes... My company asked me to make a simple searchable web page based on their price guide/catalog, built into their website. I have MySQL set up within their godaddy. I can use the SQL search functions to get the exact results back that I need, and the SQL cPanel gives me the following code: SELECT * FROM `SMQSQL` WHERE `Scott` = '(Whatever I search for)' ORDER BY `LINEID` ASC This makes sense to me up to here; this is very simple language, However, I have been pulling my hair out for days trying to get a simple search function as an actual PHP *PAGE* going. Basically, I need to set up a PHP form search (not hard) that will go back and log in to my SQL database named SMQ (not too bad yet), perform a search out of a specific column named Scott (getting a little harder, and somewhat lost), take the search results from specific columns (getting harder), and display them in a neat little table (now I'm lost). My SQL database is set up with the following columns: LINEID, Scott, Den, Color, Cond, 70, 70J, 75, 75J, 80, 80J, 85, 85J, 90, 90J, 95, 95J, 98, 98J, 100 Where LINEID is the index. LINEID is set to INT (5 char), the next 4 are TEXT (255 char, item descriptors), and the rest INT (9 char; prices). When the results are displayed, I would like all but the LINEID visible. I have tried and tried and tried playing with my PHP coding but am ready to shoot my computer. Here it is: <!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> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Online Search</title> </head> <body> <h3>Search Online</h3> <p>You may search by Catalog number. Please use the exact Catalog number or you may receive an error. Please note that if searching for more than a basic item, include the full Catalog number WITHOUT spaces.</p> <form method="post" action="search.php?go" id="searchform"> <input type="text" name="Scott"> <input type="submit" name="submit" value="Search"> </form> <?php if(isset($_POST['submit'])){ if(isset($_GET['go'])){ $Scott=$_POST['Scott'];; $db=mysql_connect ("localhost", "guestuser", "guestuser") or die ('Error connecting to the database. Error: ' . mysql_error()); $mydb=mysql_select_db("SMQ"); $sql="SELECT Scott, Den, Color, Cond, 70, 70J, 75, 75J, 80, 80J, 85, 85J, 90, 90J, 95, 95J, P98, 98J, 100 FROM SMQ WHERE Scott LIKE '%" . $Scott . "%'; $result=mysql_query($sql); while($row=mysql_fetch_array($result)){ $Scott=$row['Scott']; $Den=$row['Den']; $Color=$row['Color']; $Cond=$row['Cond']; $70=$row['70']; $70J=$row['70J']; $75=$row['75']; $75J=$row['75J']; $80=$row['80']; $80J=$row['80J']; $85=$row['85']; $85J=$row['85J']; $90=$row['90']; $90J=$row['90J']; $95=$row['95']; $95J=$row['95J']; $98=$row['98']; $98J=$row['98J']; $100=$row['100']; echo "<ul>\n"; echo "<li>" . "<a href=\"SMQ.php?id=$Scott\">" .$Scott . " " . $Den . " " . $Color . " " . $Cond . " " . $70 . " " . $70J . " " . $75 . " " . $75J . " " . $80 . " " . $80J . " " . $85 . " " . $85J . " " . $90 . " " . $90J . " " . $95 . " " . $95J . " " . $98 . " " . $98J . " " . $100 . "</a></li>\n"; echo "</ul>"; } } else{ echo "<p>Please enter a search query</p>"; } ?>I know it's probably pretty bad, but hopefully at least you can get an idea of what I'm trying to accomplish. Please dear God tell me what I am doing wrong! I'm sure it will take a knowledgeable user 5 minutes to fix this, but you would be saving my skin! THANKS!!! Edited by mac_gyver, 14 August 2014 - 11:04 AM. removed link to op's cp and code tags please when posting code hi iam trying to make a simple search form to search the members tables based on there input. iam new php so most of my code is guess work Code: [Select] <form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm"> <label for="country">Country:</label> <input type="text" name="country" /> <label for="state">State:</label> <input type="text" name="state" /> <label for="city">City:</label> <input type="text" name="city" /> <input type="submit" value="submit" /> </form> <? if ($_GET == array ()) { //Define a variable that will be used to query the members; in this case, it would select all members $query = "SELECT * FROM users"; } else { //If the user typed at least one thing (in the form OR the url) if (count ($_GET) == 1) { //If what they typed is only for one criteria, define a variable that creates a query for only ONE criteria to search for $query = "SELECT * FROM users WHERE 1"; foreach ($_GET as $field => $value) { $query .= " AND $field = '$value'"; } //If the user has typed in more than one field and hits search } else { //Define a variable for a query that selects members based off each criteria $query = "SELECT * FROM users WHERE 1"; foreach ($_GET as $field => $value) { $query .= " AND $field LIKE '%$value%'"; } } while($info = mysql_fetch_array( $data )) { Echo "<img src='http://datenight.netne.net/images/".$info['img'] ."' width='150' height='250''> <br>"; Echo "<b>Name:</b> ".$info['username'] . "<br> <hr>"; Echo "<b>Sex:</b> ".$info['sex'] . " <br><hr>"; Echo "<b>Intrested in</b>" . "<br><hr>"; Echo "".$info['rel'] . " "; Echo "".$info['frwb'] . " "; Echo "".$info['ons'] . " "; Echo "".$info['fr'] . "<br><hr>"; Echo "<b>About me:</b> ".$info['aboutme'] . "<br><hr> "; Echo "<b>Looking for:</b> ".$info['looking'] . " <br><hr>"; Echo "<a href='login_success.php'>'Back'</a>"; } ?> </body> </html> while($info = mysql_fetch_array( $data )) { is not vaild error I found this amazing tutorial and i try to change it for a different database, but when i do a search it never finds anything. <?php $dbHost = 'localhost'; // localhost will be used in most cases // set these to your mysql database username and password. $dbUser = 'root'; $dbPass = '123'; $dbDatabase = 'ergasia2'; // the database you put the table into. $con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error()); mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error()); // 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) < 3) { $error[] = "Ο όρος αναζήτησις πρέπει να είναι έχει περισσότερους από 3 χαρακτήρες."; }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 Fname, Surname, StreetName, status FROM EMPLOYEES WHERE "; // grab the search types. $types = array(); $types[] = isset($_GET['Fname'])?"`Fname` LIKE '%{$searchTermDB}%'":''; $types[] = isset($_GET['Surname'])?"`Surname` LIKE '%{$searchTermDB}%'":''; $types[] = isset($_GET['StreetName'])?"`StreetName` LIKE '%{$searchTermDB}%'":''; $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked) if (count($types) < 1) $types[] = "`sbody` 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 `stitle`"; // 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['stitle']}<br />{$row['sdescription']}<br />{$row['sbody']}<br /><br />"; $i++; } } } } function removeEmpty($var) { return (!empty($var)); } ?> <html> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>My Simple Search Form</title> <style type="text/css"> #error { color: red; } </style> <body> <?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?> <form method="GET" action="<?php echo $_SERVER['PHP_SELF'];?>" name="searchForm"> Search For: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /><br /> Search In:<br /> Body: <input type="checkbox" name="body" value="on" <?php echo isset($_GET['body'])?"checked":''; ?> /> | Title: <input type="checkbox" name="title" value="on" <?php echo isset($_GET['title'])?"checked":''; ?> /> | Description: <input type="checkbox" name="desc" value="on" <?php echo isset($_GET['desc'])?"checked":''; ?> /><br /> Match All Selected Fields? <input type="checkbox" name="matchall" value="on" <?php echo isset($_GET['matchall'])?"checked":''; ?><br /><br /> <input type="submit" name="submit" value="Search!" /> </form> <?php echo (count($results) > 0)?"Your search term: {$searchTerms} returned:<br /><br />" . implode("", $results):""; ?> </body> </html> The table which i use is the following ---------------- |EMPLOYEES| ---------------- |ssn | ---------------- |Fname ---------------- |postal code | ---------------- |salary | ---------------- |street name| ---------------- |street number | ------------------- |surname | ----------------- |UnionMembershipNumber| --------------------------------- |password | ----------------- |status | ---------------- Need some help I have 2 tables in a database and I need to search the first table and use the results from that search, to search another table, can this be done? and if it can how would you recommend that I go about it? Thanks For Your Help Guys! Hey guys, Hi all. This is the code I've been trying to execute. <?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>No search parameter</p>"; exit; } //connect to your database ** EDIT REQUIRED HERE ** mysql_connect("localhost","*","*"); //(host, username, password) //specify database ** EDIT REQUIRED HERE ** mysql_select_db("my_db") or die("Can't select database//Does not exist."); //select which database we're using // Build SQL Query $query = "select * from people \"%$trimmed%\" order by FirstName"; // 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>"; 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"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["FirstName"]; 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); 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 " <a href=\"$PHP_SELF?s=$news&q=$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>"; ?> As you can see, it's pretty simple and it's got very nice explanations of what everything does. But when I try it, I get this. Quote Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in D:\Program Files\xampp\xampp\htdocs\search.php on line 36 Results Sorry, your search: "Ella" returned zero results Click here to try the search on Google Couldn't execute query I'm pretty much stuck. Any ideas what that error means? And yes, there is a entry with the name of Ella in the people table of the database. Help? 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 I am currently looking to have two pages, one with a search form (textbox and button) and output the results (from database table) based on the strings input to another page. how do i achieve this? i just want something very simple nothing too complex and advanced please I found this nice search database script on line but the pagination does not work can someone tell me what is wrong with it ???? so i can work with it !!! here is the full code : Code: [Select] <?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("localhost","username","password"); //(host, username, password) //specify database ** EDIT REQUIRED HERE ** mysql_select_db("database") or die("Unable to select database"); //select which database we're using // Build SQL Query $query = "select * from the_table where 1st_field like \"%$trimmed%\" order by 1st_field"; // 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>"; 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"; $count = 1 + $s ; // now you can display the results returned while ($row= mysql_fetch_array($result)) { $title = $row["1st_field"]; 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); 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 " <a href=\"$PHP_SELF?s=$news&q=$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>"; ?> Can someone please double check my search query to make sure it is the minimum and most efficient coding. My goal is an exact match search of field1 from my database table and list field1, field2, field3, field4 and field5 if the part number is in the database or no results if it is not. The query works as is but I have a feeling it could be done more efficiently or professionally and minimum work for my poor little server. Thanks in advance. Code: [Select] <?php //connect to the database include("./databaseconnect.php"); //get query $q=$_GET['q']; //convert query to uppercase & remove all spaces and special charactars $q=strtoupper(preg_replace("/[^A-Za-z0-9]/","",$q)); //if blank query if ($q == "") { echo "You did not enter a search term"; } else { //exact match only query $query = "SELECT * FROM ".$dbtable." WHERE field1 like \"$q\""; $result = mysql_query($query); //if query returns no results if(mysql_num_rows($result)==0) { echo "<span class=\"noresults\">There were no results for your search</span>"; //display database results } else { while($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo "<span class=\'results\'>SEARCH RESULTS</span><br /> <span class=\'list\'>Part Number: ".$row['field1']."<br /> Manufacturer: ".$row['field2']."<br /> Cost per unit: ".$row['field3']."<br /> Warehouse Location: ".$row['field4']."<br /> Quantity Available: ".$row['field5']."<br /> Notes: ".$row['field6']."<br /> </span>"; } } } ?> <?php if(isset($_POST['ActivityId'])) { require_once('database.php'); $Search=$_POST['Search']; $query="select * from registration where Flag='A' AND Activity like '%,$Search,%'"; $result=mysqli_query($dbc,$query) or die('Not Connected'); while($row=mysqli_fetch_array($result)) { echo "<table border='2'><tr><td> Name--".$row['Name']."</td> <td>Contact Number--".$row['ContactNumber']."</td> <td>Email--".$row['Email']."</td> <td>Address--".$row['Address']."</td></tr></table>"; } } elseif(isset($_POST['EventId'])){ require_once('database.php'); $Search=$_POST['Search']; $query="select * from participation where EventId ='$Search'"; $result=mysqli_query($dbc,$query) or die('Not Connected'); while($row=mysqli_fetch_array($result)){ $LoginId= $row['LoginId']; echo $LoginId;} $query="select * from registration where LoginId='$LoginId'"; $result=mysqli_query($dbc,$query) or die('Not Connected to Reg'); while($row=mysqli_fetch_array($result)){ echo "<table border='2'><tr><td> Name--".$row['Name']."</td> <td>Contact Number--".$row['ContactNumber']."</td> <td>Email--".$row['Email']."</td> <td>Address--".$row['Address']."</td></tr></table>"; }} elseif(isset($_POST['Location'])) { require_once('database.php'); $Search=$_POST['Search']; $query="select * from registration where Flag='A' AND Address like '%$Search%'"; $result=mysqli_query($dbc,$query) or die('Not Connected'); while($row=mysqli_fetch_array($result)) { echo "<table border='2'><tr><td> Name--".$row['Name']."</td> <td>Contact Number--".$row['ContactNumber']."</td> <td>Email--".$row['Email']."</td> <td>Address--".$row['Address']."</td></tr></table>"; } } elseif(isset($_POST['BloodGroup'])) { require_once('database.php'); $Search=$_POST['Search']; $query="select * from registration where Flag='A' AND BloodGroup ='$Search'"; $result=mysqli_query($dbc,$query) or die('Not Connected'); while($row=mysqli_fetch_array($result)) { echo "<table border='2'><tr><td> Name--".$row['Name']."</td> <td>Contact Number--".$row['ContactNumber']."</td> <td>Email--".$row['Email']."</td> <td>Address--".$row['Address']."</td></tr></table>"; } } ?> <html><body><form action='<?php echo $_SERVER['PHP_SELF']?>' method="post"> <input type="text" name="Search"><br> <input type="submit" name="ActivityId" value="Submit Activity Id"><br> <input type="submit" name="EventId" value="Submit Event Id"><br> <input type="submit" name="Location" value="Submit Location"><br> <input type="submit" name="BloodGroup" value="Submit Blood Group"><br> </form> </body></html> Hi frds............. I have two tables named "registration" and "participation". Registration table have some columns like "LoginId", "email","contact no.", "Name" etc.and participation table have 2 column named "LoginId" and "EventId". Now if user enters EventId, I want to display the details like email,contact no. etc. I have a code but it not works properly....... If result have more than one row it only displays the email and contact no. of last one instead of all. Plzzzzzzzzz help anyone................... ????????/ 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"); } |