PHP - My While Loop And Sql Insert Won't Work
My while loop to do the process to every member_id won't work.Its only printing one member_id thats done.Also my INSERT statement wont insert even that 1 member_id. Can someone please point my mistake.
Code: [Select] <?php include 'config.php'; function tree_gather($node) { $sql = "SELECT lchild,rchild FROM tree WHERE parent = '$node'"; $execsql = mysql_query($sql); $array = mysql_fetch_array($execsql); if(!empty($array['lchild']) || !empty($array['rchild'])) { if(!empty($array['lchild'])) $child[] = $array['lchild']; if(!empty($array['rchild'])) $child[] = $array['rchild']; if(!empty($array['lchild'])) $lchild = tree_gather($array['lchild']); if(!empty($array['rchild'])) $rchild = tree_gather($array['rchild']); if(!empty($lchild) && !empty($rchild)) { $merge_both = array_merge($lchild, $rchild); $child = array_merge($child, $merge_both); } elseif(!empty($lchild) && empty($rchild)) $child = array_merge($child, $lchild); elseif(!empty($rchild) && empty($lchild)) $child = array_merge($child, $rchild); } return $child; } $sql = mysql_query("SELECT member_id FROM member"); while($array = mysql_fetch_array($sql)) { $memid = $array['member_id']; $pair = tree_gather($memid) ; $remove = mysql_query("SELECT lchild,rchild FROM tree WHERE parent ='".$memid."'"); $remove_array = mysql_fetch_array($remove); if(!empty($remove_array['lchild']) || !empty($remove_array['rchild'])) { $count = count($pair); for($i = 0 ; $i < $count ; $i++) { if($pair[$i] != $remove_array['lchild'] && $pair[$i] !=$remove_array['rchild']) { $trimmed[] = $pair[$i]; } else { $two_one[] = $pair[$i]; } } } $add = mysql_query("SELECT lchild,rchild FROM tree WHERE parent='".$remove_array['lchild']."'"); $add_array = mysql_fetch_array($add); if(!empty($add_array['lchild']) || !empty($add_array['rchild'])) { $count = count($trimmed); for($i=0;$i < $count ; $i++) { if(!empty($add_array['lchild'])) { if($add_array['lchild'] == $trimmed[$i]) { $two_one[] = $add_array['lchild']; unset($trimmed[$i]); $done = 1; break; } } if(!empty($add_array['rchild']) && $done !=1) { if($add_array['rchild'] == $trimmed[$i]) { $two_one[] = $trimmed[i]; unset($trimmed[$i]); $done = 1; break; } } } } if($done != 1) { $add = mysql_query("SELECT lchild,rchild FROM tree WHERE parent='".$remove_array['rchild']."'"); $add_array = mysql_fetch_array($add); if(!empty($add_array['lchild']) || !empty($add_array['rchild'])) { $count = count($trimmed); for($i=0;$i < $count ; $i++) { if(!empty($add_array['lchild'])) { if($add_array['lchild'] == $trimmed[$i]) { $two_one[] = $add_array['lchild']; unset($trimmed[$i]); $done = 1; break; } } if(!empty($add_array['rchild']) && $done !=1) { if($add_array['rchild'] == $trimmed[$i]) { $two_one[] = $trimmed[i]; unset($trimmed[$i]); $done = 1; break; } } } } } $select_child = mysql_query("SELECT rchild,lchild FROM tree WHERE parent='".$memid."'"); $select_array = mysql_fetch_array($select_child); if(!empty($select_array['rchild'])) $rchild = tree_gather($select_array['rchild']); $rchild[] = $select_array['rchild']; if(!empty($select_array['lchild'])) $lchild = tree_gather($select_array['lchild']); $lchild[] = $select_array['lchild']; if(!empty($rchild)) { $right_count = count($rchild); } if(!empty($lchild)) { $left_count = count($lchild); } if($right_count < $left_count) { $pair_num = $right_count; } elseif($right_count == $left_count) { $pair_num = $right_count - 1; } else { $pair_num = $left_count; } if(count($two_one) == 3) { $dues_adjust = 100; if($pair_num >= 1) { $dues_adjust = $dues + 100; $calcom = 200 * $pair_num; $tds = 20.60 * $pair_num; $service = 9.40 * $pair_num; $paid = $calcom - $dues_adjust; $insert = mysql_query("INSERT INTO `payout` (member_id, binary, tds, service, total, dues, amount_paid, dues_adjust, pairs) VALUES ('".$memid."', '".$calcom."', '".$tds."', '".$service."', '".$calcom."', '0', '".$paid."', '".$dues_adjust."', '".$pair_num."')"); unset($pair); echo "<br />".$memid." Done"; } } } ?> Similar TutorialsHi, I am trying to get this code to work: class People { public function insertAuthor(){ $authArray = $_POST['author']; $PCorder = 0; foreach($authArray as &$author): //Check if Pname exists $query = "SELECT * FROM People WHERE Pname = '".$author."'"; $result = mysql_query($query); if(mysql_num_rows($result) > 0): $row = mysql_fetch_array($result); $Pid = $row['Pid']; $sql = "INSERT INTO PeopleCon(Pid, PCorder, PCdateadded, PCdeleted) VALUES (".$Pid.", ".$PCorder++.", now(), 0)"; //die($sql); $result = mysql_query($sql); endif; endforeach; } } so basically for EVERY author that is inserted, check to see if their name exists and do the INSERT. I don't get any errors with this code but it doesn't do the INSERT.. Any ideas why? Thanks again Regards Billy I have a code that will enter the information into a database but as follows: A B C D E 1 2 3 4 5 I am looking for it all to be on the same row like: A B C D E 1 2 3 4 5 Here is my code: <?php if($_SESSION['admin'] !='Yes') { Echo "You are not approved to view this page!"; } Else { echo "<form action=main.php?id=test1.php method=post>"; echo "<table border=0>"; $sql = "select * from `pipilots` WHERE `enabled` = 'Yes' ORDER BY `pilot name` ASC"; $result = mysql_query($sql) or die (mysql_error()); ?> <td>Date</td> <td><input name="pi" id="pi" type="hidden" size="10"> <a href="javascript:NewCal('pi','YYYYMMDD')"><img src="images/cal.gif" width="16" height="16" border="0" alt="Pick a date"></a></td> <?php echo "<tr><td>Pilot Name: </td><td><select name = pilotname>"; while ($row = mysql_fetch_array($result)) { echo "<option Value=".rawurlencode($row['pilot name']).">".$row['pilot name']."</option>"; } echo "</select></td></tr>"; $sql = "select * from `piprice` WHERE `enabled` = 'Yes' ORDER BY `product name` ASC"; $result = mysql_query($sql) or die (mysql_error()); $count = mysql_num_rows($result); while ($row = mysql_fetch_array($result)) { $pname[] = $row['product name']; echo "<tr><td>".$row['product name'].":</td><td> <input name=name[] type=text></td></tr>"; } echo"</table> <input name=submit type=submit Value=Add> </form>"; if(isset($_POST['submit'])) { $name = $_POST['name']; $date = $_POST['pi']; $pilotname = $_POST['pilotname']; echo rawurldecode($pilotname)."<br>"; echo $date."<br>"; for($i=0;$i<$count;$i++){ echo $pname[$i]." = ".$name[$i]."<br>"; $sql1="INSERT INTO `pi` (`pilot name`, `$pname[$i]`, `date`) VALUES ('$pilotname', '$name[$i]', '$date' )"; $result1=mysql_query($sql1) or die (mysql_error()); } }} ?> And this is the part that I think I need help with: if(isset($_POST['submit'])) { $name = $_POST['name']; $date = $_POST['pi']; $pilotname = $_POST['pilotname']; echo rawurldecode($pilotname)."<br>"; echo $date."<br>"; for($i=0;$i<$count;$i++){ echo $pname[$i]." = ".$name[$i]."<br>"; $sql1="INSERT INTO `pi` (`pilot name`, `$pname[$i]`, `date`) VALUES ('$pilotname', '$name[$i]', '$date' )"; $result1=mysql_query($sql1) or die (mysql_error()); } Any help would be great. I've got Code: [Select] for ($i=1; $i<=5; $i++) { if(isset($_POST['partsusedqty'.$i]) && $_POST['partsusedqty'.$i] != "" && $_POST['partsusedqty'.$i] != "0.00") { mysql_query("INSERT INTO partsused (ptnumber, partqty, partdesc, partprice) VALUES ($ticket, '$partsusedqty'.$i, '$partsuseddesc'.$i, '$partsusedprice'.$i)") or die(mysql_error()); } } I need to know the correct formatting to put these variable variables as values in the mysql query. With this particular code, I get the error "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.1, ''.1, ''.1)' at line 2" I've tried formatting this an endless number of ways, but I used this particular example because its the one I really thought should work. Everything I've tried that doesn't throw an error put the $partsusedqty in the partqty, partdesc, and partprice fields. Thanks for any help! im trying to do a multi insert form using for loop. the concept is specifying a number and then using it in the for loop. the loop then makes a number of fields depending on the specified number. after that i use another for loop to insert the grouped fields together. code for specifying desired number Code: [Select] <? if ($_GET[num]=="") { ?><form name="form1" method="post" action="multiup.php?num=1"> <input name="num" type="text" value="10" maxlength="2"> <input type="submit" name="button" id="button" value="Submit"> </form><? } ?> Code: [Select] <? } else { ?><form name="form2" method="post" action="multiup2.php"> <input name="adder" type="hidden" value=""> <input name="num" type="hidden" value="<? echo $_POST[num]; ?>"> code for displaying fields <? for ($i=1;$i<=$_POST[num];$i++) { echo "groupnumber<br /> <input name='eno$i' type='text' value='$i'> Thumb <input name='thumb$i' type='text'> link1<br /> ";} ?> the insert code Code: [Select] <? if(isset($_POST['submit']) && ($_POST['submit'] == "Submit")) { $con = mysql_connect("lalalalala"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("kiphi_main", $con); for ($i=1;$i<=$_POST[num];$i++) { $title="$eno$i"; $sql="INSERT INTO articles (title) VALUES ('$_POST[$title]')"; } } if (!mysql_query($sql,$con)) {echo testest;}?> problem is i cant get it to work... should i try a different approach? Hi, Here is an extract of my while loop while ($personquery = mysql_fetch_array($personfetch, MYSQL_ASSOC)) { echo "$personfetch[first_name]"; } This will list each person now I want to do an INSERT to the database on every single member that is being listed I can only get it to INSERT for the one. Thanks I have developed the following code, which queries a MySQL database and returns multiple results using several WHILE loops: Code: [Select] <?php # if submit_hash is present, then pull up the attendance from specified hash if($_GET['submit_hash']) { # select all the hashers from the specified hash $query = " SELECT h.*, ha.* FROM hashes as h, hashers as ha, hash_records as hr WHERE hr.hash_id = " . $_GET['hash_id'] . " && hr.hash_id = h.hash_id && hr.hasher_id = ha.hasher_id ORDER BY ha.hasher_name "; $result = mysql_query($query) or die('Error selecting Hash attendance.'); $x = 1; while($row = mysql_fetch_array($result)) { if($x == 1) { echo '<strong>' . $row['hash_num'] . ' ' . $row['hash_name'] . ' - ' . date("D, d M Y", strtotime($row['hash_date'])) . '</strong><em>Total Hashers: ' . mysql_num_rows($result) . '</em>'; $x++; } # see if this person was the hare if($row['hare_id'] == $row['hasher_id'] || $row['hare2_id'] == $row['hasher_id'] || $row['hare3_id'] == $row['hasher_id']) { $hare = '- hare'; } else { $hare = ''; } echo $row['hasher_name'] . ' <b>' . $hare . '</b>'; } } else if($_GET['submit_hasher']) { # if submit_hasher is present, pull up all of their hashes and aliases # select all the hashes that this person has attended $a_query = " SELECT h.*, ha.* FROM hashes as h, hashers as ha, hash_records as hr WHERE hr.hash_id = h.hash_id && hr.hasher_id = ha.hasher_id && hr.hasher_id = " . $_GET['hasher_id'] . " ORDER BY h.hash_date DESC "; $a_result = mysql_query($a_query) or die('Error selecting the person\'s Hashes . '); $x = 1; while($a_row = mysql_fetch_array($a_result)) { if($x == 1) { echo '<strong>Hash Attendance Record For ' . $a_row['hasher_name'] . '</strong> <em>(' . mysql_num_rows($a_result) . ' total hashes)</em>'; $x++; } echo '#' . $a_row['hash_num'].' ' . $a_row['hash_name'] . ' on ' . date("D, d M Y", strtotime($a_row['hash_date'])); # see if this person was a hare if($a_row['hasher_id'] == $a_row['hare_id'] || $a_row['hasher_id'] == $a_row['hare2_id'] || $a_row['hasher_id'] == $a_row['hare3_id']) { echo ' - <b>hare</b>'; } echo ''; } echo ''; } echo ' <table width="100%"> <br /> <tbody> <tr> <br /> <td> '; ?> The problem is that everything that is returned from the WHILE loops is displayed in a single line. However, I want the data displayed with a line break between each result, like this: Header Return 1 from WHILE loop Return 2 from WHILE loop Return 3 from WHLIE loop How do I need to modify the code to make it display appropriately? Hi - I have spent 2 days trying to figure this out. I must be doing something stupid ... I am trying to update the DB with a collection of variables off of a various POST array's. I have indexed the variables so that I can loop through them with a FOR. However I am having all kinds of trouble: 1 - WEIGHT is giving 5 values even though the counter should only go 4 times. 2 - The WEIGHT variable is going into the wrong field in the DB even though I specify in my Query a specific place. 3 - I get undefined offset errors even though I have initialised the variables with their respective offsets. 4 - Adding the conditional statement adds even more offset errors even though they are initialised I am starting to wonder if my entire approach to updating my DB is flawed. As a student of PHP I think I need someone with more experience to look at what I am doing and tell me if something jumps out at them. There is a lot of statements echoing out values - and they all seem to check out. Man Many thanks for your advice Code: [Select] function finishedorder(){ $prodname = $_POST['prodname']; $prodid =$_POST['prodid']; $quantity = $_POST['quantity']; $pricelb = $_POST['pricelb']; $customerid = $_POST['customerid']; $price = $_POST['price']; $orderid = $_POST['orderid']; $weight = $_POST['weight']; echo "Varuable WEight"; print_r($weight); echo"<br/>"; echo "line 196 Weight"; print_r ($_POST['weight']); echo"<br/>"; echo "line 192 PriceLB"; print_r ($_POST['pricelb']); echo "<br/>"; echo "line 193 Price"; print_r ($_POST['price']); echo "<br/>"; echo "line 194 ProdID"; print_r ($_POST['prodid']); echo "<br/>"; echo "line 195 OrderID"; print_r ($_POST['orderid']); echo "<br/><br/>"; $numloops = count($_POST['prodid']); for ($i = 0; $i < $numloops ; $i++) { // !!! Start of the for loop !!! if (!isset($orderid[$i])) $orderid[$i] =''; if (!isset($prodid[$i])) $prodid[$i] =''; if (!isset($weight[$i])) $weight[$i] =''; if (!isset($pricelb[$i])) $pricelb[$i] =''; // This only initialises the Price & Weight variable to avoid an offset error message. if (!isset($weight[$i])) $weight[$i] =''; $ordervalue = $pricelb[$i] * $weight[$i]; echo " L. 216 The number is " . $i . "<br />"; echo "line 221 ProdID".$prodid[$i];echo "<br/>"; echo "line 217 Pricelb".$pricelb[$i];echo "<br/>"; echo 'Weight L. 219 weight[i]'. $weight[$i];echo "<br/>"; echo "line 220 weight".$weight; echo "<br/>"; echo "line 221 Numloops".$numloops; echo "<br/><br/>"; echo ' L. 225 $ordervalue ' .$ordervalue;echo "<br/>"; } //if ($pricelb[$i] == 0 ){ // conditonal statement // $ordervalue = $price[$i]; // } $sql =" UPDATE confirmedorder SET weight='$weight[$i]', ordervalue='$ordervalue', confirmedorder.picking = 'finished', confirmedorder.sale = 'open' WHERE prodID = '$prodid[$i]' AND OrderID = '$orderid[$i]' ; "; $this->db->query($sql); } // !! End For Loop. !! I don't understand why won't my INSERT work. Nothing gets inputted to the database.Why ? Code Code: [Select] $sql = "INSERT INTO payout (member_id, binary, tds, service, total, dues, amount_paid) VALUES ('".$memid."', '".$binary."', '".$tds."', '".$service."', '".$total."', '".$dues."', '".$amount_paid."')"; $execsql = mysql_query($sql); SQL table Code: [Select] CREATE TABLE IF NOT EXISTS `payout` ( `member_id` int(8) NOT NULL, `binary` int(10) NOT NULL, `tds` decimal(7,2) NOT NULL, `service` decimal(7,2) NOT NULL, `total` int(10) NOT NULL, `dues` int(10) NOT NULL, `amount_paid` int(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; I am really just a beginner in PHP but I've got a task to create a simple hotel booking system by using PHP and MySQL. It works in several steps, described in separate .php files. All of them seem to work fine, except the last one. In this last file I want to add all the data into a MySQL database table. I would like to do this by creating a record for each date, a guest is spending in a hotel (so that when booking, another loop checks whether the room is not occupied yet for that date). I decided to use a for-loop for that, but it doesn't seem to be working (the records just don't get inserted into the table). I checked all the variables by echo-ing them and they are all right. I also tried the query without the loop and it works as well. So I guess there is some other problem. This particular .php file looks as follow: <?php session_start(); include('db_config.php'); $name=($_POST['name']); $telephone=addslashes($_POST['telephone']); $email=addslashes($_POST['email']); $code=md5($email.time()); $checkout_date=$_SESSION['checkout']; $checkin_unix=$_SESSION['checkin_unix']; $checkout_unix=$_SESSION['checkout_unix']; $roomtype=$_SESSION['roomtype']; $checkin_date=$_SESSION['checkin']; for ($stay_date=$checkin_unix; ; $stay_date=$stay_date+24*60*60) { if ($stay_date=$checkout_unix){ break; } mysql_query("INSERT INTO reservations VALUES( '', '$roomtype', 'pending', 'date ('d/m/Y', $stay_date)', '$stay_date', '$checkout_date', '$name', '$telephone', '$email', '$code' )"); } ?> I would appreciate any kind of help, any idea. <?php function test(){ $x = ''; $arr = array('co'=>'color','ct'=>'design','cv'=>'weight','cm'=>'hight','cp'=>'price'); foreach($arr as $k=> $v){ $x .= '<tr><td> Td '.$k.' </td><td> Td '.$v.'</td></tr>' /* AFTER ACCESS THE ROW THAT DISPLAY "<tr><td> Td ct </td><td>Td design </td></tr>" */ /* insert HTML CODE (not by echo ) then complete the loop */ } return $x; } ?>
Hi Guys, in code below i dont see any reason why it doesnt add anything into my mysql, can u please tell me where is wrong? <?php session_start(); include ("includes/db.php"); include ("includes/function.php"); //authentication if (loggedin()==FALSE) { Header("Location: login.php"); exit(); } //username session $_SESSION['username']=='$username'; $username=$_SESSION['username']; echo "Welcome, " .$_SESSION['username']."!<p>"; //get details from user table to be passed to page(text fields) $getdetails=mysql_query("SELECT * FROM users WHERE username='$username'"); while($row = mysql_fetch_array($getdetails)) { $users_id=$row['id']; $first_name=$row['first_name']; $last_name=$row['last_name']; $email=$row['email']; } /////////////////////////////////////// //****************************// //post starts here if (isset($_POST['next']) && $_POST['next']) { $myfirstname = addslashes(strip_tags($_POST['firstname'])); $mylastname = addslashes(strip_tags($_POST['lastname'])); $myemail = addslashes(strip_tags($_POST['email'])); $mybookingdate = addslashes(strip_tags($_POST['datetime'])); $mytime = addslashes(strip_tags($_POST['time'])); $myseatnumber = addslashes(strip_tags($_POST['seatnumber'])); $ride_id=1; //check if booking exists $checkbooking=mysql_query("SELECT * FROM booking WHERE date='$mybookingdate' AND time='$mytime' AND seat_no='$myseatnumber'"); if (mysql_num_rows($checkbooking)>=1) { echo "Seat No $myseatnumber For $mybookingdate at $mytime has been already taken, Please try a different seat, time or date"; } else { $addbooking=mysql_query("INSERT INTO booking (ride_id, users_id, time, date, seat_no) VALUES ('$ride_id','$users_id','$mytime','$mybookingdate','$myseatnumber'"); } } ?> <html> <head> <link type="text/css" href="css/smoothness/jquery-ui-1.8.6.custom.css" rel="stylesheet" /> <script type="text/javascript" src="includes/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="includes/jquery-ui-1.8.6.custom.min.js"></script> <script type="text/javascript"> $(function() { $('#datetime').datepicker({ dateFormat: 'dd.mm.yy' }); }); </script> </head> <body> <form name="booking" method="post" action=""> <p>First Name:<br /> <input type="text" name='firstname' value="<? echo "$first_name";?>"> <p>Last Name:<br /> <input type="text" name='lastname' value="<? echo "$last_name";?>"> <p>Email:<br /> <input type="text" name='email' value="<? echo "$email";?>"> <p>Choose a Date:<br /> <input type="text" name='datetime' id="datetime"> </p> <p> Select a Time:<br/> <select name='time'> <option value="9:00">9:00 <option value="9:07">9:07 <option value="9:14">9:14 <option value="9:21">9:21 <option value="9:28">9:28 <option value="9:35">9:35 <option value="9:42">9:42 <option value="9:49">9:49 <option value="9:56">9:56 <option value="10:03">10:03 <option value="10:10">10:10 <option value="10:17">10:17 <option value="10:24">10:24 <option value="10:31">10:31 <option value="10:38">10:38 <option value="10:45">10:45 <option value="10:52">10:52 <option value="10:59">10:59 <option value="11:02">11:02 <option value="11:09">11:09 <option value="11:16">11:16 <option value="11:23">11:23 <option value="11:30">11:30 <option value="11:37">11:37 <option value="11:44">11:44 <option value="11:51">11:51 <option value="11:58">11:58 </select> </p> <p> Select Seat Number:<br/> <select name='seatnumber'> <option value="1">Seat 1 <option value="2">Seat 2 <option value="3">Seat 3 <option value="4">Seat 4 <option value="5">Seat 5 <option value="6">Seat 6 <option value="7">Seat 7 <option value="8">Seat 8 <option value="9">Seat 9 <option value="10">Seat 10 <option value="11">Seat 11 <option value="12">Seat 12 <option value="13">Seat 13 <option value="14">Seat 14 <option value="15">Seat 15 <option value="16">Seat 16 <option value="17">Seat 17 <option value="18">Seat 18 <option value="19">Seat 19 <option value="21">Seat 20 <option value="22">Seat 22 <option value="23">Seat 23 <option value="24">Seat 24 <option value="25">Seat 25 <option value="26">Seat 26 <option value="27">Seat 27 <option value="28">Seat 28 <option value="20">Seat 29 <option value="30">Seat 30 <option value="31">Seat 31 <option value="32">Seat 32 <option value="33">Seat 33 <option value="34">Seat 34 <option value="35">Seat 35 <option value="36">Seat 36 <option value="37">Seat 37 <option value="38">Seat 38 <option value="39">Seat 39 <option value="40">Seat 40 <option value="41">Seat 41 <option value="42">Seat 42 <option value="43">Seat 43 <option value="44">Seat 44 <option value="45">Seat 45 <option value="46">Seat 46 <option value="47">Seat 47 <option value="48">Seat 48 </select> <p> <input type='submit' name='next' value='Next Step'> </form> <p> </body> </html> Code: [Select] <?php include_once("includes/config.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"> <head> <title><? $title; ?></title> <meta http-equiv="Content-Language" content="English" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" type="text/css" href="style.css" media="screen" /> </head> <body> <div id="wrap"> <div id="header"> <h1><? $title; ?></h1> <h2><? $description; ?></h2> </div> <? include_once("includes/navigation.php"); ?> <div id="content"> <div id="right"> <h2>Create</h2> <div id="artlicles"> <?php if(!$_SESSION['user']) { $username = $_POST['username']; $password = $_POST['password']; $name = $_POST['name']; $server_type = $_POST['type']; $description = $_POST['description']; if(!$username || !$password || !$server_type || !$description || !$name) { echo "Note: Descriptions allow HTML. Any abuse of this will result in an IP and account ban. No warnings! All forms are required to be filled out.<br><form action='create.php' method='POST'><table><tr><td>Username</td><td><input type='text' name='username'></td></tr><tr><td>Password</td><td><input type='password' name='password'></td></tr>"; echo "<tr><td>Sever Name</td><td><input type='text' name='name' maxlength='35'></td></tr><tr><td>Type of Server</td><td><select name='type'> <option value='Any'>Any</option> <option value='PvP'>PvP</option> <option value='Creative'>Creative</option> <option value='Survival'>Survival</option> <option value='Roleplay'>RolePlay</option> </select></td></tr> <tr><td>Description</td><td><textarea maxlength='1500' rows='18' cols='40'></textarea></td></tr>"; echo "<tr><td>Submit</td><td><input type='submit'></td></tr></table></form>"; } elseif(strlen($password) < 8) { echo "Password needs to be higher than 8 characters!"; } elseif(strlen($username) > 13) { echo "Username can't be greater than 13 characters!"; } else { $check1 = $db->prepare("SELECT username,name FROM servers WHERE username = ? OR name = ? LIMIT 1"); $check1->execute(array($username, $name)); if($check1->rowCount() > 0) { echo "Sorry, there is already an account with this username and/or server name!"; } else { $ip = $_SERVER['REMOTE_ADDR']; $insertQuery = $db->prepare("INSERT INTO servers (id, username, password, name, type, description, ip, votes, beta) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)"); $insertQuery->execute(array(null, $username, $password, $name, $server_type, $description, $ip, 0, 1)); if($insertQuery->errorInfo() > 0) { echo "Sorry, there was the following error:"; print_r($insertQuery->errorInfo()); } else { echo "Server has been succesfully created!"; } } } } else { echo "You are currently logged in!"; } ?> </div> </div> <div style="clear: both;"> </div> </div> <div id="footer"> <a href="http://www.templatesold.com/" target="_blank">Website Templates</a> by <a href="http://www.free-css-templates.com/" target="_blank">Free CSS Templates</a> - Site Copyright MCTop </div> </div> </body> </html> Whats wrong with that page? :/ MySQL version 5.1.73-cll
I can't seem to get the inventory table to insert the information I have stared in an array any help would be appreciated!!
<?php $username = $_SESSION['username']; ini_set('display_errors',1); error_reporting(E_ALL); //include "php/db/db_config.php"; include "php/db/db_config.php"; include "php/db/item_connect.php"; $id = $items_id['id']; $player = $account_info['player_id']; //Update database $sql = mysqli_query($my_database,"INSERT INTO inventory ( player_id, username, id ) VALUES('$player', '$username', '$id')"); //echo values of item id echo "<div class=\"loot\">"; echo "<b>Required Level:" . $items_id['requ_level'] . "</b><br />"; echo "<b>Name:" . $items_id['name'] . "</b><br />"; echo "<b>Min Str:" . $items_id['min_str'] . "<br />"; echo "<b>Min Int:" . $items_id['min_int'] . "<br />"; echo "<b>Min Dex:" . $items_id['min_dex'] . "<br />"; echo "<b>Type:" . $items_id['type']. "<br />"; echo "<b>Min Physical Dmg:" . $items_id['min_dmg'] . "<br />"; echo "<b>Max Physical Dmg:" . $items_id['max_dmg'] . "<br />"; echo "<b>Min Magic Dmg:" . $items_id['mag_attk_min'] . "<br />"; echo "<b>Max Magic Dmg:" . $items_id['mag_attk_max'] . "<br />"; echo "<b>Phys Defense:" . $items_id['phy_def'] . "<br />"; echo "<b>Magical Defense:" . $items_id['mag_def'] . "<br />"; echo "</div>"; ?>I get no errors or notices and the info fields show up as being populated. Hi coders,
i have a js to add multiple input and its depend to a user how many input should he want to add. and my problem is, it work insert data in a first line of rows but the rest of rows are not save.
any idea, what should i add to make it work.
js
<script> $(document).ready(function(){ $('#add').click(function(){ var inp = $('#box'); var i = $('input').size() + 1; $('<div id="box' + i +'"><input type="text" id="name" class="name" name="code[]' + i +'" placeholder="Input '+i+'"/><img src="remove.png" width="32" height="32" border="0" align="top" class="add" id="remove" /> </div>').appendTo(inp); i++; }); $('body').on('click','#remove',function(){ $(this).parent('div').remove(); }); }); </script>html <div id="box"> <input name = "code[]" type="text" id="name" class="name" placeholder="Input 1"> <img src="add.png" width="32" height="32" border="0" align="top" class="add" id="add" /> </div>php $rf = $_POST['regform']; $b = $_POST['branch']; $d = $_POST['date']; $c = $_POST['code']; $u = $_POST['user']; for($i = 0; $i<count($c); $i++) { $a_query = mysql_query("INSERT INTO code_number(ts_number,branch_id,yy,code,username) VALUES('$rf','$b','$d','$c[$i]','$u')"); } return $a_query; I have a php script that I've been running that seems to have been working but now I'm wondering if some of my logic is potentially off. I select records from a db table within a date range which I put into an array called ```$validCount``` If that array is not empty, that means I have valid records to update with my values, and if it's empty I just insert. The trick with the insert is that if the ```STORES``` is less than the ```Quantity``` then it only inserts as many as the ```STORES``` otherwise it inserts as many as ```Quantity```. So if a record being inserted with had Stores: 14 Quantity:12
Then it would only insert 12 records but if it had It would only insert 1 record. In short, for each customer I should only ever have as many valid records (within a valid date range) as they have stores. If they have 20 stores, I can have 1 or 2 records but should never have 30. It seems like updating works fine but I'm not sure if it's updating the proper records, though it seems like in some instances it's just inserting too many and not accounting for past updated records. This is the logic I have been working with:
if(!empty($validCount)){ for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $out[] = $failedUpdate; } } }else{ if($row2["QUANTITY"] >= $row2["STORES"]){ for($i=0; $i<$row2["STORES"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertStore; } } }elseif($row2["QUANTITY"] < $row2["STORES"]){ for($i=0; $i<$row2["QUANTITY"]; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $out[] = $failedInsertQuantity; } } } }
Let's say customer 123 bought 4 of product A and they have 10 locations
customerNumber | product | category | startDate | expireDate | stores Because they purchased less than their store count, I insert 4 records. Now if my ```$validCheck``` query selects all 4 of those records (since they fall in a valid date range) and my loop sees that the array isn't empty, it knows it needs to update those or insert. Let's say they bought 15 this time. Then I would need to insert 6 records, and then update the expiration date of the other 9 records.
customerNumber | product | category | startDate | expireDate | stores There can only ever be a maximum of 10 (store count) records for that customer and product within the valid date range. As soon as the row count for that customer/product reaches the equivalent of stores, it needs to now go through and update equal to the quantity so now I'm running this but it's not running and no errors, but it just returns back to the command line $total = $row2['QUANTITY'] + $validCheck; if ($total < $row2['STORES']) { $insert_count = $row2['QUANTITY']; $update_count = 0; } else { $insert_count = $row2['STORES'] - $validCheck; // insert enough to fill all stores $update_count = ($total - $insert_count); // update remainder } for($i=0; $i<$row2['QUANTITY']; $i++){ try{ $updateRslt = $update->execute($updateParams); }catch(PDOException $ex){ $failedUpdate = "UPDATE_FAILED"; print_r($failedUpdate); $out[] = $failedUpdate; } } for($i=0; $i<$insert_count; $i++){ try{ $insertRslt = $insert->execute($insertParams); }catch(PDOException $ex){ $failedInsertStore = "INSERT_STORE_FAILED!!!: " . $ex->getMessage(); print_r($failedInsertStore); $out[] = $failedInsertStore; } }```
First page adds a new job number, then the order page loaded with the job number id as a get id. Basically there is a while loop in the order page which shows products/services client can order and he chooses what he requires 'one or eight services' (8 in total) and some other variables like date of order and client name etc. Here is the order item code The first sql statement executes fine, but in the second sql query nothing happens $sql="insert into job_order(order_num,order_date,order_customer_id, order_remarks) values(".$_GET['id'].",NOW(),".$_POST['companyBox'].",'".$_POST['remarkBox']."');"; $res=mysql_query($sql); $id=mysql_insert_id(); foreach($_POST as $key => $value) { if(!empty($value)) { $key.' => '.trim(strip_tags($value)); $order="INSERT INTO orderprod (order_num,prod_id,order_amount,teeth_amount) VALUES ('$_GET[id]','$value','$value','$value');"; $orderres=mysql_query($order) or die(mysql_error()); } }?>$sql="insert into job_order(order_num,order_date,order_customer_id, order_remarks) values(".$_GET['id'].",NOW(),".$_POST['companyBox'].",'".$_POST['remarkBox']."');"; $res=mysql_query($sql); $id=mysql_insert_id(); foreach($_POST as $key => $value) { if(!empty($value)) { $key.' => '.trim(strip_tags($value)); $order="INSERT INTO orderprod (order_num,prod_id,order_amount,teeth_amount) VALUES ('$_GET[id]','$value','$value','$value');"; $orderres=mysql_query($order) or die(mysql_error()); } } ?> ============= This is the formI have removed parts which are irrelevant. Please note that dateBox and companyBox are not required to be looping as they are only for first table, echo "<form action=".$config_basedir."./vieworder.php?id=".$_GET['id']." name=form1 method=post>";?><table><tr><td><h4>JOB ORDER</H4></TD><TD></TD></TR><TR><TD>ORDER NUMBER</TD><TD><?PHP ECHO $_GET['id'] ?></td></tr><tr><td>ORDER DATE</td><td><input type=text name=dateBox></td></tr> <tr><td>COMPANY NAME</td><td><?PHP$sql="select * from customers";$res=mysql_query($sql);echo "<select name=companyBox><option value=''>Please select</option>";WHILE($fetch=mysql_fetch_assoc($res)){ echo "<option value='".$fetch['id']."'>".$fetch['cust_name']."</option>";} echo "</select>"; echo "</td></tr>"; ?> </table> <table><tr><th>ITEM</th><th>QUANTITY</th><th>N0. of Teeths</th></tr><tr><?PHP$sql="select * from products";$res=mysql_query($sql); WHILE($fetch=mysql_fetch_assoc($res)){ echo "<td><input type=text name=desBox value='".$fetch['prod_id']."'>".$fetch['prod_name']."</td><td><input type=text name=quantBox></td><td><input type=text name=teethBox></td>";echo "</tr>";}echo "</table>";?>echo "<form action=".$config_basedir."./vieworder.php?id=".$_GET['id']." name=form1 method=post>"; ?> <table> <tr> <td><h4>JOB ORDER</H4></TD><TD></TD> </TR> <TR> <TD>ORDER NUMBER</TD><TD><?PHP ECHO $_GET['id'] ?></td> </tr> <tr> <td>ORDER DATE</td><td><input type=text name=dateBox></td> </tr> <tr> <td>COMPANY NAME</td><td> <?PHP $sql="select * from customers"; $res=mysql_query($sql); echo "<select name=companyBox><option value=''>Please select</option>"; WHILE($fetch=mysql_fetch_assoc($res)){ echo "<option value='".$fetch['id']."'>".$fetch['cust_name']."</option>";} echo "</select>"; echo "</td></tr>"; ?> </table> <table> <tr> <th>ITEM</th><th>QUANTITY</th><th>N0. of Teeths</th> </tr> <tr> <?PHP $sql="select * from products"; $res=mysql_query($sql); WHILE($fetch=mysql_fetch_assoc($res)){ echo "<td><input type=text name=desBox value='".$fetch['prod_id']."'>".$fetch['prod_name']."</td> <td><input type=text name=quantBox></td> <td><input type=text name=teethBox></td>"; echo "</tr>";} echo "</table>"; ?> HERE IS THE IMAGE showing the populated services. http://dubads.com/images/order.jpg I have created a registration page to access my website. After the user registrate himself should appear an alert saying that the registration was OK and a redirect to main.php page... however for some reason if I create an insert statement the alert and the redirect don't appear... If I remove the insert the alert and the redirect works... why? This is part of the code of my 3 files: registration.php (ajax call) $('#submit').click(function() {var username2 = $('#uname2').val(); var password2 = $('#psw2').val(); $.ajax({ url: 'ajax/response.php', type: 'GET', data: {username2 : username2, password2: password2}, success: function(data) { if(data === 'correct') { alert("Username and Password have been created!"); //don' work with the insert location.replace("main.php"); //don' work with the insert } else { alert("Username or password are not correct... please register yourself!"); } } }); }); response.php (answer to ajax call) if(isset($_GET['username2']) && isset($_GET['password2'])) {$username2 = $_GET['username2']; $password2 = $_GET['password2']; if (checkUser($pdo, $username2) === true) { echo 'duplicate'; } else { insertUserPwd($pdo, $username2, $password2); //including this line the redirect and the alert doesn't work... the insert is OK echo 'correct'; } } data_access.php (the function works but doesn't permit alert and redirect to appear) function insertUserPwd(PDO $pdo, $usr, $pwd){ $data = [ 'id' => '', 'user' => $usr, 'password' => $pwd ]; $sql = "INSERT INTO users (id, user, password) VALUES (:id, :user, :password)"; $stmt= $pdo->prepare($sql); $stmt->execute($data); } Can someone help me to fix the code? Dear all, Help required in code: I have 2 tables (sites and photo_gallery) in my database. First I display my posts from database, then it goes to my viewpost page. Everything work file but in gallery portion my loop didn't work. IN TOP of the page I use this code to run all viewpost pages.
if(isset($_GET['id'])) { <?php
if($result->num_rows > 0){
?>
<?php } 1 to 15 images with every post and it will display only one 2nd image. Thank you for the help. This code works outside of the while, but not inside while ($row = mysql_fetch_assoc($res)) { $host = $row['host']; $cmd = exec("mysql -h$host -e \"show status like 'wsrep_cluster_size'\""); echo $cmd; } I have found nothing on google, stackoverflow or the php manual that explains why this does not appear to work inside a loop? Ok I'm trying to insert multiple rows by using a while loop but having problems. At the same time, need to open a new mysql connection while running the insert query, close it then open the previous mysql connection. I managed to insert multiple queries before using a loop, but for this time, the loop does not work? I think it is because I am opening another connection... yh that would make sense actually? Here is the code: $users = safe_query("SELECT * FROM ".PREFIX."user"); while($dp=mysql_fetch_array($users)) { $username = $dp['username']; $nickname = $dp['nickname']; $pwd1 = $dp['password']; $mail = $dp['email']; $ip_add = $dp['ip']; $wsID = $dp['userID']; $registerdate = $dp['registerdate']; $birthday = $dp['birthday']; $avatar = $dp['avatar']; $icq = $dp['icq']; $hp = $dp['homepage']; echo $username." = 1 username only? :("; // ----- Forum Bridge user insert ----- $result = safe_query("SELECT * FROM `".PREFIX."forum`"); $ds=mysql_fetch_array($result); $forum_prefix = $ds['prefix']; define(PREFIX_FORUM, $forum_prefix); define(FORUMREG_DEBUG, 0); $con = mysql_connect($ds['host'], $ds['user'], $ds['password']) or system_error('ERROR: Can not connect to MySQL-Server'); $condb = mysql_select_db($ds['db'], $con) or system_error('ERROR: Can not connect to database "'.$ds['db'].'"'); include('../_phpbb_func.php'); $phpbbpass = phpbb_hash($pwd1); $phpbbmailhash = phpbb_email_hash($mail); $phpbbsalt = unique_id(); safe_query("INSERT INTO `".PREFIX_FORUM."users` (`username`, `username_clean`, `user_password`, `user_pass_convert`, `user_email`, `user_email_hash`, `group_id`, `user_type`, `user_regdate`, `user_passchg`, `user_lastvisit`, `user_lastmark`, `user_new`, `user_options`, `user_form_salt`, `user_ip`, `wsID`, `user_birthday`, `user_avatar`, `user_icq`, `user_website`) VALUES ('$username', '$username', '$phpbbpass', '0', '$mail', '$phpbbmailhash', '2', '0', '$registerdate', '$registerdate', '$registerdate', '$registerdate', '1', '230271', '$phpbbsalt', '$ip_add', '$wsID', '$birthday', '$avatar', '$icq', '$hp')"); if (FORUMREG_DEBUG == '1') { echo "<p><b>-- DEBUG -- : User added: ".mysql_affected_rows($con)."<br />"; echo "<br />-- DEBUG -- : Query used: ".end($_mysql_querys)."</b></p><br />"; $result = safe_query("SELECT user_id from ".PREFIX_FORUM."users WHERE username = '$username'"); $phpbbid = mysql_fetch_row($result); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('2', '$phpbbid[0]', '0', '0')"); safe_query("INSERT INTO `".PREFIX_FORUM."user_group` (`group_id`, `user_id`, `group_leader`, `user_pending`) VALUES ('7', '$phpbbid[0]', '0', '0')"); mysql_close($con); } include('../_mysql.php'); mysql_connect($host, $user, $pwd) or system_error('ERROR: Can not connect to MySQL-Server'); mysql_select_db($db) or system_error('ERROR: Can not connect to database "'.$db.'"'); } So I need to be able to insert these rows using the while loop.. how can I do this? I really appreciate any help. |