PHP - Converting Dates From The Database In While Loop
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. Similar TutorialsHello everyone, I'm here again with moar problems . This time I need help converting dates, I have the jQuery UI Datepicker on my register form, Which creates a date with the format of 21/02/1995, Or "dd/mm/yyyy". Can someone explain how convert this string to "yyyymmdd"? Thanks in advance (Something tells me this will end up really simple.... Hmm......) Hi,
I am completely stuck on this.
I am trying to allow the user to select a start day and end day. then the system adds two weeks to the start day and each previous calculation (ie intervals of 0 weeks, 2 weeks, 4 weeks, etc. from the start day) until the end date is reached. I would also like each of these dates to be inserted into my database.
I have no clue as to where to even start with this. I know I will need some kind of loop based on days, but I am not sure how I would write this.
I suppose this would be the basic structure of the query, but not sure how to incorporate this loop that I need.
mysql_query("INSERT INTO events (title, date) VALUES ('$title', '(current date that the loop is in)')"); mysql_error();can anyone help me out with this? thanks in Advance! Hi All, I'm hoping someone can help as I've got myself in a muddle on some code. Basically, the form has a date field (date moved in). If the date entered is over 3 years old, all's ok However, if the date entered is less than 3 years old, the user needs to complete a list field. The list field is essentially a repeater field with a date and address field. If the user adds a date and address and this (plus the original date) is more than 3 years combined history - happy days! If the user adds a date and address and they've still not hit 3 years history, then I need to increase the number of rows (this is handled by another function which works by incrementing a field on the form. As it stands, it works until I need another field to appear i.e. they've entered the first date, then entered a date within the list/repeater field but still not got 3 years worth. I think it's more or less there but seem to have muddled some of the logic (I think/hope!). A fresh pair of eyes would be great: Here's my code: function dateDiffInDays($date1, $date2) { # Calulating the difference in timestamps $diff = strtotime($date2) - strtotime($date1); # 1 day = 24 hours # 24 * 60 * 60 = 86400 seconds return abs(round($diff / 86400)); } add_filter( 'gform_pre_render_2', 'applicant_2_previous_address_history' ); add_filter( 'gform_pre_validation_2', 'applicant_2_previous_address_history' ); function applicant_2_previous_address_history( $form ) { #get the value from the form date input d/m/Y so need to change $get_moved_in_date = rgpost( 'input_1' ); if ( $get_moved_in_date ) { #convert the date format $moved_in_date = date_format(date_create_from_format('d/m/Y', $get_moved_in_date), 'd-m-Y'); #echo "New date format is: ".$moved_in_date. "<br/>"; } #get todays date $today = date("d-m-Y"); #echo "<h3>Today: ".$today."</h3>"; #calculate the difference in days $dateDiff = dateDiffInDays($today, $moved_in_date); #printf("<p>Difference between two dates: " . $dateDiff . " Days</p>"); #check if we moved in less than 3 years ago if ( $dateDiff < 1095 ) { #less than 3 years, so need to loop through the list fields, compare dates and tally totals days if ( $days_sum < 1095 ) { # get the input from the list $list_values = rgpost( 'input_2' ); $i = 0; #use this to get even rows only due to the way data is stored :( $sum = 0; #use this to increment the no. of rows in the list $previous = null; #use this to calc date difference between rows $days_sum = $dateDiff; #set the total number of days. Don't start at 0, start from current date - time at current residence if ( $list_values ) { foreach ( $list_values as $key => $value ){ #get even rows only if($i%2 == 0){ #$sum = $sum + 1; #increment our rows if ( $value ) { #convert the date format $additional_date = date_format(date_create_from_format('d/m/Y', $value), 'd-m-Y'); #echo "<h3>Date: ".$additional_date."</h3>"; } if ( $previous !== null ){ # if it's null, we're in the first loop #convert the date format $previous_date = date_format(date_create_from_format('d/m/Y', $previous), 'd-m-Y'); $dateDiff2 = dateDiffInDays($additional_date, $previous_date); printf("<p>Next Iteration Difference between " . $additional_date . " and " . $previous_date . " is: " . $dateDiff2 . " Days</p>"); $days_sum = $days_sum + $dateDiff2; } else { #convert the date format $dateDiff1 = dateDiffInDays($additional_date, $moved_in_date); printf("<p>1st Iteration Difference between " . $additional_date . " and " . $moved_in_date . " is: " . $dateDiff1 . " Days</p>"); $days_sum = $days_sum + $dateDiff1; } $previous = $value; # set the current value, so it will be saved for the next iteration } $i++; } #end foreach $list_values } #endif $list_values $sum = $sum + 1; #increment our rows echo "<p>Total no of days = " .$days_sum.'</p>'; } #endif $days_sum < 1095 echo '<p>Not enough days so loop through list</p>'; $flag = 'true'; } else { echo '<p>Were ok!</p>'; $flag = 'false'; } #endif $dateDiff < 1095 /* if ( $dateDiff < 1095 ) { $value = 'yes'; } else { $value = 'no'; } */ #we moved in less than 3 years ago, so get history if ( $flag == 'false' ) { return $form; } foreach ( $form['fields'] as &$field ) { if ( $field->id == 2 ) { $field->isRequired = true; } echo "<p>The sum of array element is = " .$sum.'</p>'; if ( $field->id == 3 ) { $_POST['input_3'] = $sum; } } return $form; } Thanks guys, im having a problem here... i tried too many ways to convert dates in american format, to brazilian format, but no one is working... how can i do that, to convert it to dd/mm/yyyy (it comes from my db in mysql)... example structure of text database- mytextfile.txt 10-11201|2010/09/01|Sam|Thurston 10-11307|2010/09/04|Tony|Piper 10-11405|2010/09/11|Sarah|Smith <?php $file2 = 'mytextfile.txt'; $openedfile =fopen($file2, "r") or die("ERROR- could not open file for editing."); // flock($openedfile, LOCK_EX) or die("Error!- Could not obtain exclusive lock on the file to edit."); $hold[$record_count] = explode("|", trim(fgets($openedfile))); while(!feof($openedfile)) { $record_count++; $hold[$record_count] = explode("|", trim(fgets($openedfile))); } ?> What I need to do is loop through this and one by one- take any arrays that contain a date that is between $dateX and $dateY (which comes via a form input) and place it in a new array $matched. I am stumped. 1-Is there a way to do it inside the above while loop that I am not seeing? 2- Do I need to open the file in another manner? 2- Would it be best to now loop through $hold[$record_count] I am trying to keep the process short so as not to use up too much memory. Point me in the right direction for this one please. Hi, I'm trying to get the date, using this code <?php include('config.php'); $today = date('Y-m-d 00:00:00'); $nineyesterday = date('Y-m-d H:i:s', mktime(date("H") - (date("H") + 6), date("i") - date("i"), date("s") - date("s"), date("m") , date("d"), date("Y"))); $now = date('Y-m-d H:i:s'); $nineam = date('Y-m-d 9:00:00'); $ninepm = date('Y-m-d 18:00:00'); if ((strtotime($now) >= strtotime($today)) && (strtotime($now) <= strtotime($nineam))) { //count the answers by yes or no $q = "SELECT opt, count(opt) FROM plus_poll_ans WHERE date<='".$nineyesterday."' AND date>='".$nineam."' GROUP BY opt desc "; } elseif ((strtotime($now) >= strtotime($nineam)) && (strtotime($now) <= strtotime($ninepm))) { //count the answers by yes or no $q = "SELECT opt, count(opt) FROM plus_poll_ans WHERE date<'".$nineam."' AND date>='".$ninepm."' GROUP BY opt desc "; } $q = mysql_query($q) or die(mysql_error()); //separate the results while($row = mysql_fetch_array($q)) { $total_opt[] = $row['count(opt)']; } mysql_freeresult($q); $yes = intval($total_opt[0]); $no = intval($total_opt[1]); $total = $yes + $no; echo $total."<br/>"; echo $yes."<br/>"; echo $no."<br/>"; ?> but it didn't work, why isn't it working? Thanks how do i compare dates entered in my form and dates stored in the database. as in for a hotel system a checkin date and check out date Thanks Hi, i'm basically having problems with this code, its for a newsletter script which added the email address into a file, i'm trying to convert it to work with mysql but having a few problems; I've edited the last bit, the code just basically doesn't add it to the database even though i thought i had done it right... any help is very much appreciated! If email is not valid the script is letting me know; if email is valid it says "already added to the list" no matter what. old script <?php /** BY WebResourcesDepot - http://www.webresourcesdepot.com*/ /** YOU CAN EDIT HERE*/ $newsletterFileName = "file.txt"; /** IMPORTANT: EDIT BELOW UNLESS YOU KNOW WHAT YOU ARE DOING*/ function GetField($input) { $input=strip_tags($input); $input=str_replace("<","<",$input); $input=str_replace(">",">",$input); $input=str_replace("#","%23",$input); $input=str_replace("'","`",$input); $input=str_replace(";","%3B",$input); $input=str_replace("script","",$input); $input=str_replace("%3c","",$input); $input=str_replace("%3e","",$input); $input=trim($input); return $input; } /**Validate an email address. Provide email address (raw input) Returns true if the email address has the email address format and the domain exists. */ function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { // local part length exceeded $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } } return $isValid; } $email = GetField($_GET['email']); $pass = validEmail($email); if ($pass) { $f = fopen($newsletterFileName, 'a+'); $read = fread($f,filesize($newsletterFileName)); If (strstr($read,"@")) { $delimiter = ";"; } if (strstr($read,$email)) { echo 3; } else { fwrite($f, $delimiter . $email); echo 1; } fclose($f); } else { echo 2; } ?> edited script <?php /** BY WebResourcesDepot - http://www.webresourcesdepot.com*/ /** YOU CAN EDIT HERE*/ $newsletterFileName = "file.txt"; /** IMPORTANT: EDIT BELOW UNLESS YOU KNOW WHAT YOU ARE DOING*/ function GetField($input) { $input=strip_tags($input); $input=str_replace("<","<",$input); $input=str_replace(">",">",$input); $input=str_replace("#","%23",$input); $input=str_replace("'","`",$input); $input=str_replace(";","%3B",$input); $input=str_replace("script","",$input); $input=str_replace("%3c","",$input); $input=str_replace("%3e","",$input); $input=trim($input); return $input; } /**Validate an email address. Provide email address (raw input) Returns true if the email address has the email address format and the domain exists. */ function validEmail($email) { $isValid = true; $atIndex = strrpos($email, "@"); if (is_bool($atIndex) && !$atIndex) { $isValid = false; } else { $domain = substr($email, $atIndex+1); $local = substr($email, 0, $atIndex); $localLen = strlen($local); $domainLen = strlen($domain); if ($localLen < 1 || $localLen > 64) { // local part length exceeded $isValid = false; } else if ($domainLen < 1 || $domainLen > 255) { // domain part length exceeded $isValid = false; } else if ($local[0] == '.' || $local[$localLen-1] == '.') { // local part starts or ends with '.' $isValid = false; } else if (preg_match('/\\.\\./', $local)) { // local part has two consecutive dots $isValid = false; } else if (!preg_match('/^[A-Za-z0-9\\-\\.]+$/', $domain)) { // character not valid in domain part $isValid = false; } else if (preg_match('/\\.\\./', $domain)) { // domain part has two consecutive dots $isValid = false; } else if (!preg_match('/^(\\\\.|[A-Za-z0-9!#%&`_=\\/$\'*+?^{}|~.-])+$/', str_replace("\\\\","",$local))) { // character not valid in local part unless // local part is quoted if (!preg_match('/^"(\\\\"|[^"])+"$/', str_replace("\\\\","",$local))) { $isValid = false; } } } return $isValid; } $email = GetField($_GET['email']); $pass = validEmail($email); if ($pass) { $user_name = "_db"; $password = ""; $database = "_db"; $server = "localhost"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL2 = "SELECT * FROM newsletter WHERE email = '$_GET[email]'"; $result = mysql_query($SQL2); mysql_close($db_handle); } if (strstr($SQL2,$email)) { echo 3; } else { $user_name = "_db"; $password = ""; $database = "_db"; $server = "localhost"; $db_handle = mysql_connect($server, $user_name, $password); $db_found = mysql_select_db($database, $db_handle); if ($db_found) { $SQL = "INSERT INTO newsletter (email,subscribed) VALUES ('$_GET[email]',1)"; $result = mysql_query($SQL); mysql_close($db_handle);} echo 1; } } else { echo 2; } ?> Say I have two functions that convert from Dollar to Cents and Cents to Dollar. function convertToDollar($value) { $amount = $value / 100; return $amount; } function convertToCents($value) { $amount = $value * 100; return $amount; } Currently I convert all the Dollar amounts to cents and store the cents in the mysql database column. When I showcase those amounts on a page, I simply convert the Cents back to Dollar. Am I doing this correctly or is there a better way to store product pricing in mysql table? Hi All, I need to subtract dates and display the number of days left. I have a 'Start' date and an 'End' date in DATETIME format in the DB. Not quite sure where to start. A simply start - end doesn't work . Start = 2011-11-01-00:00:00 End = 2011-11-30-23:59:59 Since it is now 2011-11-27, my output should equal 3. Any help is appreciated. Hi guys, I am trying to do a multidates events availability calender. The script below indicates todays date by highlighting an orange colour and also indicates the start and end date of the event highlighting grey colour on the two dates (The colour are link via css classes as shown). Code: [Select] //Today's date $todaysDate = date("d/m/Y"); $dateToCompare = $daystring . '/' . $monthstring . '/' . $year; echo "<td align='center' "; if($todaysDate == $dateToCompare){ echo "class='today'"; }else{ //Compare's the event dates $sqlcount = "select event_start,event_end from b_calender where event_start ='".$dateToCompare."' AND event_end='".$dateToCompare."'"; $noOfEvent = mysql_num_rows(mysql_query($sqlcount)); if($noOfEvent >= 1){ echo "class='event'"; } } It works ok i.e. if start date = 01/01/2012 and end date = 04/01/2012 both date will be highlighted with grey colour. However I want it to also highlight grey on the dates between the 1st and 4th to show that then anydates between the 1st and 4th are not available and this is when I'm stuck. Please guys I need help. Thanks 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 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.. 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 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!! For some reason my for loop only seems to be storing some data in my fields, most of the time the data is not true but simply duplicating one of the entries. So instead of having a string of 1,2,3,4 for instance it would store all of them as 4. The entires are selected using fields in a multiple select box, in theory of someone choses 10 unique entries from the "Systems" category all 10 should be made into rows in the MySQL table. Any idea why this is happening? The form, if ($type == "games") { echo "<tr><td>".$name."</td><td><select name='".$name."_".$i."'[] multiple='multiple'><option value='' selected>--------</option>"; $sqla = mysql_query("SELECT * FROM ".$pre."games ORDER BY `name` ASC") or die(mysql_error()); while($row2a = mysql_fetch_array($sqla)) { $system = mysql_fetch_array(mysql_query("SELECT * FROM ".$pre."systems WHERE id = '".$row2a[system]."'")); echo "<option value='".$row2a[id]."'>".$row2a[name]." - ".$system[name]."</option>"; } echo "</select></td></tr>"; } if ($type == "system") { echo "<tr><td>".$name."</td><td><select name='".$name."_".$i."'[] multiple='multiple'><option value='' selected>--------</option>"; $sqlb = mysql_query("SELECT * FROM ".$pre."systems ORDER BY `name` ASC") or die(mysql_error()); while($row2b = mysql_fetch_array($sqlb)) { echo "<option value='".$row2b[id]."'>".$row2b[name]."</option>"; } echo "</select></td></tr>"; } The PHP code, while($row = mysql_fetch_array($query)) { $name = "$row[name]"; for ($i = 0; $i < count($_POST["systems_$i"]); $i++) { mysql_query("INSERT INTO ".$pre."fielddata VALUES (null, 'systems', '".$_POST["systems_$i"]."', '".$fetch[0]."', 'content')"); } for ($i = 0; $i < count($_POST["games_$i"]); $i++) { mysql_query("INSERT INTO ".$pre."fielddata VALUES (null, 'games', '".$_POST["games_$i"]."', '".$fetch[0]."', 'content')"); } Hi 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'"); 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. |