PHP - Multiple Entries Into Database
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. Similar TutorialsI have a form where a user can duplicate part of a form like below: I've named the fields with the HTML arrays (ie. "fieldName[]") and came up with this: //--> CONTROLLERS $system_controllers_qty = $_POST['system_controllers_qty']; $system_controllers_make = $_POST['system_controllers_make']; $system_controllers_model = $_POST['system_controllers_model']; $system_controllers_serial_no = $_POST['system_controllers_serial_no']; for ($i = 0; $i < count($system_controllers_qty); $i++) { echo "qty " . clean($system_controllers_qty[$i]) . "<br/>"; echo "make " . clean($system_controllers_make[$i]) . "<br/>"; echo "model " . clean($system_controllers_model[$i]) . "<br/>"; echo "serial_no " . clean($system_controllers_serial_no[$i]) . "<br/>"; } //--> CPUS $system_cpus_qty = $_POST['system_cpus_qty']; $system_cpus_model = $_POST['system_cpus_model']; $system_cpus_serial_no = $_POST['system_cpus_serial_no']; $system_cpus_speed = $_POST['system_cpus_speed']; for ($i = 0; $i < count($system_cpus_qty); $i++) { echo "qty " . clean($system_cpus_qty[$i]) . "<br/>"; echo "model " . clean($system_cpus_model[$i]) . "<br/>"; echo "serial_no " . clean($system_cpus_serial_no[$i]) . "<br/>"; echo "speed " . clean($system_cpus_speed[$i]) . "<br/>"; } //--> DISKS $system_disks_qty = $_POST['system_disks_qty']; $system_disks_make = $_POST['system_disks_make']; $system_disks_model_no = $_POST['system_disks_model_no']; $system_disks_size = $_POST['system_disks_size']; $system_disks_serial_no = $_POST['system_disks_serial_no']; for ($i = 0; $i < count($system_disks_qty); $i++) { echo "qty " . clean($system_disks_qty[$i]) . "<br/>"; echo "make " . clean($system_disks_make[$i]) . "<br/>"; echo "model_no " . clean($system_disks_model_no[$i]) . "<br/>"; echo "size " . clean($system_disks_size[$i]) . "<br/>"; echo "serial_no " . clean($system_disks_serial_no[$i]) . "<br/>"; } //--> MEMORY $system_memory_qty = $_POST['system_memory_qty']; $system_memory_serial_no = $_POST['system_memory_serial_no']; $system_memory_manf = $_POST['system_memory_manf']; $system_memory_part_no = $_POST['system_memory_part_no']; $system_memory_size = $_POST['system_memory_size']; for ($i = 0; $i < count($system_memory_qty); $i++) { echo "qty " . clean($system_memory_qty[$i]) . "<br/>"; echo "serial " . clean($system_memory_serial_no[$i]) . "<br/>"; echo "manf " . clean($system_memory_manf[$i]) . "<br/>"; echo "part_no " . clean($system_memory_part_no[$i]) . "<br/>"; echo "size " . clean($system_memory_size[$i]) . "<br/>"; } This just outputs all the fields I post at the moment. Say I have 3 different disk types, it's going to loop 3 times. Is it possible to make this all into 1 giant query or am I better off doing each query separately? Each section is a different table. Hello, Hopefully I can ger som help here I have been googling this for months and seem to cant find anything that will help me out. I am trying to create a form (which is the easy part) but I want this form to send multiple entries at once from what I gather so far I need to use for each and/or loop which i am not familiar with it with my lack of knowledge........ what I have so far is Table= locations fields are id state county city the form is set up as follows state county city city city city city city city city city city city city The reason for so many cities is so i can update all cities in one county at the same time saving time I am not sure if its % doable in the manner i would like it to be done but i hope so ok i enter the state and county then i enter the cities i want i submit the form i want it to create the state/county and the first city with the next id # then enter the state/county and next city and id#. please some help me if u need to see my file let me know and ill post it im just not sure which one you need i believe it will be the save.php file but i also have the create.php file which is the form itself Thanks anyone for the help i can get Hi guys Im trying to delete multiple images from a page with the code below, I have retirieved the images successfully but i can not delete the with checkbox, wht it does is just refereshing the page and thats it, what im trying to do is to delete the image from the database but it wont. can u help me please? <?php session_start(); include ("../../global.php"); //welcome messaage $username=$_SESSION['username']; echo "$username"; $query=mysql_query("SELECT id FROM users WHERE username='$username'"); while($row = mysql_fetch_assoc($query)) { $user_id = $row['id']; } $ref=$_GET['reference']; $images=mysql_query("SELECT * FROM img WHERE refimage='$ref'"); while($row = mysql_fetch_array($images)) { $image=$row['image']; $thumb=$row['thumb']; ?> <table width="400" border="0" cellspacing="1" cellpadding="0"> <tr> <td><form name="" method="post" action=''> <tr> <td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td> <td bgcolor="#FFFFFF"><? echo "<a href='$image' rel='lightbox[roadtrip]'><img src= '$thumb' width='60' height='40' alt='$title'>";?></td> <? } ?> <tr> <td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td> </tr> <?php // Check if delete button active, start this $delete = $_REQUEST['delete']; if( $delete != '' ){ $checkbox = $_REQUEST['checkbox']; $count = count($_REQUEST['checkbox']); for($i=0;$i<$count;$i++){ $del_id = $checkbox[$i]; $del = mysql_query("DELETE FROM img WHERE id = '$del_id'"); } } ?> 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? 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. 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"); } 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++; } ?> 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 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')"); } Hi, I want to build into my html table that populates my database table to have a column for checkboxes with a delete button that takes the user to another page to confirm the deletion by outputting a message: Are you sure you want to delete ____, followed by a for loop to see how many checked records to get its ID in order to get its appropriate name. So I have a submit button with name attribute of "delete0" and the values of the input type of checkbox is $row['ID'], for some reason, I get the notice: "Notice: Undefined index: modifyArray in C:\display.php" and modifyArray is the name I give to the checkbox attribute (please see this in my display.php below) Here is my display.php Code: [Select] <table border="border"> <!--NB: checkbox form for multiple delete/update/insert--> <form method="post" action=""> <input type='submit' value='DELETE' name='delete0' /> <?php session_start(); require 'bellSessionDisconnect.inc'; require 'bellConnect.inc.php'; $result=mysql_query("SELECT ID, Image, Name, Manufacturer, Price, Description, SimSupport FROM bellProducts"); //phpinfo(); //NB: print table headings if(mysql_num_rows($result))//if there is at least one entry in bellProducts, make a table { //$counter+=1; print "<table border='border'>"; print "<tr> <th>ID</th> <th>Select entries to modifiy</th> <th>Image</th> <th>Name</th> <th>Manufacturer</th> <th>Price</th> <th>Description</th> <th>SimSupport</th> <th colspan='2' align='center'>Modify</th> </tr>"; //NB: now output each row of records while($row=mysql_fetch_assoc($result)) { //extract($row); "<tr align='center'> <td>$row[ID]</td> <td><input type='checkbox' name='modifyArray[]' value='$row[ID]' /></td> <td>"; if(!empty($row['Image'])) { $curImage=$row['Image']; } else if(empty($row['Image'])) { $curImage='fileUploadIcon.jpg'; //$title="please upload item image"; } print "<img src=$curImage width='70px' height='90px' /> </td> <td> $row[Name] </td> <td> $row[Manufacturer] </td> <td> $$row[Price]</td> <td align='left'>$row[Description]</td> <td>$row[SimSupport]</td> <td><a href='bellUploadForm.php?ID=$row[ID]'>UPLOAD IMAGE</a></td> <td><a href='bellUpdateForm.php?ID=$row[ID]'>UPDATE</a></td> </tr>"; //}//END INNER IF }//END WHILE }//END BIG IF ?> <?php if(array_key_exists('delete0', $_POST)) { $modifyArray=$_POST["modifyArray"]; if(!empty($modifyArray)) { header("Location: http://localhost/bellDeleteForm.php"); exit(); } } ?> </form> </table> I will worry about redirecting to bellDeleteForm.php to confirm the records the user wants to delete after I get this going, please help!!! thanks 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. 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."; } Here is one of those purely conceptual questions, which involves no code. I'm trying to create a select query which among other things, allows a user of a website to search other members who fall within a particular age range. I have a column in the table where the members' information are stored which records their ages. Which brings us to the problem. On any given day, a member's age may increase by one year compared to what it was the previous day, hence the need to update this column periodically. I can't think of any way to automatically update this column on a daily basis. So my solution is to run an initial update query every time a member tries to search other members based on age, which updates the age column for all other members, before running the select query which eventually retrieves the desired age range. This leads to the second problem. Imagine there are thousands of users using the website. At any given instance, there could be hundreds of members, trying to search others based on age. This means hundreds of users will be updating a single column (the age column) in one table at the same time. Is this feasible? Can it cause the server to crash? Or is there really a more reasonable way to do all of this? Thank you all for taking your time to read this. Appreciate any responses. 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 Hello, I am new to PHP coding, and I have some issues trying to upload multiple images into database. The code works only for 1 image, but when I try to add foreach, I receive this message: Warning: Invalid argument supplied for foreach() . Can anyone help me ?
This has been bugging me for quite a while and I've tried so many different things and just run into all kinds of problems... What I'm doing or trying at least is pulling data from a table displaying it into a multiple select box allowing the user the oppertunity to remove one or more options. As the code stands now I'm getting no value at all in the post variable, by taking the [] brackets out of the inputs name i was able to get the first selected option but the php code was then unable to remove that value from the database. I hope I'm explaining this well enough but the code follows I'd really appreciate some help or direction on this one. The FORM Code: [Select] <FORM action='' method='post'> <select size='8' multiple name='remove_player[]'> <?php foreach ($members as $key => $mem) { if ($mem != "") { $mem = str_replace("-", " ", $mem); $mem = ucwords($mem); echo ("<option value='" . $mem . "'>" . $mem . "</option>"); } } ?> </select> and then the handler code: Code: [Select] $to_remove = $_POST['remove_player']; $as_team = str_replace(" ", "-", $teamname); $as_team = strtolower($as_team); $for_remove = "SELECT * FROM teams WHERE name = '$as_team'"; $for_query = (mysql_query($for_remove)); foreach ($to_remove as $y => $z) { $z = str_replace(" ", "-", $z); $z = strtolower($z); } while($arr_remove = mysql_fetch_array($for_query)) { foreach ($arr_remove as $a => $b) { foreach ($to_remove as $c => $d) { if ($b == $d) { unset($arr_remove[$a]); } } } foreach ($arr_remove as $e => $f) { $add_replace = (mysql_result($for_query, 0, 'members')); $replace = ($add_replace . "\r\n" . $f . "\r\n"); $replace_mem = "UPDATE teams SET members = '$replace'"; $replace_q = (mysql_query($replace_mem)); } } echo "Member List successfully updated.<br>"; foreach ($to_remove as $h => $g) { echo ($g . " removed from the team.<br>"); } Also any time i try to print any part of the array/s I get no values but the database is being updated with 2 line breaks and a "3" at the end of the table which has me a bit confused as well. Thanks! |