PHP - Adding A Count And While Loop Using Xml Data
Hi I have currently written some code which uses of the Twitter API and extracts the information required to display my most current tweet on my website. This is all working perfectly but at the minute it is only displaying one tweet and I would like it to display as many as the variable $limit is set to.
I have tried numerous count with while loops but just cannot seem to get my head around the logic of it. Here is the code im currently using which displays one tweet. <?php $username = "my_twitter_username"; $limit = "2"; $twitter_url = "http://twitter.com/statuses/user_timeline/$username.xml?count=$limit"; $buffer = file_get_contents($twitter_url); $xml = new SimpleXMLElement($buffer); $status_item = $xml -> status; $status_id = $xml -> status -> id; $user_item = $xml -> status -> user; $user_id = $xml -> status -> user -> screen_name; $description = $status_item -> text; $status_time = $status_item -> created_at; $status_img = $user_item -> profile_image_url; $description = preg_replace("#(^|[\n ])([\w]+?://[\w]+[^ \"\n\r\t< ]*)#", "\\1<a href=\"\\2\" target=\"_blank\">\\2</a>", $description); $description = preg_replace("#(^|[\n ])((www|ftp)\.[^ \"\t\n\r< ]*)#", "\\1<a href=\"http://\\2\" target=\"_blank\">\\2</a>", $description); $description = preg_replace("/@(\w+)/", "<a href=\"http://www.twitter.com/\\1\" target=\"_blank\">@\\1</a>", $description); $description = preg_replace("/#(\w+)/", "<a href=\"http://search.twitter.com/search?q=%23\\1\" target=\"_blank\">#\\1</a>", $description); echo " <div class='tweet-wrapper'> <div class='tweet-img'> <a href='http://www.twitter.com/la__academia' target='_BLANK'><img src='$status_img' alt='La Academia Twitter' style='width:30px height:30px;' /></a> </div><!-- tweet-img --> <div class='tweet-text'> <p class='tweet-p'>$description</p> <p class='tweet-time'>$status_time . <a href='http://twitter.com/?status=@$user_id%20&in_reply_to_status_id=$status_id&in_reply_to=$user_id' target='_BLANK' class='tweet-reply'>Reply</a></p> </div><!-- tweet-text --> <div class='cleaner'></div> </div><!-- tweet-wrapper --> "; ?> Thanks for any help. Similar TutorialsSo 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. I have this SQL query that gathers set information for the Salesperson($user) that is logged in and viewing theri need information. Everything works weell, except my Loop Count. I don't know, what I am doping incorrectly. It returns only two values which are the same. But the Query returns 10 values for that user. When I run the query direct in SQL DB. What am I missing? Code: [Select] <div class='page_content clearfix'> <div class='grid_8 first'> <?php $salesPersonId = & JFactory::getUser()->get('username'); //$merchantId = JFactory::getSession()->get('merchantId'); $db =& JFactory::getDBO(); $query = " SELECT XXX_merchant.*, XXX_merchant.name as MercName, XXX_merchant.address as MercAddress FROM XXX_sales_person, jXXX_merchant WHERE XXX_sales_person.user_name = '$salesPersonId' AND XXX_merchant.sales_person_id = XXX_sales_person.id"; $db->setQuery( $query ); $row = $db->loadObject(); //echo $query; //echo $query; //echo '<br>'; //echo $salesPerson->name; ?> <?php $link = 'index.php?option=XXX&controller=deal&task=view&id=' . $row->id; $count = 0; foreach ( $row as $row): $link = '/index.php?option=XXX&controller=merchant&task=edit&cid[]=' . $row->id; ?> <div class='quickie_login grid_9 last' style="width: 140px"> <div class='text_center' id='login_banner'> <div class='page_content text_center'> <div class="avatar" style="float: left; margin-top: -10px; padding: 0px;"> <a class="k2Avatar ubAvatar" href="<?php echo $link; ?>" title="<?php echo JText::_($row->MercName); ?> Edit Account" target="_blank"> <span class="ubName" style="display: block; margin-top: -20px;"><b><?php echo $row->MercName; ?></b> </span> <?php if(!empty($row->logo_url)) { $imagePathArr = unserialize(urldecode($row->logo_url)); $link='http://'; $link.= $_SERVER["SERVER_NAME"].$link_server.DS; $link.=$imagePathArr[0]; $link =str_replace("\\","/",$link); ?> <img src='<?php echo $link; ?>' alt="<?php echo $row->name; ?>" style="max-width: 100px; height:100px;"/> <?php } ?> </a> </div> <div class="sales-system2"> <div style="display: block; margin-top: 0px;"> </div> </div> </div> </div> <?php endforeach;?> Hi all I have a string in an include file for a javascript lightbox value. I need this value to increase by one every time it loops. Here's my code: $fetchproducts = mysql_query(" SELECT * FROM `products` "); while($returnedProduct = mysql_fetch_array($fetchproducts)) { include('product-cell.php'); } The string is called $lightboxcount in the product-cell.php file Can I fit a ++ into the code above? Many thanks for your help Pete Hello all, I've built a database of coupons. Each coupon is assigned to a category (so all electronics coupons display under electronics). On my category list I'd like to display how many coupons is in each category. Currently this function displays my category list: function fetch_categories() { mysql_connect(SQL_HOST_NAME, SQL_USER_NAME, SQL_PASSWORD) or die(mysql_error()); mysql_select_db(SQL_DATABASE) or die(mysql_error()); $result = mysql_query("SELECT * FROM categories ORDER BY category_name")or die(mysql_error()); echo '<div id="category_list">'; echo '<ul class="cat_list">'; while($row=mysql_fetch_assoc($result)){ //get total of discounts in each category $count_result = mysql_query("SELECT * FROM category_relations, discounts WHERE category_relations.member_of = '$row[id]' AND discounts.active = '1'")or die(mysql_error()); $num_rows = mysql_num_rows($count_result); echo '<span class="numrows">('.$num_rows.')</span>'; echo '<li><a href="index.php?cat_ID='.$row['id'].'">'.$row['category_name'].' </a></li>'; } echo '</ul>'; echo '</div>'; } The above is a debug version so it's not all formatted correctly. However right now, that exports "3" for Airlines when right now, I have only one discount in the entire database. This is my category_relations table: Code: [Select] -- -- Table structure for table `category_relations` -- CREATE TABLE IF NOT EXISTS `category_relations` ( `id` int(10) NOT NULL, `member_of` int(10) unsigned NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; -- -- Dumping data for table `category_relations` -- INSERT INTO `category_relations` (`id`, `member_of`) VALUES (2, 2), (1, 1), (3, 1), (4, 1); And this is my discounts table: Code: [Select] -- -- Table structure for table `discounts` -- CREATE TABLE IF NOT EXISTS `discounts` ( `id` smallint(5) NOT NULL AUTO_INCREMENT, `redeem` tinyint(3) NOT NULL, `discount_title` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `short_description` tinytext CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `eligibility` blob NOT NULL, `url` varchar(100) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `coupon_code` varchar(75) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `start_date` datetime DEFAULT NULL, `end_date` datetime DEFAULT NULL, `long_description` text CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `logo` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `business_name` varchar(75) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `phone` varchar(80) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `store_location_street` varchar(75) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `store_location_city` varchar(75) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `store_location_state` char(2) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `store_location_zip` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, `categories` blob NOT NULL, `level` tinyint(5) NOT NULL, `active` tinyint(1) NOT NULL, `user_id` varchar(2555) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`), KEY `level` (`level`,`active`), KEY `user_id` (`user_id`(333)) ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ; -- -- Dumping data for table `discounts` -- INSERT INTO `discounts` (`id`, `redeem`, `discount_title`, `short_description`, `eligibility`, `url`, `coupon_code`, `start_date`, `end_date`, `long_description`, `logo`, `business_name`, `phone`, `store_location_street`, `store_location_city`, `store_location_state`, `store_location_zip`, `categories`, `level`, `active`, `user_id`) VALUES (1, 0, '$2.00 Off Transportation', '', 0x4172726179, 'www.baysideshuttle.com', '', '2010-01-01 00:00:00', '2011-01-01 00:00:00', 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer varius ipsum id justo pellentesque laoreet. Curabitur tempus tincidunt...', NULL, 'Bayside Airport Shuttle', '850-123-3456', NULL, NULL, NULL, NULL, 0x4172726179, 0, 1, '24'); It seems to be completely ignoring my active check. How can I fix this, or is there a better way to do this query? Basically, this part of the code is checking the "scanned" table in my mysql database to get the last scanned date for the item at hand. It then takes that date and selects all the vendor items in the odbc table "ARVEND" that are greater than the last purchase date. || This is where I am running into a problem. When it loops through each vendor item it selects from the "associated" mysql table to see if the vendor item has been scanned. If it does not find anything I am trying to get the $checkpurdate variable to add 1 to itself. | In the second script you will see the elseif($checkpurdate>0) .... Here I am saying if there are any vendor items that have not been scanned, highlight the row in yellow. But, this part of my code $checkpurdate = $checkpurdate + 1; does not seem to be counting correctly. Sometimes it counts '4' for an item when there are only two vendor items available. All of this may sound confusing since you may not know what I am trying to do. But, the main problem I am having is the counting part is returning wrong numbers. $checkpurdate = $checkpurdate + 1; Code: [Select] /* $checkpurdate */ $query3 = "SELECT date FROM scanned WHERE `item` = '$ITEM' ORDER BY date DESC LIMIT 1"; $result3 = mysql_query($query3); $checklastdate = ""; while($row3 = mysql_fetch_array($result3, MYSQL_ASSOC)) {$checklastdate= $row3['date']; $checklastdate=date("m/d/y", strtotime($checklastdate)); } //checkpurdate loops $checkassoc="0"; $checkpurdate="0"; $sqlc="SELECT RECNO5 FROM ARVEND WHERE PURDATE1 > '$checklastdate' AND ITEM = '$ITEM'"; $rsc=odbc_exec($conn,$sqlc); if (!$rsc) {exit("Error in SQL");} while (odbc_fetch_row($rsc)) { $checkrecno5=odbc_result($rsc,"RECNO5"); $checkassosquery = "associated WHERE `VENDORID` = '$checkrecno5' AND ITEM = '$ITEM'"; $checkassoc = get_rows($checkassosquery); if($checkassoc>0) { // do nothing } else { $checkpurdate = $checkpurdate + 1; } } Code: [Select] elseif($checkpurdate>0) { echo"<TR class=\"NV\"> <TD>"; } first i will show example, table messages containes user id, message, read. now i want to get all the messages from user id 1 and see how many of them have read as true. How can i do this, i'm using MYSQL so really i need a count thing Hi.. Sorry, if I need to repost my problem in while loop. cause until now I can't resolve my problem in saving all data from while loop. I have this code StockRequisition.php where FORM was displayed. <?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 { //------------------------------------------------------------------------------------------------------------------ // Stock Number iteration.... $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; 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']; ?>" method="post"> <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><a href="fsn.php" title="Finished Stock Note"><span>WMS FG</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='$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 = '$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 style='border: none;'> <input type='hidden' value='$Items1' 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>"; } } ?> </table> </div> <?php $RequestedBy = array('AAA', 'BBB', 'CCC', 'DDD'); $ApprovedBy = array('EEE', 'FFF', 'GGG', 'HHH'); $ReceivedBy = array('III', 'JJJ', 'KKK', 'LLL'); $IssuedBy = array('MMM', 'NNN', 'OOO', 'PPP'); ?> <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> <option value="CCC" <?php if($_POST['RequestedBy'] == 'CCC') echo "selected='selected'"; ?>>CCC</option> <option value="DDD" <?php if($_POST['RequestedBy'] == 'DDD') echo "selected='selected'"; ?>>DDD</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> <option value="GGG" <?php if($_POST['ApprovedBy'] == 'GGG') echo "selected='selected'"; ?>>GGG</option> <option value="HHH" <?php if($_POST['ApprovedBy'] == 'HHH') echo "selected='selected'"; ?>>HHH</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> <option value="KKK" <?php if($_POST['ReceivedBy'] == 'KKK') echo "selected='selected'"; ?>>KKK</option> <option value="LLL" <?php if($_POST['ReceivedBy'] == 'LLL') echo "selected='selected'"; ?>>LLL</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> <option value="OOO" <?php if($_POST['IssuedBy'] == 'OOO') echo "selected='selected'"; ?>>OOO</option> <option value="PPP" <?php if($_POST['IssuedBy'] == 'PPP') echo "selected='selected'"; ?>>PPP</option> </select> </div> <div id="save_btn"> <input type="button" name="button" value="save" onClick="save_sr()"> </div> </form> </body> </html> and here is StockRequisitionSave.php code for saving data to database : <?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']; $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') "; $result = mysql_query($sql, $con); ?> the problem is only the last data was save. I will attach my form. I hope somebody can help me.. I really don't know how can I save all data from form into my database. Thank you so much for your understanding and help. I'm telling it to add 1 each time through the while loop but its not and not sure why. Code: [Select] <fieldset class="answerLeg"> <legend>Edit Poll Answers</legend> <?php $j = 0; while($row2 = mysqli_fetch_array ( $pollAnswersResult, MYSQL_ASSOC )) { ?> <div class="field required answers"> <label for="answer<?php echo ($j + 1)?>">Answer #<?php echo ($j + 1)?></label><input type="text" class="text" name="answer<?php echo ($j + 1)?>" id="answer<?php echo ($j + 1)?>" title="Answer <?php echo ($j + 1)?>" value="<?php echo $row2['answer']; ?>"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <?php } ?> </fieldset> hello, i have created a table that desplays perticulars, price per person and number of people. the fees is then calculated by multiplying price per person with number of people. till now everything is good. but the problem is when i try to calculate the total fees. here is an example to explain you better: Perticulars Price Per Person Number of people Amount something 10 100 1000 something else 20 100 2000 Total 3000 Code: [Select] $pert_query = mysql_query ("SELECT * FROM `perticulars` WHERE `invoice` =$invoice") or die(mysql_error()); $i = 1; $sum = 0 + $_SESSION['sum']; while($perticulars = mysql_fetch_array($pert_query, MYSQL_ASSOC)) { ?> <tr> <td style="border-collapse: collapse"><div align="center"><?php echo $i; $i++; ?></div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $perticulars['perticulars']; ?></div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $perticulars['ppc']; ?></div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $perticulars['nop']; ?></div></td> <td style="border-collapse: collapse"><div align="center"> <?php $amount = $perticulars['ppc'] * $perticulars['nop']; echo $amount; $_SESSION['sum'] = $sum+$amount;?> </div></td> </tr><?php } ?> <tr> <td colspan="4" style="border-collapse: collapse"><div align="center">Total</div></td> <td style="border-collapse: collapse"><div align="center"><?php echo $sum; ?></div></td> </tr> </table> From the above code you can see that i am getting the amount form $amount = $perticulars['ppc'] * $perticulars['nop']; by this each row has its own amount which i got by multiplying the data from mysql. the problem is how do i find out the Total. i know i am suppose to add up $amount but how? i even tired using sessions to store the amount and add the new amount to get total but the problem in using sessions is it messes up my next page, no using session is a very bad idea. Hey guys, I am trying to input data into a mysql database from data thats been added by a jquery form with cloned fields. It is working however it adds the first row correctly then a blank row and then the rest of the rows correctly The code is this $x=0; do { $fga=$_POST['ID'.$x.'fga']; $fgm=$_POST['ID'.$x.'fgm']; $fta=$_POST['ID'.$x.'fta']; $ftm=$_POST['ID'.$x.'ftm']; $tpa=$_POST['ID'.$x.'tpa']; $tpm=$_POST['ID'.$x.'tpm']; $fta=$_POST['ID'.$x.'fta']; $ftm=$_POST['ID'.$x.'ftm']; $stl=$_POST['ID'.$x.'stl']; $trb=$_POST['ID'.$x.'trb']; $ast=$_POST['ID'.$x.'ast']; $blka=$_POST['ID'.$x.'blka']; $blkf=$_POST['ID'.$x.'blkf']; $tovr=$_POST['ID'.$x.'tovr']; mysql_query("INSERT INTO stats (gameId, fga, fgm, tpa, tpm, fta, ftm, ast, stl, trb, blka, blkf, tovr) VALUES ('$gameId', '$fga', '$fgm', '$tpa', '$tpm', '$fta', '$ftm', '$ast', '$stl', '$trb', '$blka', '$blkf', '$tovr')")or die("<div class='errmsg'>Insert Error: ".mysql_error()."</div><br /> \n"); $x++; Can anyone see what ive done wrong? Thanks Hi, I have a database with some rows. in each row there is a number such as: 0.0023 or 0.0135... I have the following code to loop though them and add the numbers up but it always returns 0? Code: [Select] $sql="SELECT * FROM tickets WHERE `round` = '$round' AND `confirmed` = 'yes' ORDER BY id ASC"; $result=mysql_query($sql); $row=mysql_fetch_array($result); while($row = mysql_fetch_array( $result )) { $balance = $balance + $row['amount']; } Hello, I have a database that contains a column with a int value for number of slots reserved, and what I want to do is fetch the value of each column and add them together to create one whole number. For example, in my database under preserved I have two separate values of 2 and 4.. I would like to take those two values and add them up into 6 through php... here is what I have so far: $slots = mysql_query("SELECT * FROM treservations WHERE reservation_date='$reservation_date' AND reservation_hour='$reservation_hour'") or die(mysql_error()); while ($row = mysql_fetch_assoc($slots)) { $row["preserved"]; } mysql_free_result($slots); Any help would be GREATLY appreciated.. if I need to add additional code please let me know. Thank you! hi i have got the following issues i am using the following code. Code: [Select] <?php //DB CONNECTION $ROWS = "id,firstname,lastname"; // explode at the comma and insert into an array $test = explode("," , $ROWS); //adds array test to the var sam $sam = array($test); // querys the database $new = mysql_query("SELECT * FROM {$DB_TABLE}"); // while loop to loop through selected fields while ($row = mysql_fetch_array($new)) { foreach ($sam[0] as $v) { echo $row[$v] . $DELIMITER . "<br />"; } } ?> i get the following results. 834(|) Steph(|) Thompson(|) 835(|) Lucy(|) kim(|) 836(|) Iwan(|) Will(|) 837(|) Sarah (|) Good(|) The problem i have is the br tag where do i put it because i need it to output like this. like it shows in the $ROWS variable above "$ROWS = "id,firstname,lastname";"; 834(|)Step(|)Thompson(|) 835(|)Lucy(|)kim(|) 836(|)Iwan(|)Will(|) 837(|)Sarah (|)Good(|) Where do i add the br tag??? Any Help PLease mysql_query("update pupils set record='running' where pid !='$testing[0]' Hi all, I'm trying to write a function to return an array. But it keeps returning an empty array with NULL values .... This is my code. function ShowUserData ($uid) { $con = mysql_connect("localhost","user","pass"); if (!$con) { die('Oops !! something went wrong with the DB connection, Server said ' . mysql_error()); } mysql_select_db("db", $con); $password = md5($password); $query = mysql_query("SELECT * FROM `table` WHERE `uid` = '".$uid."'"); $num = mysql_num_rows($query); while ($row = mysql_fetch_array($query, MYSQL_NUM)) { $outArray = array('uid' =>$row['uid'], 'email' => $row['email'], 'name' => $row['name']); } return $outArray; } what am i doing wrong? I am trying to get info from a table, add rows in that table, and put the added value back into the table in another field...I want to add field1 and field2 of every row and put the total in the total row. Heres what the echo gives me Susan 14 Mary 18 Bob 13 Sam 21 heres the database mysql> SELECT total_val FROM table; +-----------+ | total_val | +-----------+ | 21 | | 21 | | 21 | | 21 | +-----------+ heres the code.... <?php require("connection.php"); mysql_select_db("database", $connection); echo "<br />"; $result = mysql_query("SELECT * FROM table"); while($row = mysql_fetch_array($result)) { $values = ($row['field1'] + $row['field2']); $sql=mysql_query("UPDATE table SET total = '$values'"); echo $row['user_name'] . " " . $values; echo "<br />"; } ?> also note that if I put a INT in place of $values - the echo changes to match...why?? PLEASE help...I have been working on this for 2 entire days.... Hope someone can help, I am trying to add up all the values of a variable in a PHP while loop and have tried several approaches but none seem to work. Hopefully someone can point out what the correct method is. I've set up some code to pull the pay rate from a MySQL table, and then calculate that person's earnings based on the amount of time they spend on a particular job. That works fine:
However there may be a number of jobs for different people with different rates, so I want to add all of these up and output the total. So for example if I had values of 125.00, 35.50 and 22.75 I want to show 183.25 as the total. So I tried a few things I found on forums on the subject:
That didn't work so I tried another method that someone suggested:
The 2nd method outputted just the last individual value, the 1st method didn't work at all. Does anyone have a working method that can be used to do this? Thanks Here is my dilemma and thank you in advance! I am trying to create a variable variable or something of the sort for a dynamic associative array and having a hell of a time figuring out how to do this. I am creating a file explorer so I am using the directories as the keys in the array. Example: I need to get this so I can assign it values $dir_list['root']['folder1']['folder2'] = value; so I was thinking of doing something along these lines... if ( $handle2 = @opendir( $theDir.'/'.$file )) { $tmp_dir_url = explode($theDir); for ( $k = 1; $k < sizeof ( $tmp_dir_url ); $k++ ) { $dir_list [ $dir_array [ sizeof ( $dir_array ) - 1 ] ][$tmp_dir_url[$k]] } this is where I get stuck, I need to dynamically append a new dimension to the array durring each iteration through the for loop...but i have NO CLUE how When a post is approved I only want $details = $_POST['newstitle']; update_user_actions(8, $details); Being posted once with the corresponding news article title. Any way to achieve this? Right now it is looping through all of the titles and is posting them all. Code: [Select] foreach($posts as $post) { $displayName = ucwords("${post['firstname']} ${post['lastname']}"); if (isset($_POST['approve'])) { if(is_array($_POST['approve'])) { $keys = array_keys($_POST['approve']); $id = $keys[0]; $details = $_POST['newstitle']; update_user_actions(8, $details); $sql = "UPDATE `news` SET `newsdate` = NOW(), `approved` = 1 WHERE `id` = '$id'"; header("Location: " . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] ); } } else if (isset($_POST['deny'])) { if(is_array($_POST['deny'])) { $keys = array_keys($_POST['deny']); $id = $keys[0]; $sql = "UPDATE `news` SET `newsdate` = NOW(), `approved` = -1 WHERE `id` = '$id'"; header("Location: " . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] ); } } else if (isset($_POST['delete'])) { if(is_array($_POST['delete'])) { $keys = array_keys($_POST['delete']); $id = $keys[0]; $sql = "DELETE FROM `news` WHERE `id` = '$id'"; header("Location: " . $_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING'] ); } } if(isset($sql) && !empty($sql)) { mysql_query($sql) or die(mysql_error()); } ?> Hi I have an array of items that I am currently displaying a foreach loop What I'm looking to do, is add a string, to all of items, a part from the last 4: foreach ($pager->getResults() as $items => $item) { echo $item->getName(); //need to add a string to this for the all but the last 4 } Thanks |