PHP - Loop Through Database Table
this is my sql code
Code: [Select] <?php $query = "SELECT Player, SUM(GLI) AS 'gli', SUM(Goals) AS 'goals', SUM(Saves) AS 'saves', SUM(SOG) AS 'sog', SUM(Assists) AS'assists', SUM(CK) AS 'ck', SUM(YC) AS 'yc', SUM(RC) AS 'rc' FROM pinkpanther_stats GROUP BY Player; "; ?> their are 11 separate players and i want to set variables $adam_glie and $tyler_glie equal to the glie column for that player(the player being the first part of the variable) and i dont have any idea how to go about doing this Similar TutorialsHello forum. I'm new here, but I've been reading and finding useful things for a while now. I'm still new to PHP and I need a little help. I'm doing a school project and I have some things I want to do, but do not know how to write it down in PHP. I think I'll ask a lot of questions this week, and I hope I will get some help.. For start I want to ask this: I've been using Code: [Select] mysql_fetch_array() for doing loops and populating check-boxes. And everything's working fine.. but what I want is to control the actual loop by clicking buttons. Let's say first time a while-do is run, my check-boxes get populated from the database and every other loop the next data from the table is added.. pretty straightforward. I want to be able to populate once, then click "next" and the new data to be added and so on.. Code: [Select] <?php $tema = mysql_query("SELECT * from questions")or die(mysql_error()); function answer1($string) { $string1 = explode("/", $string); echo $string1[0]; } function answer2($string) { $string1 = explode("/", $string); echo $string1[1]; } while ($row=mysql_fetch_array($tema)) { echo mysql_fetch_array($tema); $tip=$row["tip"]; if ($tip==2) { $id=$row['prasanje_id']; $question=$row['question']; $answer=$row['answer']; ?> <label> <?php echo $question?></label><br> <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="CheckboxGroup1_0" /> <?php answer1($tekst) ?></label> <label> <input type="checkbox" name="CheckboxGroup1" value="checkbox" id="CheckboxGroup1_1" /> <?php answer2($tekst) ?></label> <?php } } ?>I want an alternative to the while-do loop.. Is it possible to do this? Thanks!! the second database found on the cloud
i try to get JSON data but how to insert and update them to another online database with the same table my php script to return json data <?php include_once('db.php'); $users = array(); $users_data = $db -> prepare('SELECT id, username FROM users'); $users_data -> execute(); while($fetched = $users_data->fetch()) { $users[$fetchedt['id']] = array ( 'id' => $fetched['id'], 'username' => $fetched['name'] ); } echo json_encode($leaders);
i get
{"1":{"id":1,"username":"jeremia"},"2":{"id":2,"username":"Ernest"}} Edited March 24 by mahenda Hi
I am very new to PHP & Mysql.
I am trying to insert values into two tables at the same time. One table will insert a single row and the other table will insert multiple records based on user insertion.
Everything is working well, but in my second table, 1st Table ID simply insert one time and rest of the values are inserting from 2nd table itself.
Now I want to insert the first table's ID Field value (auto-incrementing) to a specific column in the second table (only all last inserted rows).
Ripon.
Below is my Code:
<?php $con = mysql_connect("localhost","root","aaa"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("ccc", $con); $PI_No = $_POST['PI_No']; $PO_No = $_POST['PO_No']; $qry = "INSERT INTO wm_order_entry ( Order_No, PI_No, PO_No) VALUES( NULL, '$PI_No', '$PO_No')"; $result = @mysql_query($qry); $val1=$_POST['Size']; $val2=$_POST['Style']; $val3=$_POST['Colour']; $val4=$_POST['Season_Code']; $val5=$_POST['Dept']; $val6=$_POST['Sub_Item']; $val7=$_POST['Item_Desc']; $val8=$_POST['UPC']; $val9=$_POST['Qty']; $N = count($val1); for($i=0; $i < $N; $i++) { $profile_query = "INSERT INTO order_entry(Size, Style, Colour, Season_Code, Dept, Sub_Item, Item_Desc, UPC, Qty, Order_No ) VALUES( '$val1[$i]','$val2[$i]','$val3[$i]','$val4[$i]','$val5[$i]','$val6[$i]','$val7[$i]','$val8[$i]','$val9[$i]',LAST_INSERT_ID())"; $t_query=mysql_query($profile_query); } header("location: WMView.php"); mysql_close($con); ?>Output is attached. Hi there! On a page of mine, random tables get generated. The tables consist of 8 characters, so there's 5 . 10^13 possibilities. Yet ofcourse there is a possibility that 2 tables with the same name can be generated, which ofcourse is not desired. So I need an adjustment that can see whether there is already a name that's the same, and if so, make another random name. And if that one also exists, make a new one again. Untill the name doesn't exist yet and it remains. Here's the script I have right now: function createName($length) { $chars = "abcdefghijkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; $i = 0; $password = ""; while ($i <= $length) { $password .= $chars{mt_rand(0,strlen($chars))}; $i++; } return $password; } $name = createName(8); mysql_select_db($database, $con); $sql = "CREATE TABLE " . $name . "( id int NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), devraag varchar(500), weergave varchar(500), naam varchar(500), inhoud varchar(500), tijd varchar(100))"; mysql_query($sql, $connection)or die(mysql_error()); I'm not goot with the combination of PHP and mysql, and really have no Idea how to do this. Any help? Hi.. I need help in using for loop in saving data from while loop. Now, I encountered that the Demanded Qty was get only is the last Demanded Qty and save it to all Items. I want to happen is per Items will save the Demanded Qty. for example: Items Demanded Qty P28 ---1 P28 ---1 P28 ---1 P30 ---2 P30 ---2 P30 ---2 and so on.. here is my code: <?php error_reporting(0); date_default_timezone_set("Asia/Singapore"); //set the time zone $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); $sr_date =date('Y-m-d H:i:s'); $sql = "SELECT sr_number FROM stock_requisition ORDER BY sr_date DESC LIMIT 1"; $result = mysql_query($sql, $con); if (!$result) { echo 'failed'; die(); } $total = mysql_num_rows($result); if ($total <= 0) { $currentSRNum = 1; $currentYear = (int)(date('y')); $currentMonth = (int)(date('m')); $currentDay = (int)(date('d')); $currentSRYMD = substr($row['sr_number'], 0, 6); $currentYMD = date("ymd"); if ($currentYMD > $currentSRYMD) { $currentSRNum = 1; } else { $currentSRNum += 1; } } else { $row = mysql_fetch_assoc($result); $currentSRNum = (int)(substr($row['sr_number'],0,3)); $currentSRYear = (int)(substr($row['sr_number'],2,2)); $currentSRMonth = (int)(substr($row['sr_number'],0,2)); $currentSRNum = (int)(substr($row['sr_number'],6,4)); $currentYear = (int)(date('y')); $currentMonth = (int)(date('m')); $currentDay = (int)(date('d')); $currentSRYMD = substr($row['sr_number'], 0, 6); $currentYMD = date("ymd"); if ($currentYMD > $currentSRYMD) { $currentSRNum = 1; } else { $currentSRNum += 1; } } $yearMonth = date('ymd'); $currentSR = $currentYMD . sprintf("%04d", $currentSRNum); ?> <html> <title>Stock Requisition</title> <head> <link rel="stylesheet" type="text/css" href="kanban.css"> <script type="text/javascript"> function save_sr(){ var sr_date = document.getElementById("sr_date").value; var sr_number = document.getElementById("sr_number").value; var Items1 = document.getElementById("Items1").value; var SubItems = document.getElementById("SubItems").value; var ItemCode = document.getElementById("ItemCode").value; var DemandedQty = document.getElementById("DemandedQty").value; var UoM = document.getElementById("UoM").value; var Class = document.getElementById("Class").value; var Description = document.getElementById("Description").value; var BINLocation = document.getElementById("BINLocation").value; var RequestedBy = document.getElementById("RequestedBy").value; var ApprovedBy = document.getElementById("ApprovedBy").value; var ReceivedBy = document.getElementById("ReceivedBy").value; var IssuedBy = document.getElementById("IssuedBy").value; var Items = document.getElementById("Items").value; document.stock_requisition.action="StockRequisitionSave1.php?sr_date="+sr_date+"&sr_number="+sr_number+"&Items1="+Items1+ "&SubItems="+SubItems+"&ItemCode="+ItemCode+"&DemandedQty="+DemandedQty+"&UoM="+UoM+"&Class="+Class+"&Description="+ Description+"&BINLocation="+BINLocation+"&RequestedBy="+RequestedBy+"&ApprovedBy="+ApprovedBy+"&ReceivedBy="+ReceivedBy+ "&IssuedBy="+IssuedBy+"&Items="+Items; document.stock_requisition.submit(); alert("Stock Requisition data save."); window.location = "StockRequisition1.php"; } function disp(){ document.stock_requisition.action="StockRequisitionDisplay.php"; document.stock_requisition.submit(); } </script> </head> <body> <form name="stock_requisition" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post"> <div id="SR_date"> <label>Date :</label> <input type="text" name="sr_date" value="<?php echo $sr_date; ?>" size="16" readonly="readonly"> </div> <div id="SR_number"> <label>SR# :</label> <input type="text" name="sr_number" value="<?php echo $currentSR; ?>" size="10" readonly="readonly"> <br/> </div> <div> <table> <thead> <th>Items</th> <th>Sub Items</th> <th>Item Code</th> <th>Demanded Qty</th> <th>UoM</th> <th>Class</th> <th>Description</th> <th>BIN Location</th> </thead> <?php $sql = "SELECT DISTINCT Items FROM bom_subitems ORDER BY Items"; $res_bom = mysql_query($sql, $con); while($row = mysql_fetch_assoc($res_bom)){ $Items = $row['Items']; echo "<tr> <td> <input type='name' value='$Items' name='Items[]' id='Items' readonly = 'readonly' size='5'></td> <td> </td> <td> </td> <td><center><input type='text' name='DemandedQty' id='DemandedQty[]' value='' size='7'></center></td> </tr>"; $sql = "SELECT Items, SubItems, ItemCode, UoM, Class, Description, BINLocation FROM bom_subitems WHERE Items = '$Items' ORDER BY Items"or die(mysql_error()); $res_sub = mysql_query($sql, $con); while($row_sub = mysql_fetch_assoc($res_sub)){ $Items1 = $row_sub['Items']; $SubItems = $row_sub['SubItems']; $ItemCode = $row_sub['ItemCode']; $UoM = $row_sub['UoM']; $Class = $row_sub['Class']; $Description = $row_sub['Description']; $BINLocation = $row_sub['BINLocation']; echo "<tr> <td> <input type='hidden' value='$Items1' id='Items1' name='Items1[]'></td> <td> <input type='text' name='SubItems[]' value='$SubItems' id='SubItems' readonly='readonly' size='10'></td> <td> <input type='text' name='ItemCode[]' value='$ItemCode' id='ItemCode' readonly='readonly' size='10'></td> <td> </td> <td> <input type='text' name='UoM[]' value='$UoM' id='UoM' readonly='readonly' size='3'></td> <td> <input type='text' name='Class[]' value='$Class' id='Class' readonly='readonly' size='10'></td> <td> <input type='text' name='Description[]' value='$Description' id='Description' readonly='readonly' size='10'></td> <td> <input type='text' name='BINLocation[]' value='$BINLocation' id='BINLocation' readonly='readonly' size='10'></td> </tr>"; } } ?> </table> </div> <?php $RequestedBy = array('AAA', 'BBB'); $ApprovedBy = array('EEE', 'FFF'); $ReceivedBy = array('III', 'JJJ'); $IssuedBy = array('MMM', 'NNN'); ?> <div id='Requested_By'> <label>Requested By:</label> <select name="RequestedBy"> <option value="Select">Select</option> <option value="AAA" <?php if($_POST['RequestedBy'] == 'AAA') echo "selected='selected'"; ?>>AAA</option> <option value="BBB" <?php if($_POST['RequestedBy'] == 'BBB') echo "selected='selected'"; ?>>BBB</option> </select> </div> <div id='Approved_By'> <label>Approved By:</label> <select name="ApprovedBy"> <option name='Select'>Select</option> <option value="EEE" <?php if($_POST['ApprovedBy'] == 'EEE') echo "selected='selected'"; ?>>EEE</option> <option value="FFF" <?php if($_POST['ApprovedBy'] == 'FFF') echo "selected='selected'"; ?>>FFF</option> </select> </div> <div id='Received_By'> <label>Issued By:</label> <select name="IssuedBy"> <option name='Select'>Select</option> <option value="III" <?php if($_POST['ReceivedBy'] == 'III') echo "selected='selected'"; ?>>III</option> <option value="JJJ" <?php if($_POST['ReceivedBy'] == 'JJJ') echo "selected='selected'"; ?>>JJJ</option> </select> </div> <div id='Issued_By'> <label>Received By:</label> <select name="ReceivedBy"> <option name='Select'>Select</option> <option value="MMM" <?php if($_POST['IssuedBy'] == 'MMM') echo "selected='selected'"; ?>>MMM</option> <option value="NNN" <?php if($_POST['IssuedBy'] == 'NNN') echo "selected='selected'"; ?>>NNN</option> </select> </div> <div id="save_btn"> <input type="button" name="button" value="save" onClick="save_sr()" style="width: 5em;"> <input type="button" name="button" value="display" onclick="disp()"> </div> </form> </body> </html> and here is the save code: <?php error_reporting(0); date_default_timezone_set("Asia/Singapore"); //set the time zone $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); $sr_date = $_POST['sr_date']; $sr_number = $_POST['sr_number']; $Items1 = $_POST['Items1']; $SubItems = $_POST['SubItems']; $ItemCode = $_POST['ItemCode']; $DemandedQty = $_POST['DemandedQty']; $UoM = $_POST['UoM']; $Class = $_POST['Class']; $Description = $_POST['Description']; $BINLocation = $_POST['BINLocation']; $RequestedBy = $_POST['RequestedBy']; $ApprovedBy = $_POST['ApprovedBy']; $ReceivedBy = $_POST['ReceivedBy']; $IssuedBy = $_POST['IssuedBy']; $Items = $_POST['Items']; for($i = 0; $i < count($Items1); $i++) { if ( $DemandedQty != "" ) { $sql = "INSERT INTO stock_requisition (sr_date, sr_number, Items, SubItems, ItemCode, DemandedQty, UoM, Class, Description, BINLocation, RequestedBy, ApprovedBy, ReceivedBy, IssuedBy) VALUES ('$sr_date', '$sr_number', '$Items1[$i]', '$SubItems[$i]', '$ItemCode[$i]', '$DemandedQty', '$UoM[$i]', '$Class[$i]', '$Description[$i]', '$BINLocation[$i]', '$RequestedBy', '$ApprovedBy', '$ReceivedBy', '$IssuedBy') "; $result = mysql_query($sql, $con); } } ?> I attach my sample form and the data save in database. Thank you so much Is it possible to use for loop to insert values into database using for loop? Or what would be the another way to insert these values into the database if the number of values being entered differs from one time to another? Here is basically what I am trying to do: mysql_query("INSERT INTO MaxMillionsNum SET Day='$weekday', DrawDate='$CompleteDate', DateTime='$timestamp', for($i=1; $i<=$SetNumber; $i+=1){ for($j=0; $j<7; j+=1){ $NumberName="Number".$i.$v[$j];//Generating name of database field $$NumberName=$Match[0][$j];//Here I would store the $Match value into the fieldname name created above } } Tries='$RunCounter'"); Hi.. I just want to know how can I save to another table all data that I display using while loop. Now I encountered only one row was save. Code: [Select] <?php error_reporting(0); date_default_timezone_set("Asia/Singapore"); //set the time zone $con = mysql_connect('localhost', 'root',''); if (!$con) { echo 'failed'; die(); } mysql_select_db("mes", $con); $sr_date =date('Y-m-d H:i:s'); $sr_date = $_GET['sr_date']; $sr_number = $_GET['sr_number']; $Items = $_GET['Items']; $SubItems = $_GET['SubItems']; $ItemCode = $_GET['ItemCode']; $DemandedQty = $_GET['DemandedQty']; $UoM = $_GET['UoM']; $Class = $_GET['Class']; $Description = $_GET['Description']; $BINLocation = $_GET['BINLocation']; $RequestedBy = $_GET['RequestedBy']; $ApprovedBy = $_GET['ApprovedBy']; $ReceivedBy = $_GET['ReceivedBy']; $IssuedBy = $_GET['IssuedBy']; $sql = "SELECT sr_number FROM stock_requisition ORDER BY sr_date DESC LIMIT 1"; $result = mysql_query($sql, $con); if (!$result) { echo 'failed'; die(); } $total = mysql_num_rows($result); if ($total <= 0) { $currentSRNum = 1; } else { $row = mysql_fetch_assoc($result); $currentSRNum = (int)(substr($row['sr_number'],0,3)); $currentSRYear = (int)(substr($row['sr_number'],2,2)); $currentSRMonth = (int)(substr($row['sr_number'],0,2)); $currentSRNum = (int)(substr($row['sr_number'],6,4)); $currentYear = (int)(date('y')); $currentMonth = (int)(date('m')); $currentDay = (int)(date('d')); $currentSRYMD = substr($row['sr_number'], 0, 6); $currentYMD = date("ymd"); if ($currentYMD > $currentSRYMD) { $currentSRNum = 1; } else { $currentSRNum += 1; } } //------------------------------------------------------------------------------------------------------------------ $yearMonth = date('ymd'); $currentSR = $currentYMD . sprintf("%04d", $currentSRNum); ?> <html> <title>Stock Requisition</title> <head> <script type="text/javascript"> function save_sr(){ var sr_date = document.getElementById("sr_date").value; var sr_number = document.getElementById("sr_number").value; var Items1 = document.getElementById("Items1").value; var SubItems = document.getElementById("SubItems").value; var ItemCode = document.getElementById("ItemCode").value; var DemandedQty = document.getElementById("DemandedQty").value; var UoM = document.getElementById("UoM").value; var Class = document.getElementById("Class").value; var Description = document.getElementById("Description").value; var BINLocation = document.getElementById("BINLocation").value; var RequestedBy = document.getElementById("RequestedBy").value; var ApprovedBy = document.getElementById("ApprovedBy").value; var ReceivedBy = document.getElementById("ReceivedBy").value; var IssuedBy = document.getElementById("IssuedBy").value; document.stock_requisition.action="StockRequisitionSave.php?sr_date="+sr_date+"&sr_number="+sr_number+"&Items1="+Items1+ "&SubItems="+SubItems+"&ItemCode="+ItemCode+"&DemandedQty="+DemandedQty+"&UoM="+UoM+"&Class="+Class+"&Description="+ Description+"&BINLocation="+BINLocation+"&RequestedBy="+RequestedBy+"&ApprovedBy="+ApprovedBy+"&ReceivedBy="+ReceivedBy+ "&IssuedBy="+IssuedBy; document.stock_requisition.submit(); alert("Stock Requisition data save."); window.location = "StockRequisition.php"; } </script> </head> <body> <form name="stock_requisition" action="<?php echo $_SERVER['PHP_SELF']; ?>" > <div id="ddcolortabs"> <ul> <li> <a href="ParameterSettings.php" title="Parameter Settings"><span>Parameter Settings</span></a></li> <li style="margin-left: 1px"><a href="kanban_report.php" title="WIP Report"><span>Wip Report</span></a></li> <li id="current"><a href="StockRequisition.php" title="WMS RM"><span>WMS RM</span></a></li> </ul> </div> <div id="ddcolortabs1"> <ul> <li><a href="ReceivingMaterials.php" title="Receiving Materials"><span>Receiving Materials</span></a></li> <li><a href="Shelving.php" title="Shelving"><span>Shelving</span></a></li> <li id="current"><a href="StockRequisition.php" title="Stock Requisition"><span>Stock Requisition</span></a></li> </ul> </div> <div id="SR_date"> <label>Date :</label> <input type="text" name="sr_date" value="<?php echo $sr_date; ?>" size="16" readonly="readonly" style="border: none;"> </div> <div id="SR_number"> <label>SR# :</label> <input type="text" name="sr_number" value="<?php echo $currentSR; ?>" size="10" readonly="readonly" style="font-weight: bold; border: none;"> <br/> </div> <div> <table> <thead> <th>Items</th> <th>Sub Items</th> <th>Item Code</th> <th>Demanded Qty</th> <th>UoM</th> <th>Class</th> <th>Description</th> <th>BIN Location</th> </thead> <?php $sql = "SELECT DISTINCT Items FROM bom_subitems ORDER BY Items"; $res_bom = mysql_query($sql, $con); while($row = mysql_fetch_assoc($res_bom)){ $Items = $row['Items']; echo "<tr> <td style='border: none;font-weight: bold;'> <input type='name' value='$row[Items]' name='Items' id='Items' readonly = 'readonly' style = 'border:none;width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='5'></td> </tr>"; $sql = "SELECT Items, SubItems, ItemCode, UoM, Class, Description, BINLocation FROM bom_subitems WHERE Items = '$row[Items]' ORDER BY Items"or die(mysql_error()); $res_sub = mysql_query($sql, $con); while($row_sub = mysql_fetch_array($res_sub)){ $Items1 = $row_sub['Items']; $SubItems = $row_sub['SubItems']; $ItemCode = $row_sub['ItemCode']; $UoM = $row_sub['UoM']; $Class = $row_sub['Class']; $Description = $row_sub['Description']; $BINLocation = $row_sub['BINLocation']; echo "<tr> <td style='border: none;'> <input type='hidden' value='$Items1' id='Items1' name='Items1[]'></td> <!--<td style='border: none;'> <input type='hidden' value='$cast[$i]['id']' id='Items1' name='Items1[]'></td> --> <td style='border: none;'> <input type='text' name='SubItems[]' value='$SubItems' id='SubItems' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='10'></td> <td style='border: none;'> <input type='text' name='ItemCode[]' value='$ItemCode' id='ItemCode' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='10'></td> <td style='border: none;'><center><input type='text' name='DemandedQty' id='DemandedQty' value='' size='7'></center></td> <td style='border: none;' size='3'> <input type='text' name='UoM[]' value='$UoM' id='UoM' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='3'></td> <td style='border: none;'> <input type='text' name='Class[]' value='$Class' id='Class' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='10'></td> <td style='border: none;'> <input type='text' name='Description[]' value='$Description' id='Description' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='10'></td> <td style='border: none;'> <input type='text' name='BINLocation[]' value='$BINLocation' id='BINLocation' readonly='readonly' style='border:none; width:auto;font-family: Arial, Helvetica, sans-serif;font-size: 1em;' size='10'></td> </tr>"; } $sql = "INSERT INTO stock_requisition (sr_date, sr_number, Items, SubItems, ItemCode, DemandedQty, UoM, Class, Description, BINLocation, RequestedBy, ApprovedBy, ReceivedBy, IssuedBy) VALUES ('$sr_date', '$sr_number', '$Items1', '$SubItems', '$ItemCode', '$DemandedQty', '$UoM', '$Class', '$Description', '$BINLocation', '$RequestedBy', '$ApprovedBy', '$ReceivedBy', '$IssuedBy') ON DUPLICATE KEY UPDATE sr_date = '$sr_date', sr_number = '$sr_number', Items = '$Items1', SubItems = '$SubItems', ItemCode = '$ItemCode', DemandedQty = '$DemandedQty', UoM = '$UoM', Class = '$Class', Description = '$Description', BINLocation = '$BINLocation', RequestedBy = '$RequestedBy', ApprovedBy = '$ApprovedBy', ReceivedBy = '$ReceivedBy', IssuedBy = '$IssuedBy'"; $result = mysql_query($sql, $con); } ?> </table> </div> <div id='RequestedBy'> <label>Requested By:</label> <select name="Requested_By"> <option name='None'>Select</option> <option name='AAAAAAAAA'>AAAAAAAAA</option> <option name='BBBBBBBBB'>BBBBBBBBB</option> <option name='CCCCCCCCCC'>CCCCCCCCCC</option> </select> </div> <div id='ApprovedBy'> <label>Approved By:</label> <select name="Approved_By"> <option name='None'>Select</option> <option name='AAAAAAAAA'>AAAAAAAAA</option> <option name='BBBBBBBBB'>BBBBBBBBB</option> <option name='CCCCCCCCCC'>CCCCCCCCCC</option> </select> </div> <div id='ReceivedBy'> <label>Received By:</label> <select name="Received_By"> <option name='None'>Select</option> <option name='AAAAAAAAA'>AAAAAAAAA</option> <option name='BBBBBBBB'>BBBBBBBB</option> <option name='CCCCCCCC'>CCCCCCCC</option> </select> </div> <div id='IssuedBy'> <label>Issued By:</label> <select name="Issued BY"> <option name='None'>Select</option> <option name='AAAAAAAAA'>AAAAAAAAA</option> <option name='BBBBBBBB'>BBBBBBBB</option> <option name='CCCCCCCC'>CCCCCCCC</option> </select> </div> <div id="save_btn"> <input type="button" name="button" value="save" onclick="save_sr()"> </div> </body> </html> I attach the sample form and output. Sorry if I repost my previous thread. I hope somebody can help me. Thank you Hello everyone, Let's say I am connecting to a database using PDO (I am excluding prepared statements for the sake of simplicity): try { $conn = new PDO('mysql:host=localhost;dbname=cms', 'root', 'password'); $result = $conn->query('SELECT * FROM news'); } catch (PDOException $e) { echo 'Error: '.$e->getMessage(); exit; } So far I been using the following to manipulate the data in object form: while ($row = $result->fetchObject()) { echo $row->title; echo $row->text; } My question is, is there a better way? What is the foreach code equivalent to that? I have had no luck keeping the data in object form using foreach statements. Which method is faster, while or foreach? Thank you, any suggestions are highly appreciated. Hello everyone, I am trying to convert dates directly from the database but still keep it within the same array so that I can conveniently access it later on. I am not sure how to explain this better, but I believe the code is pretty self explanatory: $stmt = $this->db->query("SELECT title,slug,content,author_id,created FROM article"); $stmt->setFetchMode(PDO::FETCH_ASSOC); $i = 0; while($var = $stmt->fetch()) { $this->data[] = $var; $this->data[$i]['date'] = date("F j, Y", strtotime($var['created'])); $i++; } print_r($this->data); /* produced array Array ( [0] => Array ( [title] => PHP Security Book [slug] => php-security-book [content] => Lorem ipsum dolor sit amet, consectetur adipisicing elit. [author_id] => 3 [created] => 2012-03-13 12:34:42 [date] => March 13, 2012 ) [1] => Array ( [title] => Something To Do [slug] => somthing-to-do [content] => You know what a dolor sit amet, consectetur adipisicing elit. [author_id] => 3 [created] => 2012-03-13 12:35:46 [date] => March 13, 2012 ) ) */ I access it like so: foreach ($_data as $var) { echo '<h2>' . $var['title'] . '</h2> <br />'; echo '<b>' . $var['date'] . '</b> <br />'; echo '<p>' . $var['content'] . '</p> <br />'; } It works perfectly but my question is: Is there a better or more efficient way to do this? I think that my while loop could use some improvement. I was also thinking of maybe fetching the results into a class using PDO::FETCH_CLASS, but it seems like a bit of a hassle for just one modification. 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')"); } I can get the info from the database fine with this: Code: [Select] $sql2 = "SELECT 1, 2, 3, 4, 5, 6 FROM ratestable ORDER BY id ASC"; $stmt2 = $db->prepare($sql2); $stmt2->execute(); $e2 = $stmt->fetch(); and display it with this: Code: [Select] <?php while($e2 = $stmt2->fetch()) { ?> <input type="text" name="1" maxlength="10" value="<?php echo $e2['1'] ?>" class="rates" /> <input type="text" name="2" maxlength="10" value="<?php echo $e2['2'] ?>" class="rates" /> <input type="text" name="3" maxlength="10" value="<?php echo $e2['3'] ?>" class="rates" /> <input type="text" name="4" maxlength="10" value="<?php echo $e2['4'] ?>" class="rates" /> <input type="text" name="5" maxlength="10" value="<?php echo $e2['5'] ?>" class="rates" /> <input type="text" name="6" maxlength="10" value="<?php echo $e2['6'] ?>" class="rates" /> <?php } ?> How do I update it to the database? Code: [Select] $sql = "UPDATE rates SET title1=?, title2=?, title3=?, title4=?, title5=?, title6=? THE CODE HERE IS WHERE I AM STUCK.... and that's as far as I can get, need to use an array or foreach??????? [/quote] hi every body.
i want a loop that takes and shows more than one record from database.
and then i want to show these to user by ajax.
indeed i made an html page that when user arrives at end it must do this.
first i made loop that took one record from database and it worked fine.
but for taking several records it went wrong.
this is my html file that has interact by user
webgoo-ajax.html 4.36KB
2 downloads
and this is my php file that interacts by database
ajax-get.php 1012bytes
3 downloads
when user arrives at end of page naturally ajax must be run and show several records to user.but it does'nt.
first it stays idle for 3 minutes and then loads my first record extremely.
and a point: if these pages does'nt work on IE it will work on Firefox because it did'nt worked in IE for me too.
i just want a for loop that work correctly for my need.
thank you for everything
Hi all, The below example is a workable code, taken from tutor_profile.sql table Code: [Select] <?php $query = "SELECT tutor_id, religion_id FROM tutor_profile WHERE tutor_id = '" . $_GET['tutor_id'] . "'"; $data = mysqli_query($dbc, $query) or die(mysqli_error($dbc)); // The user row was found so display the user data if (mysqli_num_rows($data) == 1) { $row = mysqli_fetch_array($data); print_r($row); if ($row != NULL) { $religion_id = $row['religion_id']; $tutor_id = $row['tutor_id']; } else { echo '<p class="error">There was a problem accessing your profile.</p>'; } } <!--Religion--> <tr> <td class="label">Religion:</td> <td> <select id="religion_id" name="religion_id"> <option value="1" <?php if (!empty($religion_id) && $religion_id == '1') echo 'selected = "selected"'; ?>>Buddhism</option> <option value="2" <?php if (!empty($religion_id) && $religion_id == '2') echo 'selected = "selected"'; ?>>Christianity</option> <option value="3" <?php if (!empty($religion_id) && $religion_id == '3') echo 'selected = "selected"'; ?>>Hinduism</option> <option value="4" <?php if (!empty($religion_id) && $religion_id == '4') echo 'selected = "selected"'; ?>>Islam</option> <option value="5" <?php if (!empty($religion_id) && $religion_id == '5') echo 'selected = "selected"'; ?>>Taoism</option> <option value="6" <?php if (!empty($religion_id) && $religion_id == '6') echo 'selected = "selected"'; ?>>Others</option> </select> </td> </tr> ?> As you can see I have hard coded the names of the religion in html code example - <option value="3" <?php if (!empty($religion_id) && $religion_id == '3') echoselected = "selected"'; ?>>Hinduism</option> And if our record shows that the tutor has previously selected '3', it will reflect as 'hinduism' in his profile. View profile.jpg for example example - <option value="3" <?php if (!empty($religion_id) && $religion_id == '3') echo 'selected = "selected"'; ?>>Hinduism</option> In fact, these names can be found in another table called religion.sql, but I hard coded it anyway, without using loop (while function), since there are only 8 names Code: [Select] <!--Religion--> <tr> <td class="label">Religion:</td> <td> <select id="religion_id" name="religion_id"> <option value="1" <?php if (!empty($religion_id) && $religion_id == '1') echo 'selected = "selected"'; ?>>Buddhism</option> <option value="2" <?php if (!empty($religion_id) && $religion_id == '2') echo 'selected = "selected"'; ?>>Christianity</option> <option value="3" <?php if (!empty($religion_id) && $religion_id == '3') echo 'selected = "selected"'; ?>>Hinduism</option> <option value="4" <?php if (!empty($religion_id) && $religion_id == '4') echo 'selected = "selected"'; ?>>Islam</option> <option value="5" <?php if (!empty($religion_id) && $religion_id == '5') echo 'selected = "selected"'; ?>>Taoism</option> <option value="6" <?php if (!empty($religion_id) && $religion_id == '6') echo 'selected = "selected"'; ?>>Others</option> </select> </td> </tr> Currently I am facing an issue, I guess I will need to use looping, as there are 22 names in another table which I will need to call forth, tutor_educational_level.sql, and the number of names get more and more in other tables. My question is, how do I pull out the entire list of names into a drop down box and yet showing the selected name which the user has chosen, more elaboration can be seen in profile.jpg. In profile.jpg - as you can see the list of names are shown in the drop down box and the system is able to decipher the chosen name. Another Example 1) N level 2) O level 3) A level 4) University User selected '3', which is A level, and system would still show the list of educational_names in a drop down box,, but selecting A level as the one to appear. Example 1) N level 2) O level 3) A level (selected) 4) University It should have the same overall result as the religion which I have stated above, however this time round, it is using looping function (while) to retrieve the entire list of names, select and show the name which the user has chosen Below is my code, and I know it is wrong, but generally would like to relate my idea across. Code: [Select] <?php <!--Teaching Credentials--> <tr> <td class="label">Teaching Credentials:</td> <td> <?php echo '<select name="educational_level" id="educational_level">'; $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die(mysqli_error($dbc)); $query = "SELECT tp.educational_id, el.educational_name AS educational_name, el.educational_id AS list_educational_id " . "FROM tutor_profile AS tp " . "INNER JOIN * tutor_educational_level AS el USING (educational_id) " . "WHERE tp.tutor_id = '" . $_GET['tutor_id'] . "'"; $sql = mysqli_query($dbc, $query) or die(mysqli_error()); while($data = mysqli_fetch_array($sql)) { echo'<option value="'.$data['list_educational_id'].'">'.$data['educational_name'].'</option>'; if (!empty ($data['educational_id']) && ($data['educational_id']) == ($data['list_educational_id'])) { echo 'selected = "selected"'; } } echo '</select><br/>'; mysqli_close($dbc); ?> </td> </tr> ?> Hi friends. I want to php code on how i can modify my retrieved database values from a particular table before echoing out. Please could you help me correct the code. Or if there is any better way of editing loop datas before printing out, please kindly drop the code for me. Thanks <?php please if there is any better way of editing loop values from mysql database before printing out, please kindly drop the code for me. Thanks So i have an event page where it will show the next 3 events, then i need logged in users to click either of two buttons to say there attending or not attending. i have the below code showing events, and the <form> and the submit and both buttons, but if i submit 1 button on event ID: 1 it inserts data into the database but for event ID: 2, and if i click the button on event ID :2 it also puts it into database with eventid:2 so no matter which event i click it seems to submit data with the latest event ID shown on page, and not for "each" event seperatly. i have moved the submit query everywhere around and still same results or duplicate results if its in the loop. i assume its looping the submit and only submitting the latests event ID.
<?php if ($result = $con->query("SELECT * FROM events ORDER BY id ASC LIMIT 3")) { if ($result->num_rows > 0) { while ($row = $result->fetch_object()) { $event_id = $row->id; // set up table and echo data! echo "<table border='1' cellpadding='2' width='50%'>"; echo "<tr><td>"; echo "<p><img src='images/raid_banners/" . $row->bannerimg . "'>" . $row->name . " (iLvl: " . $row->itemlevel . ")</p>"; echo "<p>Event Starts: " . $row->datestart . " - " . $row->timestart . "</p>"; echo "<p>Event Ends: " . $row->dateend . " - " . $row->timeend . "</p>"; echo "<p>Raid Lead: " . $row->raidlead . "</p>"; echo "<form action='' name='$event_id' method='post'>"; // Process and populate SELECT form element echo "<select name=\"charname\">"; $sql = mysqli_query($con, "SELECT * FROM characters WHERE userid = $userid"); while ($row = $sql->fetch_assoc()){ echo "<option value=\"{$row['id']}\">{$row['charname']}</option>"; } echo "</select>"; echo "<input type='hidden' name='raidid' value ='$event_id'>"; echo "<input type='hidden' name='action' value='submit' />"; echo "<input type=\"submit\" name=\"submit\" value=\"going\">"; echo "<input type=\"submit\" name=\"submit\" value=\"notgoing\">"; echo "</form></td></tr></table><br><br>"; } if(isset($_POST['action'])){ $charid = $_POST['charname']; $submit = $_POST['submit']; // Submit the data from dropdown in the form mysqli_query($con,"INSERT INTO eventsignup (eventid, charid, userid, status) VALUES ('$event_id', '$charid', '$userid', '$submit')"); } } else { echo "No results to display!"; } } else { echo "Error: " . $con->error; } $con->close(); ?> any help would be awesome. im tearing my hair out here. Throughout the application I'm building, I include a db.php file which has the information about the local database so that I can use it wherever I do a database call. However, I am now using a second database located on a remote server in order to fetch additional information not stored on the local database, inside a while loop. This fail miserably and I have tested many things and need a bit of guidance. Code simplified: Code: [Select] function grab_expiration_date ($number) { $remote_link = mysql_connect('remote_host', 'user', 'pass'); $remote_connect = mysql_select_db('remote_db', $remote_link); $query = "SELECT ExpirationDate FROM remote_table WHERE Number='$number'"; $result = mysql_query($query, $remote_link); $num_rows = mysql_num_rows($result); if ($num_rows == 1) { $r = mysql_fetch_assoc($result); $expire_date = $r['ExpirationDate']; mysql_close($remote_link); return $expire_date; } else { return false; } } $query = "SELECT Number FROM local_table; $result = mysql_query($query, $local_link); while ($r = mysql_fetch_assoc($result)) { $number = $r['Number']; $expire_date = fetch_expiration_date($number); if ($expire_date) { $query2 = UPDATE local_table SET ExpirationDate='$expire_date' WHERE Number='$number'"; $result2 = mysql_query($query2, $link); if (!$result2) { echo 'Could not update the Expiration Number because: ' . mysql_error(); exit(); } } else { echo 'Nothing found, or dublicates'; } } The attempt of update the local table fails, and mysql_error() does not even return anything, stating what's wrong. In the past, I fetched this information from a website using CURL, but since I now have access to the database, hitting the database is by far faster. Any help would be much appreciated. Using a for loop counting from 0 to 9, I need to make this into a table. Making sure the table is 100% of the page. Any sort of help is appreciated. Thank you 0 1 2 3 4 5 6 7 8 9 Hi, When I use the below table in a while loop, it will repeat down the page. I want it to repeat in rows of 3, how can I do this? Code: [Select] while () { echo ' <table width="50%" cellpadding="2" cellspacing="1" bgcolor="'.$border.'"> <tr > <td colspan="5" height="20" align="center" class="title" bgcolor="'.$bghead.'"><b>'.$pt['platform'].'</b></td> </tr> </table>'; } Thanks! Hey guys, I am using php loop to echo out all off the data in my database category within a html table. However I would like to reduce each table row to only 5 results then start a new row so that the table fits within the webpage. Any suggestions? Any help is much appreciated. Thanks. Jason Here is what i am using, but does not fit within the page. Code: [Select] <table cellspacing="10"> <tr> <?php $query = mysql_query('SELECT photo_id, photo_name FROM gallery_photos WHERE photo_category = "Books" AND photo_approved = 1 ORDER BY rand()'); while ($row = mysql_fetch_array($query)) { echo "<td><a href='http://www.mysite.com/view.php?pid=".$row['photo_id']."'><img src='photos/".$row['photo_id'].".jpg' width='115' height='115' /><center><h3><b>".$row['photo_name']."</b></h3></center></a></td>"; } ?> </tr> </table> I am trying to place a unique number into a mysql table. Currently, my code generates a random number, then is supposed to scan through the table for that number. If the code finds that number already in the table, it generates a new random number and repeats the process. I have commented my code for the purpose of this help forum: Code: [Select] $result = mysqli_query($link,"SELECT * FROM testTable"); do { $end = true; //prepares end of loop $idNum = rand(1,10); //rand(1,999999); <-- for testing purposes I have reduced the number generated $idNumTx = (string)$idNum; //loop through the rows while ($row = mysqli_fetch_assoc($result)) { if ($row['idNum'] = $idNum) //check if the random number equal to this row { $end = false; //prep end of loop repeat echo $idNumTx; //display rand number that failed for testing purposes echo " NO! "; //display error for testing purposes } } } while(!$end); I know I must be doing something wrong, as when I run this, it runs the if statement within the while loop always executes, and I get an output like: Code: [Select] 1 NO! 1 NO! 1 NO! 1 NO! 1 NO! 1 NO! 5 Win Win is when it places the value before it, in this case 5, into the table. However, the value of 5 might already be in the table and it doesn't seem to matter. I execute the code multiple times, and it seems to increase the number of "# NO!" almost (but not every) time. However, each time ALL of the "# NO!" are the same #, and the "# Win" just seems to be random (as it should be, but not unique). Checking the table after shows me random numbers between 1 and 10 (as it should) in the correct field, but the are not unique. (Ex/ Both row 1 and 5 could have the same value, say 6) I'm hopefully doing something simple wrong, so someone please point it out to me |