PHP - Simple Sql Search -tutorial Help
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 | ---------------- Similar Tutorialsim a complete novice. im using one of the tutorials on here to make a simple search form. the bit of script that i think outputs the results is $results = array(); // the result array $i = 1; while ($row = mysql_fetch_assoc($searchResult)) { $results[] = "{$i}: {$row['placing']},   {$row['racedate']},   {$row['horseid']}<br /><br />"; $i++; how do i make these results appear in a table, and how would i make it so there was a link on the date that clicked would show all the races on that day? sorry i advance as this is probably the most dumb of questions! Hello, Does anyone know a tutorial I can follow to create my own search engine over the items I have in my SQL database? I find a lot of tutorials but they are all 'one word searches' which means if you type two words you will get all results that contain either word (too many hits). If the search engine tutorial displays result with AJAX even better. Thanks for help. df Hello, I'm making a website which includes an articles page. I want users to be able to search for particular articles. For this search function I used the Simple SQL Search tutorial from phpfreaks (http://www.phpfreaks.com/tutorial/simple-sql-search). It's working quite well but i'd like to expand it a little. The most important thing i want changed is what happens when users enters a string which holds multiple words. The function from the tutorial perceives these words as one string and searches for that string as a whole. For example when a user enters 'winter 2012' and an article holds the string 'winter of 2012', the function returns no matches. This is, ofcourse, not the way i'd like it to function. I've managed to seperate the words and search for them individually by using explode and foreach, but now i'm getting duplicate results when an article holds mulitple words from the users' entry string. My idea to fix this was to make an array with the article id's of the articles that have matched, and then to exclude them from the SQL query for the next word from the search string by using 'NOT IN $array' in the where clause. Unfortunately i haven't managed to succeed with this so far and that's why i ask for your help.. This my search function: Code: [Select] function zoekopdracht() { require('dbcon.php'); $zoekopdr = trim($_GET['zzoek']); $zoekopdr = strip_tags($zoekopdr); if (strlen($zoekopdr) < 3) { echo "De zoekopdr moet minimaal 3 karakters bevatten."; } else { $zoekopdr = explode(" ", $zoekopdr); foreach($zoekopdr as $zoekterm) { $zoekopdrDB = mysql_real_escape_string($zoekterm); $searchSQL = "SELECT * FROM n_artikelen WHERE "; $types = array(); $types[] = isset($_GET['zartikel'])?" volledig_artikel LIKE '%{$zoekopdrDB}%'":''; $types[] = isset($_GET['ztitel'])?" titel LIKE '%{$zoekopdrDB}%'":''; $types[] = isset($_GET['zjaar'])?" YEAR(publicatie) LIKE '%{$zoekopdrDB}%'":''; $types = array_filter($types, "removeEmpty"); // removes any item that was empty (not checked) if (count($types) < 1) { $types[] = "volledig_artikel LIKE '%{$zoekopdrDB}%'"; // use the artikel + titel as a default search if none are checked $types[] = "titel LIKE '%{$zoekopdrDB}%'"; } $searchSQL .= implode(" OR ", $types) . " ORDER BY publicatie LIMIT 0,10"; $searchResult = mysql_query($searchSQL) or die(mysql_error()); if (mysql_num_rows($searchResult) < 1) { echo "De zoekopdracht '{$zoekopdr}' heeft geen resultaten."; } else { while ($row = mysql_fetch_array($searchResult, MYSQL_NUM)) { artikelelement($row); // function that outputs the result of $row[] } } } } } Additionally, if this problem is fixed, i'd love to see a way to sort the results on closest match (article which matches two words > article which matches one word). Thanks! Hey guys, need some help real quick. I'm using this walkthrough over at css-tricks, some might be familiar with it by now? Anyway, I've followed the instructions exactly. It's supposed to display a simple form that you fill out and submit, which then updates the MYSQL database. However, whenever i load display.php in my browser, all i get is a blank page, and there are no notifications or errors to be in seen in the console. Any help is greatly appreciated. Thanks! Here's my code: SimpleCMS.zip 3.7KB 0 downloads display.php <!DOCTYPE html> <html lang="en"> Hey guys, I'm looking for some sort of tutorial on how to code a search script which would allow users to select number of results per page (and take care of the page 1, page 2, etc. links accordingly) as well as order them by date, most views, etc. I thought I'd be good to do this on my own but my script is looking very dirty and I'm pretty sure it isn't very secure.. anyone ever consult a tutorial with main guidance as how to code the kind of script I'm interested in?? thanks 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>"; ?> 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>"; ?> 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. 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 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 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.... 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 am wanting to write a script that will allow a user to search youtube videos! What I have so far is not working yet, but I know it can be done! I found this code and it works and its not a million api files to get one thing working! Code: [Select] <?php # YouTube Video Collector - YouTube.class.php ##################################################### # # # YouTube Video Collector 2010 # # # # Author: CMBSystems (Chris Bearcroft) # # Copyright: CMBSystems 2010, All Rights Reserved # # Last Modded: 29-09-2010, 1:26 AM (GMT) # # # ##################################################### class YouTube { public function getURL($Search){ if(!empty($Search)){ $Search=split("\n",$Search); for($i=0;$i<count($Search);$i++){ $SearchURL=urlencode($Search[$i]); $SearchURL="http://www.youtube.com/results?search_category=10&search_type=videos&search_query={$SearchURL}"; preg_match('/\/watch\?v=(.*?)\"/',file_get_contents($SearchURL),$URL); if(strpos($URL[1],'&')){$URL=split('&',$URL[1]);$URL=$URL[0];}else{$URL=$URL[1];} $array[]="http://www.youtube.com/watch?v={$URL}"; } return $array; } } public function printForm($Search){ $Search=htmlspecialchars(stripslashes($Search)); return "<form method=\"get\" action=\"\">\n <table>\n <tr>\n". " <td><textarea cols=\"60\" rows=\"15\" name=\"search_query\">{$Search}</textarea></td>\n". " </tr>\n <tr>\n <td align=\"right\"><input type=\"submit\" value=\"Search YouTube\" /></td>\n". " </tr>\n </table>\n</form>\n"; } } ?> Code: [Select] <?php # YouTube Video Collector - YouTube.php ##################################################### # # # YouTube Video Collector 2010 # # # # Author: CMBSystems (Chris Bearcroft) # # Copyright: CMBSystems 2010, All Rights Reserved # # Last Modded: 29-09-2010, 1:26 AM (GMT) # # # ##################################################### # Require the YouTube class require 'YouTube.class.php'; # Set the PHP vars $Form = YouTube::printForm($_GET['search_query']); $Result = YouTube::getURL($_GET['search_query']); print <<<YTVSC <!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>YouTube Collector</title> </head> <body> {$Form} YTVSC; print_r($Result); print <<<YTVSC </body> </html> YTVSC; ?> It allows me to have a feed link on my site to get the data http://claritydreams.com/youtube/YouTube.php?YT_Search=Staind I can push that ?YT_Search as a search from with in my client but I want to convert the file in to xml to read the data back into the client. ugh... 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 ;... The result pages is supposed to have pagination like google help me please
I followed the tutorial at http://www.devshed.com/c/a/PHP/Building-An-Extensible-Form-Validator-Class/ because I wanted to have an easier way to build and maintain form validation. I completed the tutorial, but the form does not register the form as being filled out. Here is the class code (FormValidator.class.inc) <?php //FormValidator.class.inc //class to perform form validation class FormValidator { //---------------private variables------------------ var $_errorList; //the _ prefix is used to distinguish private variables from public variables //---------------methods (private)------------------ //functio to get the value of a variable (field) function _getValue($field) { global ${$field}; //makes the field entry a global variable return ${$field}; } //---------------methods (public)------------------- //it is a good idea to run resetErrorList() whenever the class is first initialized //PHP makes it possible to automatically execute a specific function when a new instance of a class is spawned. This function is referred to as a "constructor" and must have the same name as the class. //reset error list function FormValidator() { $this->resetErrorList(); } //begin basic validation routines //check whether input is empty //the isEmpty public method is called with 2 arguments, one for the form variable and one for the error message //the method internally calls the _getValue method and then trim()s the result to check if it is empty // if the variable is empty, a new element is added class variable $_errorList (an array) to represent the error. This new element is itself a three-element associative array, with the keys "field", "value" and "msg", representing the form variable name, the current value of that variable, and the corresponding error message // if the variable is not empty, it will pass the test and return true // this function, along with _getValue, allows the user to get both the field name and the field value //the $this prefix provides a convenient way to access variables and functions which are "local" to the class. function isEmpty($field, $msg) { $value = $this->_getValue($field); if (trim($value) == "") { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether input is a string function isString($field, $msg) { $value = $this->_getValue($field); if(!is_string($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether input is a number function isNumber($field, $msg) { $value = $this->_getValue($field); if(!is_numeric($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether input is an integer function isInteger($field, $msg) { $value = $this->_getValue($field); if(!is_integer($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether input is a float function isFloat($field, $msg) { $value = $this->_getValue($field); if(!is_float($value)) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether input is within a valid numeric range function isWithinRange($field, $msg, $min, $max) { $value = $this->_getValue($field); if(!is_numeric($value) || $value < $min || $value > $max) { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } else { return true; } } //check whether the input is alphanumeric function isAlpha($field, $msg) { $value = $this->_getValue($field); $pattern = "/^[a-zA-Z]+$/"; if (preg_match($pattern, $value)) { return true; } else { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } } //check whether input is a valid email address function isEmailAddress($field, $msg) { $value = $this->_getValue($field); $pattern = "/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/ "; if (preg_match($pattern, $value)) { return true; } else { $this->_errorList[] = array("field" => $field, "value" => $value, "msg" => $msg); return false; } } //end basic validation routines----- //return the list of current errors function getErrorList() { return $this->_errorList; } //check whether any errors have occured in validation //this method checks the size of the $_errorList array; if the size is greater than one, it implies that one or more errors have occured during validation //it returns a Boolean value function isError() { if(sizeof($this->_errorList) > 0) { return true; } else { return false; } } //reset the error list to a blank array function resetErrorList() { $this->_errorList = array(); } }//end FormValidator class ?> -------Here is the form (simpleform.html) <html> <head> <basefont face="Arial"> </head> <body> <form action="processor.php" method="POST"> <b>Name:</b> <br> <input type="text" name="name" size="15"> <p> <b>Age:</b> <br> <input type="text" name="age" size="2" maxlength="2"> <p> <b>Sex:</b> <br> <input type="Radio" name="sex" value="m">Male <input type="Radio" name="sex" value="f">Female <p> <b>Favourite sandwich type:</b> <br> <select name="stype"> <option value="">-select one-</option> <option value="1">Thin crust</option> <option value="2">Thick crust</option> <option value="3">Toasted</option> </select> <p> <b>Favourite sandwich filling:</b> <br> <input type="Checkbox" name="sfill[]" value="BLT">Bacon, lettuce tomato <input type="Checkbox" name="sfill[]" value="EC">Egg and cheese <input type="Checkbox" name="sfill[]" value="PBJ">Peanut butter and jelly <p> <input type="Submit" name="submit" value="Save"> </form> </body> </html> ------and here is processor.php <?php //include class include("FormValidator.class.inc"); // instantiate object $fv = new FormValidator(); //perform validation $fv->isEmpty("name", "Please enter a name"); $fv->isNumber("age", "Please enter a valid age"); $fv->isWithinRange("age", "Please enter an age within the numeric range 1-99", 1, 99); $fv->isEmpty("sex", "Please enter your sex"); $fv->isEmpty("stype", "Please select one of the listed sandwich types"); $fv->isEmpty("sfill", "Please select one or more of the listed sandwich fillings"); if($fv->isError()) { $errors = $fv->getErrorList(); echo "<b>The operation could not be performed because one or more error(s) occurred.</b> <p> Please resubmit the form after making the following changes:"; echo "<ul>"; foreach($errors as $e) { echo "<li>" . $e['msg'] . "</li>"; } echo "</ul>"; } else { //do something useful with the data echo "Data OK"; } ?> Hello Php Freaks I am following this tutorial how to make a login for my website, the only trouble is that... It dosen't seem to work, so i wanna know if its only me who cant make it work... and if it is why XD... Tutorial can be found he http://www.knowledgesutra.com/forums/topic/7887-php-simple-login-tutorial/ Now when i get started it starts saying error at line 6: if ($_GET["op"] == "login") It says that when im about to login right above the login. Now when i put in data i get error on line 19: $r = mysql_query($q); That one, and i have no idea how to fix it. Anyone please ? This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=308352.0 I have a need to create a form that will get info from a mysql table, show that info, two fields one of which I want to be a checkbox that will need to update the table with either a 0 or a 1. I will later use that info. I have searched all over and haven't found what I am looking for. I can find tutorials for creating checkboxes but nothing what I need / want
This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=130332.0 |