PHP - Php/mysql Usage = Display Full List, Checkbox Each Record Where User Is 'yes'
Hey guys, I can't wrap my head around how to make this work right...
I have three tables: Code: [Select] CREATE TABLE `games` ( `g_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(150) DEFAULT NULL, PRIMARY KEY (`g_id`)); CREATE TABLE IF NOT EXISTS `game_player` ( `r_id` int(11) NOT NULL AUTO_INCREMENT, `p_id` int(11) DEFAULT NULL, `g_id` int(11) DEFAULT NULL, `bool` int(1) NOT NULL DEFAULT '0', PRIMARY KEY (`r_id`)); CREATE TABLE IF NOT EXISTS `players` ( `p_id` int(11) NOT NULL AUTO_INCREMENT, `playerid` varchar(150) NOT NULL, PRIMARY KEY (`p_id`), UNIQUE KEY `playerid` (`playerid`)); The players table is my list of users, and they're tied to the list of games via the game_player table. So here's my issue... I'm trying to show the full list of games, and then check mark each record where the player does play it. This is what I have so far - it shows all the games, but it's not checking the boxes. Code: [Select] $result = mysql_query("SELECT * FROM games") or die(mysql_error()); while($row = mysql_fetch_array($result)) { $newquery = "SELECT * FROM game_player, players WHERE game_player.p_id = players.p_id AND game_player.g_id = ".$row['g_id']. " AND players.playerid = {$userid}"; $query = mysql_query($newquery) or die(mysql_error()); if($query['bool'] == 1) { $set_checked = " CHECKED"; } else{ $set_checked = ""; } echo "<input type=\"checkbox\" name=\"box1\" value=\"".$query['g_id']."\"" . $set_checked . "/>".$row['name']."<br />\n"; } Similar TutorialsHi, basically, here's the deal: I have a lit of checkboxes that are added by the admin (there's an unlimited amount, just depends on how many are added). Then, those are put in a form, in which the user picks whichever ones need to be chosen and those values get sent to a MySQL table. Here's the code that displays the checkboxes Code: [Select] <?php $sql="SELECT * FROM category ORDER BY categoryID ASC"; $result=mysql_query($sql); while($row=mysql_fetch_array($result)){ echo "<input type='checkbox' id='". $row['categoryName'] ."' name='licensed[]' value='" . $row['categoryID'] ."' /><label for='". $row['categoryName'] ."'><br>" . $row['categoryName'] ."</label><br>"; } ?> What I'm making now, is an edit form where whichever checkboxes were checked, will show up checked in the edit form. But I'm not really sure how to go about this, since there is only one actual input tag in the code, I can't select the different ones. I also have this SQL query which selects whichever boxes were inputted into the DB Code: [Select] $sql2="SELECT * FROM category, categoryInfo WHERE category.categoryID = categoryInfo.categoryID AND categoryInfo.parentID = $parentID"; $result2=mysql_query($sql2); Where $parentID is the ID of whichever form you're editing. But yes, I'm basically not really sure how to go about this and would like some help figuring this out Thanks for your time Ok, so I've spent quite a bit of time piecing together this solution from a variety of sources. As such, I may have something in my code below that doesn't make sense or isn't neccessary. Please let me know if that is the case. I'm creating an administrative form that users will you to add/remove items from a MySQL table that lists open positions for a facility. The foreach loop generates all of the possible job specialties from a table called 'specialty_list'. This table is joined to a second table ('open_positions') that lists any positions that have been selected previously. Where I'm stuck is getting the checkbox to be checked if the facility_ID from the open_positions table matches the $id passed in the URL via ?facility_id=''. Here's where I am so far: $query = "SELECT specialty_list.specialty_displayname , specialty_shortname , open_positions.position , facility_ID FROM specialty_list LEFT OUTER JOIN open_positions ON open_positions.position = specialty_list.specialty_shortname ORDER BY specialty_list.specialty_shortname"; $results = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($results)) { $positions[$row['specialty_shortname']] = $row['specialty_displayname']; } echo "<form method='POST' action='checkbox.php'>"; foreach($positions as $specialty_shortname => $specialty_displayname) { $facility_ID = $row['facility_ID']; $checked = $facility_ID == $row['facility_ID'] ? ' checked' : ''; echo "<input type='checkbox' name='position[]' value=\"{$specialty_shortname}\"{$checked}> {$specialty_displayname}</input><br/>"; } echo "<input type='hidden' name='facility_ID' value='$id'>"; echo "<input type='submit' value='Submit Checkboxes!'>"; echo "</form>"; Any ideas how to get this working? I feel like I'm very close, but I just can't get it. I also tried starting from scratch with a WHILE statement instead of a FOREACH, but haven't tweaked it enough to prevent duplicate checkboxes. With that in mind, here it is, just in case that's a better direction: $query = "SELECT specialty_list.specialty_displayname , specialty_shortname , open_positions.position , facility_ID FROM specialty_list LEFT OUTER JOIN open_positions ON open_positions.position = specialty_list.specialty_shortname ORDER BY specialty_list.specialty_shortname"; $results = mysql_query($query) or die(mysql_error()); echo "<form method='POST' action='checkbox.php'>"; while($row=mysql_fetch_assoc($results)) { $facility_ID = $row['facility_ID']; $specialty_shortname = $row['specialty_shortname']; $specialty_displayname = $row['specialty_displayname']; if ($facililty_ID==$id) { $checked=' checked'; } echo "<input type='checkbox' name='position[]' value=\"$specialty_shortname\"$checked> $specialty_displayname</input><br/>"; } echo "<input type='hidden' name='facility_ID' value='$id'>"; echo "<input type='submit' value='Submit Checkboxes!'>"; echo "</form>"; Hello there, I'm trying to make when you click on a record, it opens another page with full details about this record the code for it is Code: [Select] <td><a href=\"user.php?id=".$row['id']."\">".$row['id']."</a></td> and it's working right, but when it opens the other page, no records is shown about the user with that ID So I figure the problem that I need to pass $row['id'] to my second page and make it search for it in the database how can I do that? here is the code from the second page (details of the record) Code: [Select] $dbObj = new DB(); $result = mysql_query("select * from users where id = '$userID'"); return $result; $row = @mysql_fetch_array($result); echo "<table width=98%>"; echo "<tr>"; echo "<td valign=\"top\" width=\"120px\">"; $rowid = $row['id']; echo "<td valign=\"top\">"; echo "<table> <tr> <td valign=\"top\" class=\"searchtitle\"> ".$row['fname']. ' ' .$row['mname']. ' ' .$row['lname']." </td> </tr> <tr> <td class=\"text\" valign=\"top\"> ".$row['mobile']." </td> </tr> <tr> <td> <a href=\"user.php?id=".$row['recruiterid']."\" class=\"link\">".$row['recruiterid']."</a> </td> </tr> </table>"; echo "</td>"; echo "</tr>"; echo "</table>"; Hi, I use the following code to create a select menu from an array of options stored in LISTS.php: include 'LISTS.php'; print('<select id="from" name="from">'); foreach ($langList as $lang) {printf('<option %s>%s</option>', ($from1 == $lang ? 'selected="selected"' : ''), $lang); } echo '</select>'; where LISTS.php includes the following: $langList = array(' ','English', 'French', 'German', 'Dutch', 'Spanish'); This works great, but now I want to do something similar with a checkbox list, where each checkbox has an associated 'onchange' javascript function and I'm getting pretty stuck. My checkbox list is of the following form: Code: [Select] <html> <ul style="height: 95px; overflow: auto; width: 200px; border: 1px solid #480091; list-style-type: none; margin: 0; padding: 0;"> <li id="li1b"><label for="chk1b"><input name="chk1b" id="chk1b" type="checkbox" onchange="function1('chk1b','li1b')">Option1</label></li> <li id="li2b"><label for="chk2b"><input name="chk2b" id="chk2b" type="checkbox" onchange="function1('chk2b','li2b')">Option2</label></li> //etc. </ul> </html> What I want to do is have 'Option1', 'Option2', etc. stored in an array in LISTS.php and have a PHP script that populates the checkbox list accordingly, in a similar manner to my select menu above. I can't work out how to get the ID of the next <li> and the next <input> in the list to go up by one each time, e.g. 'li1b' then 'li2b', 'li3b', etc. Could someone pls help me out? Thanks! I posted a topic earlier and there was confusion as to what I could not work out.
I am able to display the checkbox, either checked or unchecked depending of the value or 1 or 0 in the obcDisplay field.
<input type="checkbox" name="obcDisplay" value="<?=$r['obcDisplay'] ?>" <?=($r['obcDisplay']) ? 'checked="checked"' : ''; ?>/>I am trying to update the DB table by the checkbox. If the checkbox is checked (obcDisplay = 1) and I uncheck the box and submit, I want the table updated so that obcDisplay now equals 0. When the form is displayed, the checkbox is now uncheck (obcDisplay = 0). Now I check the box and submit and the update changes the field from 0 to 1. I can display the checkbox as checked or unchecked by the DB field obcDisplay being either 0 or 1. It is changing the value where I am having the problem. Hi, Firstly, I am a complete newcomer to PHP though I am enjoying my first tentative steps into learning the language! I have been searching Google for hours now to try and find a simple solution to a problem I just can't seem to figure out, though I thought would be easy to find? I have found a lot of very informative solutions to other questions on this forum so figured it was the best one to join? My question is: I have built and can interact with a simple database and now populate a page with usernames in a list. Each one is a link which, when clicked sends the username to another page. On this page I use the $_GET function and see the username displayed ok. What I can't figure out is how to then display other information about them from the fields in the database identified with that user? Any help would be greatly appreciated as this is driving me nuts! Also can anyone suggest a good book for learning PHP? There are lots out there but the reviews on Amazon seem to always talk about coding errors in print etc. so I really don't know which one to buy? FF I would appreciate your assistance, there are tons of login scripts and they work just fine. However I need my operators to login and then list their activities for the other operators who are logged in to see and if desired send their clients on the desired activity. I have the login working like a charm and the activities are listed just beautifully. How do I combine the two tables in the MySQL with PHP so the operator Logged in can only make changes to his listing but see the others. FIRST THE ONE script the member logges in here to the one table in MSQL: <?php session_start(); require_once('config.php'); $errmsg_arr = array(); $errflag = false; $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD); if(!$link) { die('Failed to connect to server: ' . mysql_error()); } $db = mysql_select_db(DB_DATABASE); if(!$db) { die("Unable to select database"); } function clean($str) { $str = @trim($str); if(get_magic_quotes_gpc()) { $str = stripslashes($str); } return mysql_real_escape_string($str); } $login = clean($_POST['login']); $password = clean($_POST['password']); if($login == '') { $errmsg_arr[] = 'Login ID missing'; $errflag = true; } if($password == '') { $errmsg_arr[] = 'Password missing'; $errflag = true; } if($errflag) { $_SESSION['ERRMSG_ARR'] = $errmsg_arr; session_write_close(); header("location: login-form.php"); exit(); } $qry="SELECT * FROM members WHERE login='$login' AND passwd='".md5($_POST['password'])."'"; $result=mysql_query($qry); if($result) { if(mysql_num_rows($result) == 1) { session_regenerate_id(); $member = mysql_fetch_assoc($result); $_SESSION['SESS_MEMBER_ID'] = $member['member_id']; $_SESSION['SESS_FIRST_NAME'] = $member['firstname']; $_SESSION['SESS_LAST_NAME'] = $member['lastname']; session_write_close(); header("location: member-index.php"); exit(); }else { header("location: login-failed.php"); exit(); } }else { die("Query failed"); } ?> ................................................. ................................ Now I need the person who logged in to the table above to be able to make multiple entries to the table below <? $ID=$_POST['ID']; $title=$_POST['title']; $cost=$_POST['cost']; $activity=$_POST['activity']; $ayear=$_POST['aday']; $aday=$_POST['ayear']; $seats=$_POST['special']; $special=$_POST['seats']; mysql_connect("xxxxxx", "xxx350234427", "========") or die(mysql_error()); mysql_select_db("xxxx") or die(mysql_error()); mysql_query("INSERT INTO `activity` VALUES ('ID','$title', '$cost','$activity', '$aday', '$ayear', '$special', '$seats')"); Print "Your information has been successfully added to the database!" ?> Click <a href="member-profile.php">HERE</a> to return to the main menu <?php ?> the difference between memory usage and bandwidth usage? I did a test with 500 rows in table, got 2.36mb memory usage, and then once without 500 rows in table, i got 2.34 (IN MBS) memory usage, can that translate into bandwidth usage? somone told me that bandwidth usage != memory usage, how so? it does effect it some doesn't it ? hi, i have made a website where people resgister their details of them and products. they have to enter the following details in form Name of company name of the product company address email id password mobile number contact and brief details about their company
user can then login with email id and pwd. now after login ..user will get a page where he can upload the photos of products images and their price, so now my question is that when he finishes uploading (|by clicking on upload button) the product images and price text box ..then on final uploaded webspage it should show all other things which he registerd before (company name , mobile number etc) along with images and price...hence the main question that user does not need to enter mobile and address while uploading images and filling proce ..but on the final page it should show mobile and address along with price and images..as user is not going to enter mobile and address again and again as he will have multiple products to upload.
1 Total number of likes work, but I'm guessing it can be done differently, any input would be appreciated. /controllers/indexController.php $posts = Post::find('all', [ 'limit' => 4, 'include' => ['likes'] ]); foreach ($posts as $post) { $post->assign_attribute('likeCount', count($post->likes)); } } /models/Post.php class Post extends ActiveRecord\Model { static $has_many = [ ['comments', 'class_name' => 'PostComments'], ['likes', 'class_name' => 'UserLikePosts'] ]; } /models/UserLikePosts.php class UserLikePosts extends ActiveRecord\Model { static $belongs_to = [ ['user'], ['post'] ]; }2 The big question is, how can I get a true/false for "if current user has liked post"? I was thinking something like this, but using vars won't work here, and I would have to use a ternary or a function call to do it like this as the session var might not be set (guest). class Post extends ActiveRecord\Model { static $has_many = [ ['comments'], ['likes', 'class_name' => 'UserLikePosts'], ['user_likes', 'class_name' => 'UserLikePosts', 'conditions' => ['user_id = ?', [$_SESSION['user']['id']]] ]; } Edited by JimL, 21 June 2014 - 03:36 PM. Hi everyone... I would like to implement a questionnaire/survey system that has only two Answers (Yes /No). Basically, this questionnaire system will be widely used on Mobile Phones. It will be looking something like this below: http://awardwinningfjords.com/2009/06/16/iphone-style-checkboxes.html Lets say a user selects a response as No (Using the above slider button for a question). That response should be recorded in the database with User Details + Time Stamp. Also, I would like to generate a report for each question (Responses of Multiple Users) and a report at a User Level for the entire questionnaire/survey (s). Can some one guide me the fastest & easiest way to achieve this? I'm a new learner of PHP. Regards Sandeep Yesterday, I created a topic about how I could update records and I managed to achieve that successfully. Now I have another dilemma. When I have a specific record I want to update, I want to change a category ID of an product (e.g. change it from 1 to 2) but how do I go about doing this? Here is my code thus far: Code: [Select] <?php require_once ('./includes/config.inc.php'); require_once (MYSQL); $id=$_GET['prodID']; $results = mysqli_query($dbc, "SELECT * FROM product WHERE prodID=".$_GET['prodID'].""); $row = mysqli_fetch_assoc($results); ?> <form action="" method='POST'> Product ID: <input type="text" value="<?php echo $row['prodID'];?>" name="prodID" /> <br /> Product: <input type="text" value="<?php echo $row['product'] ;?>" name="product" /> <br /> Product Description: <input type="text" value="<?php echo $row['prod_descr'] ;?>" name="prod_descr" /> <br /> Category: <select name="category"> <option value="<?php echo $row['catID'];?>"></option> </select> Price: <input type="text" value="<?php echo $row['price'] ;?>" name="price" /> <br /> In Stock: <input type="text" value="<?php echo $row['stock'] ;?>" name="stock" /> <br /> <br /><input type="submit" value="save" name="save"> </form> <?php if(isset($_POST['save'])) { $id = $_POST['prodID']; $product = $_POST['product']; $descr = $_POST['prod_descr']; $price = $_POST['price']; $stock = $_POST['stock']; // Update data $update = mysqli_query($dbc, "UPDATE product SET product='$product', prod_descr='$descr', price='$price', stock='$stock' WHERE prodID=".$_GET['prodID'].""); header( 'Location: update_save.php' ) ; } ?> Hey guys I'm not amazing at PHP, but know just enough to be dangerous. Basically I'm trying to get these records from my database to display in rows of 4. For some reason every time, I'm missing a record (the first record returned in my query). It's probably something simple is my code. Would be grateful if anyone could lend a suggestion. Code: [Select] <?php $a=0; $b=3; while ($ArrayData = mysql_fetch_array($QueryData)) { //if a=0, start new row if ($a==0) { echo '<tr>'; } //create cell //if thumbnail exists, use it, otherwise throw in the unavailable image if ($ArrayData["PhotoThumb"]!="") { $ImageToUse = $ArrayData["PhotoThumb"]; } else { $ImageToUse = "image_unavailable_thumb.jpg"; } echo ' <td width="33%" align="center" valign="top"><p><a href="item.php?ItemID='.$ArrayData["ItemID"].'"><img src="images/'.$ImageToUse.'" border="0" /></a></p> <p><a href="item.php?ItemID='.$ArrayData["ItemID"].'" class="cart_body_text">'.$ArrayData["ItemName"].'</a><br /> <span class="style1"> <strong>$'.sprintf("%01.2f", $ArrayData["UnitPrice"]).'</strong></span><br /> </p> </td>'; //increment by 1 $a++; //if a = 3 then close the row using </tr>, ready to start a new one if ($a==$b) { echo ' </tr>'; //reset counter, ready to start new row $a=0; } } if ($a > 0 ) { echo '</tr>'; } ?> Thanks guys! Hello all. I am using an API from jambase.com to display events on a php page. Everything works great, the xml file is read and the data is displayed on the page as it should. My only problem is that when the data is displayed there is always a blank area where the first record of data should go. Any ideas how to get rid of this? http://www.wddclients.com/mag33/events_search.php (artist search field not enabled yet) Hopefully this is something pretty minor but if anyone wants to see specific code I can supply that. Thanks so much for all help! Greetings! I have a website www.lanceronlinejobs.com/our_franchises.php I have a franchise images. I want to display each franchise record from database whenever a user click on franchise link. Here is my code. ourfranchises.php code: Code: [Select] <?php include('fconnection.php'); $sql = mysql_query("SELECT * FROM tbl_franchise ORDER BY id DESC") or die(mysql_error()); $row3 = mysql_fetch_array($sql); ?> <a href="franchiseDetails.php?city=<?php echo $row3['city'];?>"><img src="images/lbatkhela.jpg" width="150" height="150" alt="Batkhela" /></a>---------------------------------------------------------------------- franchiseDetails.php code: Code: [Select] <?php $id = $_GET['id']; $query = "SELECT * FROM tbl_franchise WHERE id = '$id' ORDER BY id DESC LIMIT 1"; $result = mysql_query($query); if (!$result) { echo "NO RECORD FOUND"; } else { while($row3 = mysql_fetch_array($result)): ?> Manager Name: <?php echo $row3['manager_name'];?> Please help me. Any help would be appreciated. Thanks. Hello, First time posting here, my MYSQL version is 5.1.52 and I have a created a search function to find a user record and if the name is typed correctly the name and details are displayed on the search page, but if the name is typed incorrectly nothing is appearing. Basically I would like to be able to say if no record found and redirect back to the previous page. Code: Code: [Select] <?php add = $_POST['add']; // Database details $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name="Rewards"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot SELECT DB"); //Add query $sql = mysql_query("UPDATE Rewards SET Rewards = (Rewards + 10) WHERE Name '%$add%'"); // Database details $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name="UserList"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot SELECT DB"); //Update Total Points query $sql = mysql_query("UPDATE UserList SET TotalPoints = (TotalPoints + 10) WHERE Name '%$add%'"); // Database details $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name="UserList"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot SELECT DB"); //Search Query $sql = mysql_query("SELECT * FROM UserList WHERE Name '%$add%'"); while ($row = mysql_fetch_array($sql)){ echo '<br/><img src="images/line1.jpg" alt="" width="200" height="2" />'; echo '<br/> Username: '.$row['Username']; echo '<br/>'; echo '<br/><img src="images/line2.jpg" alt="" width="200" height="2" />'; echo '<br/> Name: '.$row['Name']; echo '<br/> Year Group: '.$row['YearGroup']; echo '<br/> Form Class: '.$row['FormClass']; echo '<br/>'; echo '<br/><img src="images/line3.jpg" alt="" width="200" height="2" />'; } // Database details $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name="Rewards"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot SELECT DB"); $sql = mysql_query("SELECT * FROM Rewards WHERE Name '%$add%'"); while ($row = mysql_fetch_array($sql)){ echo '<br/> Rewards: '.$row['Rewards']; } // Database details $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name="Sanctions"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot SELECT DB"); $sql = mysql_query("SELECT * FROM Sanctions WHERE Name '%$add%'"); while ($row = mysql_fetch_array($sql)){ echo '<br/> Sanctions: '.$row['Sanctions']; } // Database details $host=""; // Host name $username=""; // Mysql username $password=""; // Mysql password $db_name=""; // Database name $tbl_name="UserList"; // Table name // Connect to server and select databse. mysql_connect("$host", "$username", "$password")or die("cannot connect"); mysql_select_db("$db_name")or die("cannot SELECT DB"); $sql = mysql_query("SELECT * FROM UserList WHERE Name '%$add%'"); while ($row = mysql_fetch_array($sql)){ echo '<br/> Total Points: '.$row['TotalPoints']; echo '<br/>'; echo '<br/><img src="images/line4.jpg" alt="" width="200" height="2" />'; } Any help would be greatly appreciated. Many Thanks P Quinn MOD EDIT: [code] . . . [/code] tags added. I am looking to accomplish the following but have been hitting a brick wall: * User enters a single keyword into a text field, and conducts a search keyword search. * The results are pulled from the campusbooks.com API(API docs attached) * result are then output in <div> class and includes all the book details and its corresponding url./img etc I'm trying to simplify this process but I continue to receive syntax errors. A step by step practical explanation would do me justice! Hi guys, I have a very simple add.php to add data to a mySQL db. I have a menu/list drop down as one of my fields on my form and this shows an array of results from another table (ranks of the RAF) within my db. When I click the save button I have it process a INSERT INTO command but all i get inputted into my staff table is the first word... eg if I chose "Pilot Officer" from the list menu and then click save all that would appear in my db is "Pilot". Any clues? I will paste the php below... Code: [Select] <?php include('config.php'); ?> <form action='' method='POST' enctype='multipart/form-data'> <p><b>Rank:</b><br /> <select name="rank" id="rank"> <option selected>Please Select</option> <?php $query = "SELECT * FROM ranks ORDER BY rank ASC"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { echo "<option value=". $row["rank"] .">". $row["rank"] ."</option>"; } ?> </select> <p><b>Forename:</b><br /> <input name="forename" type="text" id="forename" value="" size="40"> <p><b>Surname:</b><br /><input name='surname' type='text' id="surname" value='' size="40" /> <p><b>Category:</b><br /> <select name="category" id="category"> <option selected>Please Select</option> <?php $query = "SELECT * FROM categories"; $result = mysql_query($query); while($row = mysql_fetch_array($result)) { echo "<option value=". $row["category"] .">". $row["category"] ."</option>"; } ?> </select> <p><b>Email:</b><br /><input name='email' type='text' id="email" value='' size="50" /> <p><b>Mobile:</b><br /> <input name='mobile' type='text' id="mobile" value='' size="40" /> </p> <input type='submit' value='Save' /> <input type='hidden' value='1' name='submitted' /> </form> <?php if (isset($_POST['submitted'])) { $rank = mysql_real_escape_string($_POST['rank']); $forename = mysql_real_escape_string($_POST['forename']); $surname = mysql_real_escape_string($_POST['surname']); $category = mysql_real_escape_string($_POST['category']); $email = mysql_real_escape_string($_POST['email']); $mobile = mysql_real_escape_string($_POST['mobile']); $sql = "INSERT INTO `staff` (`rank` , `forename` , `surname` , `category` , `email` , `mobile` ) VALUES ( '$rank' , '$forename' , '$surname' , '$category' , '$email' , '$mobile')"; mysql_query($sql) or die(mysql_error()); echo (mysql_affected_rows()) ? "Staff Added":"Nothing Added"; } ?> i am having the database consists of morethan one lac rows. we have a search option in our website to search the database for required information. the present code is like this: form.php `<input type="radio" name="tag" value="city" /> CITY <br/>` `<input type="radio" name="tag" value="name" /> NAME OF CUSTOMER <br/>` `<input type="radio" name="tag" value="amount" /> CHEQUE AMOUNT <br/>` `<input type="radio" name="tag" value="somethingelse" /> some thing else ` `Enter the part of any of the above Here :<input type="text" name="value" />` search.php `$tag = $_POST['tag'];` `$value = $_POST['value'];` `$query = "SELECT * FROM database WHERE $tag LIKE '%$value%' "` note: we always input the part field only. with this some times the output comes in thousands of rows. with which we are facing problems. we want to search the two or more fields for getting more precise results. hence i tried this form: `<h3 align="center">ENTER ALL OR DESIRED ITEMS YOU WANT TO SEARCH</h3>` `<div width="80%" align="center">` `<input type="text" name="city" /> CITY <br/>` `<input type="text" name="name" /> NAME OF THE CUSTOMER <br/>` `<input type="text" name="amount" /> AMOUNT <br/>` `<input type="text" name="somethingelse" /> SOME OTHER SEARCH FIELD </div> ` `$query = "SELECT * FROM database WHERE city LIKE %$city%' || name LIKE %$name%' || amount LIKE %$amount%' || somethingelse LIKE %$somethingelse%';` it worked in the mysql console, and even in our website when we give all the variables. but it displaying the entire database when we dont give even one field in the search box. i tried to assign NULL to the variable which was not given. it is also not worked. it works if any variable is replaced with NULL in the query. i don't know how to do that. i tried a lot of queries after searching in lot of code provider websites. but none of them gave the desired results.hence i request you to provide me a sql query code for search the database using all of the above fields or any two or even with one. the code must work independent of number of fields we entered. |