PHP - Duplicate Database Entries
I am quite new so I am sure this is an easy fix for some of the experts around here.
I am using the canned script below to add urls to the database as text. The problem is if you update one of the form text boxes it loads all the urls into the database again resulting in a lot of duplicates. My question is, How do I get the form to only post the new changes and not re-post the existing urls? <?php session_start(); if(isset($_SESSION['userSession']) && !empty($_SESSION['userSession'])) { include_once("dbc.php"); if($_POST) { $c = 0; $errMssg = ""; for($i=0;$i<count($_POST['url']);$i++) { if($_POST['url'][$i]=="") { $c++; } } if($c==5) { $errMssg = "Submission error . Please fill at least 1 url."; } else { for($j=0;$j<count($_POST['url']);$j++) { if(!empty($_POST['url'][$j])) { $sql = mysql_query("INSERT INTO images (id ,url ,user_id)VALUES (NULL , '".$_POST['url'][$j]."',".$_SESSION['userId'].")"); } } } } $sqlresult = mysql_query("SELECT * FROM images WHERE user_id =".$_SESSION['userId']); $count = 0; while($data = mysql_fetch_array($sqlresult)) { $image[$count] = $data['url']; $count++; } ?> Similar TutorialsI've run into a little bit of a logistical nightmare on some registration pages I've taken over work on. On these pages, parents register their kids for classes. The pages have been coded as such: page one: the user enters name and personal info, and selects one or two classes to register for, on submit, they go to page two. page two: their info is entered into the mysql database's registration table on a unique id The user verifies the total, enters a discount and submits page three: credit card info is added to registration table, and sent to authorize.net. page four: payment processed, and they enter the data for their kids into the attendees table page five: confirmation and done. My issue is that, at first I saw people entering page one data, going to page two, then for some reason, hitting the back button. They could then enter the data again. I'd have two entries in the registration table for the same person. I was going to put some sort of unique key on the name and an email, but then I saw scenario two... Another person enters data and registers one kid.. then for whatever personal reason goes back and registers a second kid in a completely separate transaction. So I can't put that key on there, but is there a way to prevent them from going back and reentering twice. I don't want to have to blow up the code to do it at the end of everything. and that would take implementing sessions, wouldn't it? I'm not so versed at that. Any thoughts? Hi Guys, This is a new post based on my last post for the same but I've revamped the code a little from the last post since I couldn't get it to work even with the suggestions, so my new code is below... Basically I have an updates table (updates_all) and a subscriptions table (subscriptions) and in the updates table items are entered for multiple users with querydate which increases based on the unix timestamp of the update. The Subscriptions table holds the data for users who are subscribed to other user's profiles. My issue is to show a logged in user his subscriptions and when a user he is subscribed to has a new update that user shows up on top of the list of his users. With the code below, i've been able to list the contents of the updates table, filter out the profiles which he is not subscribed to, and order the results by the most recent querydate. My question now is how do I run the while loop so it filters out all but one result per/member name?? Results output below the code... Code: [Select] $sql_findsubs = "SELECT * FROM updates_all ORDER BY auto_id DESC"; $rs_findsubs = mysql_query($sql_findsubs); $subscripPID = array(); $sql="SELECT * FROM subscriptions WHERE memberid='$id' "; $rs=mysql_query($sql); while($row=mysql_fetch_array($rs)) { $subscripPID[] =$row['profileid']; } while($rowfs = mysql_fetch_assoc($rs_findsubs)) { $id = $rowfs['id']; if (in_array($id, $subscripPID)) { echo $rowfs['auto_id'].' - '.$rowfs['querydate'].'.......'.$rowfs['member']; echo '<br>'; } } RESULTS: So if John is subscribed to Bob, Mary, Jim and Andy, I want to only show the four rows below, not all the other entries because those have a smaller querydate for those members. AutoID - Querydate - Name 130 - 1109092040.......Bob <-------- I want to show this one only for Bob 129 - 1109092039.......Bob 128 - 1109091935.......Bob 98 - 1106162306.......Mary <-------I want to show this one only for Mary 97 - 1106162254.......Mary 96 - 1106162215.......Jim <-------I want to show this one only for Jim 90 - 1105062043.......Bob 89 - 1105052200.......Andy <------I want to show this one only for Andy 88 - 1105052154.......Bob 87 - 1105052154.......Bob 86 - 1105052038.......Bob 80 - 1105052034.......Andy 79 - 1105052032.......Andy 73 - 1105052023.......Bob 72 - 1105052018.......Andy 60 - 1103192354.......Bob 4 - 1103172045.......Bob Any help is greatly appreciated... Thanks. I dont even know where to begin doing this. I am supposed to remove duplicate entries in this 2 dimensional array but I just can't find any answers anywhere. Code: [Select] <?php /* In the following two dimensional array (an array of arrays) you will notice that there are several duplicate entries (David and Patricia). 1) Write a basic function which will go through $input and remove the duplicate entries. A "duplicate" is an entry which has the same FirstName and LastName as another entry. Ignore the other fields. Call your function "dedupe1". It should return a two-dimensional array without these duplicates 2) Using your dedupe1 function, write one called dedupe2 which will detect empty DOB's and DOB's of '00/00/0000'. When an empty or zeroed DOB is detected, your code should use the entry with a complete DOB (if available). Like dedupe1 your code should return a two-dimensional array without duplicates. If you use the provided $input function, all of the returned entries should have a complete DOB listed. */ $input = array( array( 'FirstName' => 'Daniel', 'LastName' => 'Anderson', 'Phone' => '614-123-4568', 'Address' => '123 Main St', 'SSN' => '001-01-0001', 'DOB' => '01/11/1922' ), array( 'FirstName' => 'Aaron', 'LastName' => 'Williams', 'Phone' => '937-321-3993', 'Address' => '933 N Park St', 'SSN' => '992-23-1192', 'DOB' => '04/21/1965' ), array( 'FirstName' => 'David', 'LastName' => 'Taylor', 'Phone' => '223-293-9921', 'Address' => '123 Main St', 'SSN' => '003-19-2992', 'DOB' => '12/14/1995' ), array( 'FirstName' => 'Patricia', 'LastName' => 'Anderson', 'Phone' => '614-123-4568', 'Address' => '123 Main St', 'SSN' => '123-32-3123', 'DOB' => '00/00/0000' ), array( 'FirstName' => 'David', 'LastName' => 'Taylor', 'Phone' => '223-293-9921', 'Address' => '123 Main St', 'SSN' => '003-19-2992', 'DOB' => '' ), array( 'FirstName' => 'Patricia', 'LastName' => 'Anderson', 'Phone' => '614-123-4568', 'Address' => '123 Main St', 'SSN' => '123-32-3123', 'DOB' => '02/22/1957' ), ); // Get results from dedupe1 and print them $result1 = dedupe1($input); var_dump($result1); // Get results from dedupe2 and print them $result2 = dedupe2($input); var_dump($result2); print_r($input);//just to see the information in the web page function dedupe1($in_array) { // your code here } function dedupe2($in_array) { // your code here } ?> Hello, i am inserting some form data into my mysql db, i happen to get some duplicates so i want to check first if the entry exists already before i insert. my current code: Code: [Select] <?php if(isset($_POST['submit'])) { ?> <?php if (strlen($_POST['code']) == 19 && substr($_POST['code'],0,7) == '5541258') { mysql_query("INSERT INTO table(code,secret,ip,date) VALUES('$_POST[code]','$_POST[secret]','$_SERVER[REMOTE_ADDR]',CURDATE())"); Print "<font color='green'>The code will be checked now</font>"; } else { Print "<font color='red'>The code is invalid</font>"; } ?><?php } ?> I would like to use the value 'code' to check if the entry exists, that one is unique for each entry. How would i do that ? Thanks ! The only 2 tables relevant to what I want to do are "User" and "Scores." Basically this database holds high scores for a project I've been working on. I only want to display 10 scores, all from different users. No 2 or more scores from the same user. This is my db structure within phpmyadmin: Quote database -> table -> X / User / Score / X / X / X / X / X / X / X / X If possible I'd like to run a query where it checks for duplicate entries by the same user and only show the highest score. The current query I'm running is below: $result = mysql_query("SELECT * FROM table ORDER BY Score DESC LIMIT 0, 10"); Is this possible? I can only seem to find information regarding the INSERT IGNORE clause and that obviously won't help me as the users and scores are already in the database. Thanks. Hi all,
Its been a long time since last help request from real professional from here but I'm again in trouble with a much more spectacular plan I'm working on. For those who are interested in the plan then here it is: My Idea was to make a new build starting from scratch and make it as dynamical as possible. So my goal is not to make almost anything fixed in the code. I have made a decision to make a one supper large table for multiple different entries so no more joining and no more views for me.! In this help request I'm having trouble with Posting values to a page processing page lets call it record_changer.php The sole purpose of this file is to get form posts and decide what to do. Either update, delete, or insert. record_changer.php <?php include '../../config/config.inc.php'; if(is_ajax()){ # Checks if action value exists if(isset($_POST["action"]) && !empty($_POST["action"])){ $action = $_POST["action"]; # Switch case for value of action switch($action){ case "insert": datatable_insert_function(); break; case "update": datatable_update_function(); break; case "delete": datatable_delete_function(); break; } } } # Function to check if the request is an AJAX request function is_ajax(){ return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'; } function datatable_insert_function(){ } function datatable_update_function(){ } function datatable_delete_function(){ } ?>The problem. The problem is that the $insert places two entries to the DB. I cant seem to understand why.? # Test _POST values $_POST['UserID'] = '2'; $_POST['WorkID'] = '22'; $_POST['Status'] = '1'; $_POST['Code'] = '1'; $_POST['Title'] = '1'; $columns = array(); foreach(array_keys($_POST) as $name){ # Exclude Action and ID if($name == 'Action' || $name == 'ID' || $name == 'submit' ){ continue; } $columns[] = $name; } print_r($columns); echo "<br>"; $data = array_fill_keys($columns, 'NULL'); print_r($data); foreach($data as $key => $value){ $data[$key] = empty($_POST[$key]) ? 'NULL' : "'".mysql_real_escape_string($_POST[$key])."'"; } echo "<br>"; print_r($data); $insert = mysql_query('INSERT INTO datatable (ID, '.implode(', ',$columns).')VALUES (null, '.implode(',',$data).')') or die(mysql_error());No errors no nothing. Just two entries of correct data. PS. Sorry for a lot of prints in the code it is work and idea in the progress. The posts at the moment are fixed in the code so it is easier to refresh and debug. Please help if you spot the problem. Im really out of ideas. Some fresh eyes might make a difference. And Please for those who want to say it is a bad idea and why and why and so on.. Move a long.!!! Im not interested in whinging i have a great use for this and just having trouble with the two entries. Thanks. Edited by ztimer, 14 January 2015 - 03:27 PM. MySQL returns an error in the form of a number, a state, and a message. Without parsing the message you will not be able to determine what column is duplicated.While parsing the error code, I have also notice that, if you have multiple unique fields as duplicates, only the first duplicate encountered will be returned in the message. This is not very helpful to the end user.
Is there any way to parse the returned error code to reflect all duplicate fields, please see sample code below?
$error=array(); $sql = 'INSERT INTO staff(username, email, phone) VALUES (?, ?, ?)'; $stmt = $conn->stmt_init(); $stmt = $conn->prepare($sql); // bind parameters and insert the details into the database $stmt->bind_param('sss', $username, $email, $phone); $stmt->execute(); if ($stmt->errno == 1062) { $errors[] = "One of the fields is already in use."; } Code: [Select] $query = mysql_query("SELECT a.*, b.* FROM friendlist a INNER JOIN friendlist b ON (a.friendemail=b.friendemail) INNER JOIN users c ON (b.friendemail = c.EmailAddress) WHERE a.email = 'asdf@gmail.com' AND c.Username LIKE '%carol%' GROUP BY a.id ORDER BY count(*) DESC"); Code: [Select] while ($showfriends = mysql_fetch_array($query)) { echo $showfriends['Username']; } and I would get nothing. It produces the correct number of <div> so i know it's getting through, but it's having trouble displaying the entries? Hello... I have a .txt database with ~100 records. I only want to show the 15 records that are at the top (referring to reading order of the file). Here is my php code to display the records. http://www.flcbranson.org/mobile.php?content=mobile-freedownloads.php if you want to see the results of the code, below. Code: [Select] <?php $index_file = 'services/series/Index-Date.txt'; $fd = fopen($index_file, 'r'); if ($fd) { while (!feof ($fd)) { $seriestitle = trim(fgets($fd, 1024)); // Series Title if(feof ($fd)) break; $seriessubtitle = trim(fgets($fd, 1024)); // Series subtitle $seriesinfo = trim(fgets($fd, 1024)); // Series Info (Church name) $serieslocation = trim(fgets($fd, 1024)); // City, State $seriesindex = trim(fgets($fd, 1024)); // Series index file $seriesstatus = trim(fgets($fd, 1024)); //Online Only? $divider = trim(fgets($fd, 1024)); // Divider $seriestitle2 = $seriestitle; $seriestitle3 = str_replace("'", "%27", $seriestitle); // Kind of makes the alt= below work "God's Will" ends up being "God%27s Will" but without is "God" if(strstr($seriestitle,"<")) { $seriestitle2 = strip_tags($seriestitle); } $seriestitle2 = urlencode($seriestitle2); if(file_exists("images/ProductCovers/".substr($seriesindex,0,-4).".jpg")) { echo "<img src='images/ProductCovers/".substr($seriesindex,0,-4).".jpg' width='115' height='150' border='0' alt='".substr($seriestitle3,7)."'><br />"; } } fclose ($fd); } ?> I'm assuming that "for" would do the trick, but when I tried I got 10 copies of every record. Hehehe... I'm guessing that it's a quick fix. Thanks... JJ I have an issue with some code I have. All the code works correctly apart from when submit is clicked not only does it update a the current club but it creates a blank entry in the database! I cant see whats wrong. Here is the code......... //gets $validation = $_GET['new_club']; //Querys $qGetClub = "SELECT * FROM clubs WHERE validationID = '$validation'"; $rGetClub = mysql_query($qGetClub); $Club = mysql_fetch_array($rGetClub); //Query for category by name $qGetCat = "SELECT * FROM club_category WHERE catID = ".$Club['cat'].""; $rGetCat = mysql_query($qGetCat); $CatName = mysql_fetch_array($rGetCat); //query for related sub categorys. $qGetSub = "SELECT * FROM sub_categorys WHERE catID =".$Club['cat'].""; $rSubCat = mysql_query($qGetSub); // query for groups created $Groupq = mysql_query("SELECT * FROM groups WHERE memberID = '".$User['memberID']."'"); //end of querys if(isset($_POST['insert_clubbtn1'])){ //Process data for validation $subcat = trim($_POST['subcat']); $NewSubCat = trim($_POST['NewSubCat']); //Prepare data for db insertion $subcat = mysql_real_escape_string($subcat); //find the new category //insert $result = mysql_query("UPDATE clubs SET `sub_category` = '$subcat' WHERE validationID ='$validation'") or die(mysql_error()); if ($result!=="") { $otherg = trim($_POST['other_groups']); $newg = trim($_POST['new_group']); $newg = mysql_real_escape_string($newg); //if an item other than none from the list is selected then update the club with an ID relating to the group it belongs to if ($otherg !=='None') { $groupsq = mysql_query("UPDATE `clubs` SET groupID ='$otherg' WHERE validationID ='$validation'") or die (mysql_error()); } // If none is selected then $newg must have a value so create a new group in the groups table and then on the next page I will add the group in the club table else { $groupsq = mysql_query("INSERT INTO `groups` (`memberID`, `group`, `clubID`) VALUES ('".$User['memberID']."', '$newg', '".$Club['clubID']."')")or die (mysql_error()); } } if ($NewSubCat !="") { mail("mail","New Sub Category Request","Dear Ring Master, \n\nThe club in the name of $name with a validation code of $validationID would like a new sub category called $new_cat\n\n \nTeam Arena\n\n\n\n"); } $url = "/members/create/create_clubp3.php?new_club=$validation"; header("Location: $url"); } Hello, For starters I'm not sure if what I want to do is possible, but if it is I would like your input. I have a script that will show a number of fields to fill out in a second form based on the number the user puts into the first from. the problem is that only the last one saves into the database and not all of them. Code: [Select] <form auction="index.php" method="post"> System Name: <input type="text" name="systemname"> Number of E-sites: <input type="text" name="events"> Number of Sigs: <input type="text" name="sigs"><br> <input type="reset" name="reset" value="Reset"> <input type="submit" name="start" value="Start"> </form> <form auction="index.php" method="post"> <?php $events = $_POST['events']; $system = $POST['systemname']; if (isset($_POST['start'])) { $num = $_POST['sigs']; $i = 0; While ($i < $num) { echo "Sig ID: <input type=text name=sigid>"; echo "Type: <input type=text name=type>"; echo "Name: <input type=text name=name>"; echo "Notes: <input type=text name=notes>"; echo "<br>"; $i++; } } ?> <input type="submit" name="enter" value="Enter"> </form> <?php $sigid = $_POST['sigid']; $type = $_POST['type']; $name = $_POST['name']; $notes = $_POST['notes']; mysql_connect('xt', 'x', 'x'); mysql_select_db('wormhole'); if (isset($_POST['enter'])) { $query = "INSERT INTO sites VALUES ('$system','$events','$sigid','$type','$name','$notes')"; mysql_query($query); } ?> How do I get it so all the data saves, lets say that $num = 5, I want all 5 to save not just the last one. Is there any other way of getting PHP form data into C# any other way besides calling www.downloadHandler.text I am having issues bringing all the entries into C# and breaking them all up. I can do one row fine but multiple rows isn't working. I keep getting an out range error. This is my PHP echo echo $row['userName']. '|' .$row['level']. '|' .$row['points']. '|' .$row['killRate']. '/'; And this is my C# code string nothing = "Not Placed"; string Data_string = www.downloadHandler.text; string[] DataArray; DataArray = Data_string.Split('/'); int numberOfEntries = DataArray.Length; Debug.Log(numberOfEntries); if (DataArray[0] == null || numberOfEntries == 1) { DataArray[0] = nothing; Debug.Log("Data Array [0] isn't there"); High_Points_1.text = DataArray[0]; } else { High_Points_1.text = DataArray[0]; //Debug.Log(DataArray.Length); } if (DataArray[1] == null || numberOfEntries == 2) { DataArray[1] = nothing; Debug.Log("Data Array [1] isn't there"); High_Points_2.text = DataArray[1]; } else { High_Points_2.text = DataArray[1]; //Debug.Log(DataArray.Length); } if (DataArray[2] == null || numberOfEntries == 3) { DataArray[2] = nothing; Debug.Log("Data Array [2] isn't there"); High_Points_3.text = DataArray[2]; } else { High_Points_3.text = DataArray[2]; } if (DataArray[3] == null || numberOfEntries == 4) { DataArray[3] = nothing; Debug.Log("Data Array [3] isn't there"); High_Points_4.text = DataArray[3]; } else { High_Points_4.text = DataArray[3]; } if (DataArray[4] == null || numberOfEntries == 5) { DataArray[4] = nothing; Debug.Log("Data Array [4] isn't there"); High_Points_5.text = DataArray[4]; } else { High_Points_5.text = DataArray[4]; } I have two entries in the database. But when I debugged the number int he array I get 3 strings. I want to show the top five entries in the database. Hi, I want to be able to generate visitor statistics for a blog I'm creating. I'm going to be collecting numerous pieces of data when a post is viewed, including a time stamp of the visit. I need to be able to select timestamps that were within the current day, the previous day, the day before that ect.. So that I can generate the statistics. Show it for the current week (current day and 6 previous days). So it would be the entries where the timestamp was made on the days: 11/1, 10/1, 9/1, 8/1, 7/1, 6/1, 5/1. For example. Not quite sure how I could do this. Thanks. For some reason my for loop only seems to be storing some data in my fields, most of the time the data is not true but simply duplicating one of the entries. So instead of having a string of 1,2,3,4 for instance it would store all of them as 4. The entires are selected using fields in a multiple select box, in theory of someone choses 10 unique entries from the "Systems" category all 10 should be made into rows in the MySQL table. Any idea why this is happening? The form, if ($type == "games") { echo "<tr><td>".$name."</td><td><select name='".$name."_".$i."'[] multiple='multiple'><option value='' selected>--------</option>"; $sqla = mysql_query("SELECT * FROM ".$pre."games ORDER BY `name` ASC") or die(mysql_error()); while($row2a = mysql_fetch_array($sqla)) { $system = mysql_fetch_array(mysql_query("SELECT * FROM ".$pre."systems WHERE id = '".$row2a[system]."'")); echo "<option value='".$row2a[id]."'>".$row2a[name]." - ".$system[name]."</option>"; } echo "</select></td></tr>"; } if ($type == "system") { echo "<tr><td>".$name."</td><td><select name='".$name."_".$i."'[] multiple='multiple'><option value='' selected>--------</option>"; $sqlb = mysql_query("SELECT * FROM ".$pre."systems ORDER BY `name` ASC") or die(mysql_error()); while($row2b = mysql_fetch_array($sqlb)) { echo "<option value='".$row2b[id]."'>".$row2b[name]."</option>"; } echo "</select></td></tr>"; } The PHP code, while($row = mysql_fetch_array($query)) { $name = "$row[name]"; for ($i = 0; $i < count($_POST["systems_$i"]); $i++) { mysql_query("INSERT INTO ".$pre."fielddata VALUES (null, 'systems', '".$_POST["systems_$i"]."', '".$fetch[0]."', 'content')"); } for ($i = 0; $i < count($_POST["games_$i"]); $i++) { mysql_query("INSERT INTO ".$pre."fielddata VALUES (null, 'games', '".$_POST["games_$i"]."', '".$fetch[0]."', 'content')"); } Hello, I am using the following code to display images managed by a MySQL database. Basically another program manages a bunch of images, but this script displays certain ones (ones with INCLUDE = 1 in the database) on my main page. My question is, is there an easy way to limit the number of images it displays, say to 5? I'm not too concerned which images actually display (ascending or descending)... or better yet, random! Most importantly, I only want five to display. Each image will be linked to the full page, which displays all the images. Any ideas? Thanks! Code: [Select] <?php $username="XXXXXXX"; $password="XXXXXXX"; $database="XXXXXXX"; mysql_connect(localhost,$username,$password); @mysql_select_db($database) or die( "Unable to select database"); $query="SELECT * FROM ft_form_12 WHERE col_24='1'"; // $query="SELECT * FROM ft_form_12"; // SELECT * FROM ft_form_12 WHERE col_24='1' $result=mysql_query($query); $num=mysql_numrows($result); mysql_close(); ?> <?php $i=0; while ($i < $num) { $f20=mysql_result($result,$i,"col_23"); //Photo file name $f21=mysql_result($result,$i,"col_24"); //INCLUDE ?> <a href="http://www.domain.com/display_whole_page.shtml"><img src="http://www.domain.com/the_file/pictures/<?php echo $f20; ?>" height="50" border="0"></a> <?php $i++; } ?> I coded the following but some parts are not working (the "curveball" mentioned at the end). How would YOU do this? I have a page (A) displaying a form with a textarea field using a WYSIWYG interface. The user will enter a list of unordered items and upon submit the string will look something like this: This is my list of food items: <ul> <li> Lettuce </li> <li> Tomatoes </li> <li> Eggs </li> <ul> Upon submit, I need to give each list item an unique id and store this id along with the text next to it in a separate table: List_item_id List_item_text List_item_state food_1 Lettuce food_2 Tomatoes food_3 Eggs The user will then land in another page with a form displaying the list. The text is now in the page itself and not in a textarea. Instead of the bullets a dropdown list appears, and the user can select "buy" or "sell" for each list item. This page (B) looks something like this: <form> This is my list of food items: <br><select name="food_1"> <option value="buy">Buy</option> <option value="sell">Sell</option> </select> Lettuce <br><select name="food_2"> <option value="buy">Buy</option> <option value="sell">Sell</option> </select> Tomatoes <br><select name="food_2"> <option value="buy">Buy</option> <option value="sell">Sell</option> </select> Eggs <input type=submit value="submit"> </form> When the user hits "submit" the table with the list items will be updated with the values selected in the dropdown list: List_item_id List_item_text List_item_state food_1 Lettuce Buy food_2 Tomatoes Buy food_3 Eggs Sell The next time the user goes to Page B the list will remember the states. Here's the curveball: At any point the user may click on "EDIT LIST" on Page B so they may add more items (at the begining, middle or end of the string). On edit mode the list items should appear as bullets again inside the WYSIWYG interface. Keep in mind that some of the text in the string may not be a list item (ie, "this is my list of food...") Hello. Many thanks for your help. I am writing a PHP/MySQL dating-site and have hit a programming impass. I have a database full of members and a search form consisting of checkboxes. So to search, a member ticks say...gender: female; age: 21,22,23,24,25,26; height: 5'4",5'5",5'6",5'7"; county: cornwall,devon,somerset How can a run a check on the database selecting all entries that fall into the selected criteria. For example a 23 year old female of 5'5" living in Cornwall and a 26 year old female of 5'4" living in Somerset? The key index of my database is 'id' and the fields a age,height,county The names of the form checkboxes a Gender: male, female; Age: 21,22,23,24 etc; Height: 5_4,5_5,5_6 etc; county: cornwall,devon etc Im trying to create a website where users login, and then when they add a new entry to the database there name is put as the author. This is how my tables are set up. One table is named job and has the columns id, jobtext, jobdate, and authorid. Another table is called author. This table contains the columns id, username, password, and name. Authorid from the job table matches with id from the author table. When a user logins in this code is used to register the name...session_start(); $_SESSION['myusername'] = $_POST['myusername']; $_SESSION['mypassword'] = $_POST['mypassword']; header("location: index.php"); } else { echo "Wrong Username or Password"; } This is the form users use to add a new entry... if (isset($_GET['add'])) { $pagetitle = 'New Job'; $action = 'addform'; $text = ''; $authorid = ''; $id = ''; $button = 'Add job'; include $_SERVER['DOCUMENT_ROOT'] . '/jobs/includes/db.inc.php'; // Build the list of authors $sql = "SELECT id, name FROM author"; $result = mysqli_query($link, $sql); if (!$result) { $error = 'Error fetching list of authors.'; include 'error.html.php'; exit(); } while ($row = mysqli_fetch_array($result)) { $authors[] = array('id' => $row['id'], 'name' => $row['name']); } // Build the list of categories $sql = "SELECT id, name FROM category"; $result = mysqli_query($link, $sql); if (!$result) { $error = 'Error fetching list of categories.'; include 'error.html.php'; exit(); } while ($row = mysqli_fetch_array($result)) { $categories[] = array( 'id' => $row['id'], 'name' => $row['name'], 'selected' => FALSE); } include 'form.html.php'; exit(); } if (isset($_GET['addform'])) { include $_SERVER['DOCUMENT_ROOT'] . '/includes/db.inc.php'; $text = mysqli_real_escape_string($link, $_POST['text']); $author = mysqli_real_escape_string($link, $_POST['author']); if ($author == '') { $error = 'You must choose an author for this job. Click ‘back’ and try again.'; include 'error.html.php'; exit(); } $sql = "INSERT INTO job SET jobtext='$text', jobdate=CURDATE(), authorid='$author'"; if (!mysqli_query($link, $sql)) { $error = 'Error adding submitted job.'; include 'error.html.php'; exit(); } $jobid = mysqli_insert_id($link); if (isset($_POST['categories'])) { foreach ($_POST['categories'] as $category) { $categoryid = mysqli_real_escape_string($link, $category); $sql = "INSERT INTO jobcategory SET jobid='$jobid', categoryid='$categoryid'"; if (!mysqli_query($link, $sql)) { $error = 'Error inserting job into selected category.'; include 'error.html.php'; exit(); } } } header('Location: .'); exit(); } Form.html.php = <?php include_once $_SERVER['DOCUMENT_ROOT'] . '/includes/helpers.inc.php'; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title><?php htmlout($pagetitle); ?></title> <meta http-equiv="content-type" content="text/html; charset=utf-8"/> <style type="text/css"> textarea { display: block; width: 100%; } </style> </head> <body> <?php session_start(); ?> <h1><?php htmlout($pagetitle); ?></h1> <form action="?<?php htmlout($action); ?>" method="post"> <div> <label for="text">Type your job he </label> <textarea id="text" name="text" rows="3" cols="40"><?php htmlout($text); ?></textarea> </div> <div> <label for="author">Author:</label> <select name="author" id="author"> <option value="">Select one</option> <?php foreach ($authors as $author):?> <option value="<?php htmlout($author['id']); ?>"<?php if ($author['id'] == $authorid) echo ' selected="selected"'; ?>><?php htmlout($author['name']); ?></option> <?php endforeach; ?> </select> </div> <fieldset> <legend>Categories:</legend> <?php foreach ($categories as $category): ?> <div><label for="category<?php htmlout($category['id']); ?>"><input type="checkbox" name="categories[]" id="category<?php htmlout($category['id']); ?>" value="<?php htmlout($category['id']); ?>"<?php if ($category['selected']) { echo ' checked="checked"'; } ?>/><?php htmlout($category['name']); ?></label></div> <?php endforeach; ?> </fieldset> <div> <input type="hidden" name="id" value="<?php htmlout($id); ?>"/> <input type="submit" value="<?php htmlout($button); ?>"/> </div> </form> </body> </html> Right now, under authors, it displays all the authors in the database. I want it to just show/submit the authorid of the logged in user. Maybe some of the great coders here can help this noob out. So here is what I have so far: Code: [Select] //set age criteria for deletion $age = 60; //get current date $datenow = date("Y-m-d"); //set the range we want to delete $delete_range = $datenow - $age; //get old user_id from users table $oldusers_users = mysql_query ("SELECT user_id FROM users WHERE lastvisit < $delete_range "); //get user_id from images table that correspond to users table $oldusers_images = mysql_query ("SELECT user_id FROM images WHERE $oldusers_users=user_id.images "); //find folders that correspond to the usernames and delete $oldusers_files = mysql_query ("SELECT username FROM users WHERE lastvisit < $delete_range "); //print out username //$result = mysql_($oldusers_files); $foldername = mysql_result($oldusers_files, 0); $sigspath = "sigs/"; unlink($sigspath . $foldername . ".gif/index.php"); rmdir($sigspath . $foldername . ".gif"); //now delete user_id's from database mysql_query("DELETE * FROM users WHERE user_id=$oldusers_users"); mysql_query("DELETE * FROM images WHERE user_id=$oldusers_images"); unset($oldusers_users, $oldusers_images, $oldusers_files, $foldername, $sigspath ); mysql_close($link); Right now it is only returning the first entry, not the entire list that meets the criteria. It does delete that one file though but does not remover the rows from the database. I am sure the database stuff is jacked up I am really new to that part. What am I doing wrong here or is there a better way to do this perhaps Hi everyone, I need a little bit of help finishing off my code. Ive managed to get this far. Code: [Select] <?php mysql_connect("") or die ("Not Connected to MYSQL"); echo "</br>"; mysql_select_db("") or die ("Not Connected to DB"); // Database Connection stuff $partialNumber = $_POST['partialNumber']; // Post the Partial number $partialNumber = strtoupper($partialNumber); $numberSearch = mysql_query("SELECT * FROM product_option_value_description WHERE name LIKE '%$partialNumber%'") or die (mysql_error()); // Query to select the key number //Query to get product ID // $productId = "SELECT product_id FROM product_option_value_description"; //Query to get product ID // while ($keyNumber = mysql_fetch_array($numberSearch)) { $id = $keyNumber['product_id']; // Query for the images // $query = "SELECT image FROM product WHERE product_id = '$id'"; $result = mysql_query($query); $row = mysql_fetch_array($result) or die(mysql_error()); $query2 = "SELECT product_option_id FROM product_option_value WHERE product_id = '$id'"; $result2 = mysql_query($query2); $row2 = mysql_fetch_array($result2) or die(mysql_error()); $query3 = "SELECT product_option_value_id FROM product_option_value WHERE product_id = '$id'"; $result3 = mysql_query($query3); $row3 = mysql_fetch_array($result3) or die(mysql_error()); ?> <div> <br /><br /> Key Number: <? echo $keyNumber['name']; ?></a> <form action="http://www.co.uk/teststore/index.php?route=checkout/cart" method="post" enctype="multipart/form-data" id="product"> <br /> <table style="width: 100%;"> <tr> <td> Colour: <select name="option[<? echo $row2['product_option_id']; ?>]"> <option value="<? echo $row3['product_option_value_id']; ?>"></option> </select></td> </tr> </table> <div class="content"> Qty: <input type="text" name="quantity" size="3" value="1" /> <input type="hidden" name="product_id" value="<? echo $id; ?>" /> <input name="submit" type="submit" value="Add to Cart" /> </div> </form> <? echo $row3['product_option_value_id']; ?> </div> <br /> <img height="150" width="150" src='http://www.co.uk/teststore/image/<? echo $row['0']; ?>'/> <? } ?> And here is my SQL Table code. Code: [Select] product_option_value_id product_option_id product_id 599 302 49 598 302 49 589 297 42 588 297 42 So as you can probably tell, it is a search program that looks for products on a shopping cart. The products will have different option values, and the php script will grab the option values and echo them in a form to post back to the cart to add the product to the basket. The problem is that the "product_option_value_id" can have lots of different values, but my code echos only the first one it finds. So when I click the add to cart button, it will only add the first option value for the product it finds. For some reason I am having a hard time explaining this, so I hope someone can help me. Thanks for looking. |