PHP - While Loop Auto Increment?
Hi,
I have coded a lot in the past but only now getting into PHP and web coding in general, when I use a while loop in most other languages I need to increment some form of counter to move to the next item e.g. Code: [Select] while (count < 10) { Do something; count + 1; } I am going through a set of tutorials that have just enlightened me to the following code when looking up a MYsql d'base: Code: [Select] $reults = "SELECT * FROM table"; while ($row = mysql_fetch_assoc($results)){ extract($row); echo $tblcol1; echo " - "; echo $tblcol2; echo "<br>"; } Now in fairness I have no real problem with this, if thats how you extract your results from a query then fine but I feel I am missing something and have not been able to nail it on the head. Am I to assume that $row in the loop returns the first row from the query results, moves through the actions of the loop, returns then automatically points to the next row of the array? Does that mean while($row){} where $row is a 3x3 array(for example) it would loop through this 3 times assigning the next row until the end? Is there a better way to explain this? Similar TutorialsHello, I am creating a job setup form and have a need for the job id field to increment based on the last inserted job id into our Oracle database. So far I have created a function that selects the maximum job id from the job table and adds 1 to the number. However, I run into the problem of when a user is filling out the form and another user opens it and begins filling out the form they both will receive the same job id in the field. I'm assuming this could possibly be solved with sessions, but I'm not sure where to start. Also, the form is not inserted into the table on submit (instead an excel sheet is created with the information and someone will enter the data into the database manually). Since the form data can be entered anytime from completion to next week/two weeks, how can I ensure that that job id is not used again. Thanks Hey, In my table, I have 773 rows like this: 10800 ... 772 ... 771 ... 770 ... 769 ... etc ... When I insert a new row, it will have an ID of 10801 and not 773. I delete row 10800 and I want to insert a new row that has an ID of 773. Is there a code I can use also so that it creates the IDs in order? 1, 2, 3 etc no missing numbers. Thanks. ok, how do I add an auto incremented value to another table at the same time the value is created. so I will do a query to insert into db, and it creates auto incremented value of 1, then I need this value to also be put into another table just as text. how do I go about doing this? I need this all in one query. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=310983.0 is there a way to save a field in a session or variable while its being inserted into the data base? with out having to select it using another query $mail2 = "INSERT INTO pm SET pm_id = '', (turn pm_id into a $variable or session) WHERE blah blah blah the problem im having is Im creating two rows right after each other where each row is in differant tables and I need them to match ids and I have nothing to compare it to. only option i can think of is making a fast toggle switch or telling my select to grab in order which would work. Is there a way to copy an auto-increment value (`id`) into another field in the same table (`org_id`)? So, when someone creates a new organization, it will copy the new auto-increment value into the org_id field. Is this possible? Thanks! This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=321437.0 hey guys i have this invoice im working on but my clients want's the invoice id start at a specific number?
do it put that number in phpmyadmin direct on the line null?or can i do it another way?
Hi everyone,
I have an application that makes use of a transaction, inserting and updating values in different tables. One of the first tables it inserts into has an auto increment ID field. This ID values is used / updated in some other tables. Everything works fine. If however the transaction fails then the auto_increment values are upset - meaning that the sequence is jumped.
For ex. if I had auto_increment values from 1 to 6 in this table and then the insert query fails for an auto_increment value of ID=7, then this value of ID = 7 is lost because the next time the query is run the auto_increment ID value will be equal to 8 and accordingly updated in the tables. ID value = 7 is lost. Is there any way to prevent this ? Please know that this is a multi - user application.
Thanks.
I've been trying to grab the unique auto incrementing table id and put into a session variable. $name_id = mysql_insert_id(); $query = sprintf("INSERT INTO profile ( name_id, bio, ex) VALUES (LAST_INSERT_ID(),'%s','%s')", mysql_real_escape_string($_SESSION['pro']['bio']), mysql_real_escape_string($_SESSION['pro']['ex'])); $result = mysql_query($query, $db) or die(mysql_error($db)); $name_id = mysql_insert_id(); $_SESSION['name_id'] = $name_id; //this is the key line $_SESSION['logged'] = 1; header('Refresh: 5; URL=main.php'); I've echoed out the result of $_SESSION['name_id'] and it says '0'. I've tried changing the key line to $_SESSION['name_id'] = LAST_INSERT_ID(); but I get this error message: Fatal error: Call to undefined function LAST_INSERT_ID() in C:\x\xa Is my goal acheivavle or should I just set up a select query after the insert query and extract the id key? must be v easy to answer for many here but i dont know how to do it how can i use for loop to print values between any range but with increment of 0.5 0 0.5 1 1.5 2 2.5 3 ........till n 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 I am doing some study on using time() and date() and i just wrote this simple for loop to add one day to each iteration with +$i and its echoing the unix timestamp as opposed to the correctly formated date as it should be based on my code. Anyone have any idea why this is not working as expected? for($i=0; $i < 50; $i++) { echo $time = time()+$i . "<br />"; // add a day on each iteration echo date('y-m-d', $time) . "<br />"; // should echo 10-12-02, 10-12-03, 10-12-04, etc.. } what am i doing wrong here? arrgggg! maybe its too late for this s$%^#!
hi, i’m currently facing a new problem (i managed to use array_unique function successfully but i face this problem)with my php loop. i couldn’t seem to increment in my foreach loop to get the value of an array. $update_id1=Array ( [0] => 398 [1] => 397 [2] => 393 [3] => 391 [8] => ); //$i=0; foreach ($update_id1 as $i => $v) { $ex= explode(",", $v); $unique=array_unique($ex); //f$ketch username from update table in db and inject it to the feed query. $imp_id= implode(',', $ids); //$id1=$ids[$i]; // $x=0; // for($x=0;$x<count(unique);$x++){ echo 'ids:- '.$i; print_r($unique[$i]); echo '<br>'; //} $totalUpdates=$project->totalUpdates($ids[$i],$_SESSION['uname'] ,$unique[$i],$load); //$i++; } i tried every method nothing seems to work can anyone help me in this regard please. Edited December 25, 2019 by narutofanHi Guys Ever had the feeling your being a spoon and can't see the wood for the trees? Well, that's how I feel today. All I am trying to to is implement a variable in a "foreach" loop that increments by one through each iteration of the loop. I know how to do it in a "for" loop but can't for the life of me get it to work here. Here is the code: foreach ($cart as $prodcode => $qty) { $item = get_product_details($prodcode); echo '<input type="hidden" name="item_name_'.[b]$needavariablehere[/b].'" value="'.$item['description'].$_SESSION['finish'][$prodcode].$_SESSION['handles'][$prodcode].'" />' . "\n"; } Where I have highlighted $needavariablehere is where I want a number to appear i.e. if there is one item available and the foreach loop iterates once I want the number 1 here. If there are two items and the foreach loop iterates twice I want the output to have number 1 in the first line and number 2 the second time around and so on. How many times the foreach loop iterates is based on the $cart array which contains items in a shopping cart. Thanks for any help you can give guys. I believe it's called increment. Either way, I cannot figure out how to simply count up beginning at 1 (in red in the div below) ... function wp_rss( $url, $num_items = -1 ) { if ( $rss = fetch_rss( $url ) ) { echo '<div id="charts">'; if ( $num_items !== -1 ) { $rss->items = array_slice( $rss->items, 0, $num_items ); } foreach ( (array) $rss->items as $item ) { printf( '<div id="chart_lt">1</div><div id="chart_rt">%3$s</div>', esc_url( $item['link'] ), esc_attr( strip_tags( $item['description'] ) ), htmlentities( $item['title'] ) ); } echo '</div>'; } else { _e( 'An error has occurred, which probably means the feed is down. Try again later.' ); } } Code: [Select] $db->query('UPDATE users set actions=actions+1|'.time().' where id = '.$pun_user['id'].''); im trying to do set actions=actions+1, then put a | atfter +1ing it, then add my time stamp to it so I can explode it later. so it will look like this 2|unixtimestamphere how would i achieve this? or do I need to make another seperate row? seems dumb So a project I have simply to learn how it is done is to make an auto updating sitemap with a auto submitter. I have been doing a little research on sitemaps but haven't found much in the way of a tutorial or white paper or similar, anyway I was wondering if I am on the right track or not. What I was thinking for the auto-updating sitemap is since site maps are XML, when an article is published using my custom CMS/Blogging system, I make it rewrite the sitemap appending the new URL that will be generated. Then for the auto-submit, I can either make it a cron job or just manual press, but it would go though a for list of URLs, replacing the end part with my site map url. I think that is how it would be done. If you have a better idea, or can point out an article so I can understand a lot more with sitemaps, I will appreciate it, I am trying to learn as much as possible, I have gone to the offical website (sitemaps.org) but it doesn't have what I am looking for. Thanks, James //php code <?php include_once('con.php'); if(!empty($_GET['search'])) { $search = $connect->prepare('SELECT * FROM posts WHERE title LIKE :search'); $search->bindValue(':search', '%'.$_GET['search'].'%', PDO::PARAM_STR); $search->execute(); ?> <?php while($row = $search->fetch()) {?> <li class="result" onClick="searchValue('<?php echo $row['title'];?>')"><?php echo $row['title'];?></li> <?php } ?> <?php } ?> //ajax $('#inputsch').keyup(function(){ $.ajax({ type: 'GET', url: 'fetch.php', data:'search='+$(this).val(), success: function(data){ $('#box').show(); $('#box').html(data); } }); }); }); function searchValue(val) { $('#inputsch').val(val); $('#box').hide(); } //search box <form action="search.php"> <input id="inputsch" type="text" name="search" placeholder="search..." autocomplete="off" autofocus> <button type="submit" value="search" >search</button> </form> <div id="box"></div> //the problem here is when i click the result is only added to input, but i want it to autosubmit
Hi there! Hoping someone can help me with this very specific issue I have a string that looks like this: Code: [Select] var1 var2 X var3 var4 X var5 I need to find the highest number next to var (in this case 5), and to replace X with the following number (in this case var6). So after the replace, the string would look like this: Code: [Select] var1 var2 var6 (this x has been replaced for var6) var3 var4 var7 (this x has been replaced for var7) var5 Any ideas!? Thanks! |