calmchess Posted December 11, 2009 Share Posted December 11, 2009 i have a field that stores a number i need to increment that number by 1 for each row so if there is a 1 in the row it get incrmented to 2 then if there is a 2 in the next row it gets incremented to 3 .....and on untill there are no more rows.I'm using php to make the queries here is the code i tried so far but it just increments all rows to the same number. Thankyou for your time. $result3 = mysql_query("select cnum from payroll") or die(mysql_error()); while ($row = mysql_fetch_array($result3)){ foreach($row as $field) echo $field; mysql_query("update payroll set cnum = cnum+1 where username ='$field'") or die(mysql_error()); } Quote Link to comment https://forums.phpfreaks.com/topic/184784-php-update-number-in-rows/ Share on other sites More sharing options...
premiso Posted December 11, 2009 Share Posted December 11, 2009 Why are you looping through each field doing this update? You do not need to do that, as $field is always going to be cnum, since that is the only column you are pulling out of the database (not sure why you are assigning username to that). Is cnum considered a "username" I do doubt that, where is username suppose to come from for the update? If from the table, add it to your original SQL SELECT statement to pull it out. Now for your logic / what you are trying to do I am so confused. Can you elaborate, perhaps with an example of what you want accomplished (meaning this is what is in the database this is what it should be after running and only show 4-5 rows for the example)? To clean up your code: $result3 = mysql_query("select username from payroll") or trigger_error("SQL Failed: " . mysql_error()); while ($row = mysql_fetch_assoc($result3)){ mysql_query("update payroll set cnum = cnum+1 where username ='{$row['username']}'") or trigger_error("SQL Failed: " . mysql_error()); } However, for a query this simple you do not really need to pull it out into PHP. UPDATE payroll SET cnum = cnum+1 Will do it, as that is essentially all you are doing in the php code. As stated, please elaborate more on what the end goal is and please provide a small example data of what it currently is and what you want to have happen. Quote Link to comment https://forums.phpfreaks.com/topic/184784-php-update-number-in-rows/#findComment-975502 Share on other sites More sharing options...
calmchess Posted December 11, 2009 Author Share Posted December 11, 2009 sorry about the bad post with wrong variables been trying to do a bunch of diffrent things....think i've solved my problem i was approaching the problem from too complicated process.....Thanks for your time u helped me focus. Quote Link to comment https://forums.phpfreaks.com/topic/184784-php-update-number-in-rows/#findComment-975511 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.