?
Solved

PHP with MySQL looping to find next number down in primary key

Posted on 2007-11-18
7
Medium Priority
?
738 Views
Last Modified: 2013-12-13
I'm having real trouble with a loop that I'm hoping someone can help with.

The situation is as follows.
I have a variable $prev with the value 499. I also know that in my MySQL database the highest value in my ID field (primary key) below 499  is 3.

I'm using the following loop to count backwards from $prev until it hits a database row with that number in its ID field. However it's not working at all, can anyone tell me where I'm going wrong?

When the loop terminates the value of $prev should be 3

while ($row=mysql_fetch_array(mysql_query("SELECT * FROM guestbook WHERE ID NOT LIKE '$prev'"))) {$prev--;}
echo $prev;

Open in new window

0
Comment
Question by:Mr_Splash
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
7 Comments
 
LVL 82

Expert Comment

by:hielo
ID: 20310217
The problem is that you are executing a mysql_query always returns results.
when $prev=499, you will get all the rows except the one where ID=499 (rows 498 -> 3),
when $prev=498, you will get all the rows except the one where ID=498 (row 499, 497 -> 3),
.
.
.
when $prev=3, you will get all the rows except the one where ID=3 (rows 499 -> 4),
when $prev=2, you will get all the rows (rows 499 -> 3),
when $prev=1, you will get all the rows (rows 499 -> 3),
when $prev=0, you will get all the rows (rows 499 -> 3),
...(forever!)

Why forever? Because once $prev decreases beyond your lowest id (3), your query is looking for
all the fields where the ID does not equal $prev, which is all the fields. What are you trying to accomplish?
Why are you counting backwards?
0
 
LVL 3

Author Comment

by:Mr_Splash
ID: 20311607
Hi heilo,

Basically I'm trying to find the next row down in the db, so that I can take it's ID add one to its value and change record 499's ID to this number. So basically closing the gap between them.
0
 
LVL 82

Expert Comment

by:hielo
ID: 20313409
It sounds like you want to have only consecutive IDs. If so, you should not be doing this if the table in question is related to some other table. If this is the case, you will corrupt your Data.

Having said that, if you really want to do this, the easiest way to accomplish this is to create a new empty table with the exact same fields (datatype and fieldName) as the original one (guestbook in your case). On your new table, the ID should be set to autonumber.
Assuming guestbook looks as follows:
ID first     last
3  John   Doe
5  Jane   Doe

you can copy that table to guestbook2 as follows:
INSERT INTO guestbook2(ID,first, last) SELECT FROM guestbook (NULL as ID, first, last) WHERE 1;

After executing that, guestbook2 would have:
ID first last
1 John Doe
2 Jane Doe

If need the table to begin with ID 3, you can first insert two empty records into guestbook2 before runnting the query above. I suspect your tables have more fields, but I think you get the idea.
0
Why Off-Site Backups Are The Only Way To Go

You are probably backing up your data—but how and where? Ransomware is on the rise and there are variants that specifically target backups. Read on to discover why off-site is the way to go.

 
LVL 3

Author Comment

by:Mr_Splash
ID: 20314427
Sorry that doesn't really seem ideal as it's something that has to be done regularly.

I'll give a better overview of what's going on. I've built an admin page for the guestbook on a clients site. In this admin page they can do a number of things to the posts, i.e. Delete, move up, move down etc.

The particular loop I gave previously is part of the move up code, The full block is below.
//Move up
if ($_POST['up'] == 1) {
  $ID = $_POST['ID'];
  $row = mysql_query("SELECT * FROM guestbook WHERE ID='$ID'") or die(mysql_error());
  $prev = $ID - 1; //Get previous slot
    if ($row=mysql_fetch_array(mysql_query("SELECT * FROM guestbook WHERE ID='$prev'"))) { //is there a entry with prev ID?
	  $temp = 99999;
	  while ($row=mysql_fetch_array(mysql_query("SELECT * FROM guestbook WHERE ID='$temp'"))) {//If a value is in temp find a new one
	    $temp++;
	  }
	  mysql_query("UPDATE guestbook SET ID='$temp' WHERE ID='$prev'"); 
	  mysql_query("UPDATE guestbook SET ID='$prev' WHERE ID='$ID'");
	  mysql_query("UPDATE guestbook SET ID='$ID' WHERE ID='$temp'");  	  
	}
	else { //No entry in previous
	  while ($row=mysql_fetch_array(mysql_query("SELECT * FROM guestbook WHERE ID NOT LIKE '$prev'"))) {$prev--;} //Find previous record
	  echo $prev;
	  $replace = $prev++;
	  mysql_query("UPDATE guestbook SET ID='$replace' WHERE ID='$prev'"); 
	  mysql_query("UPDATE guestbook SET ID='$prev' WHERE ID='$ID'"); 
	}
}

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
ID: 20316340
Do you have a "position"  (or equivalent) field on db? EX:
Browser sees:
<option value="5">A</option>
<option value="8">B</option>
<option value="2">C</option>

Moving "C" up once requires you to update the new position of B and the new position of C. The id values don't reveal the items position. It might help clarify the issue if you paste the HTML code that is being send to the browser.
0
 
LVL 3

Accepted Solution

by:
Mr_Splash earned 0 total points
ID: 20316863
I've managed to figure out a solution. It came to me while trying to sleep actually :)

I've swapped the loop in my original post for this one and it's all working now.

Thank you for your help anyway Hielo.
while ($found != 1) {
  if ($row=mysql_fetch_array(mysql_query("SELECT * FROM guestbook WHERE ID='$prev'"))){$found = 1;}
  else {$prev--;}
}

Open in new window

0
 
LVL 82

Expert Comment

by:hielo
ID: 20317035
Good job. I see originally your WHERE condition was: "NOT LIKE". I guess this was the root of your problem.
0

Featured Post

WordPress Tutorial 3: Plugins, Themes, and Widgets

The three most common changes you will make to your website involve the look (themes), the functionality (plugins), and modular elements (widgets).

In this article we will briefly define each again, and give you directions on how to install them.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to count occurrences of each item in an array.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question