Jump to content

php update number in rows


calmchess

Recommended Posts

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());

  }

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.