Solved

Move the records up/down (sort) in database PHP

Posted on 2008-06-17
10
8,715 Views
Last Modified: 2008-06-18
Hi, I'm trying to sort the records in a table by using an 'up' and 'down' buttons (images).

Basically it should swap the position of the two records in the database:
example records A B C D - When you click the 'up' button for C the records should now read A C B D.

I'm using 'id' which is the primary key and 'order' (integer with default as 0) which should hold the value of the order of the records.

Been struggling for a long time on this one, your help would be really appreciated!!! :D

I'm attaching the sort_toptip.php page as a code snippet, the code with the buttons which call it are below:

---------------------------------------------------

<?php

// Create an object (instance) of the DbConnector
$connector = new DbConnector();

// Execute the query to retrieve articles
$result = $connector->query('SELECT id,day,month,year,location,venue FROM TopTips ORDER BY id ASC LIMIT 0,1000');

// Get an array containing the results.
// Loop for each item in that array
echo '<h3>Top Tips</h3>';

while ($row = $connector->fetchArray($result)){

echo '<h6>';
echo '<span class="courselist">';
echo $row['day'];
echo '</span>';
echo '<span class="courselist">';
echo $row['month'];
echo '</span>';
echo '<span class="courselist">';
echo $row['year'];
echo '</span>';
echo '<span class="courselist">';
echo $row['location'];
echo '</span>';
echo '<span class="courselist">';
echo $row['venue'];
echo '</span>';
echo '<span class="courselist">';
echo '<a href="edit_toptip.php?id='.$row['id'].'">EDIT</a> /';
echo '</span>';
echo '<span class="courselist">';
echo '<a href="delete_toptip.php?id='.$row['id'].'">DELETE</a>';

echo '<span class="sorting"> ';
echo ' <a href="sort_toptip.php?id='.$row['id'].'&move=up"><img src="../images/up.gif" border="0" /></a>';
echo '</span>';

echo '<span class="sorting">';
echo '<a href="sort_toptip.php?id='.$row['id'].'&move=down"><img src="../images/down.gif" border="0" /></a>';
echo '</span>';

echo '</span>';
echo '</h6>';

}
?>

<?php

 

// Require the database class

require_once('../includes/DbConnector.php');

 

// Create an object (instance) of the DbConnector

$connector = new DbConnector();

 

 

if (isset($_GET['move']) && $_GET['move'] == "up"){

 

$connector->query("UPDATE `TopTips` SET `order` = `order` - 1 WHERE `order` = " . $_GET['order']+1);

$connector->query("UPDATE `TopTips` SET `order` = `order` + 1 WHERE `id` = " . $_GET['id']);

 

print "<meta http-equiv=\"refresh\" content=\"0;URL=index.php\">";

 

}

 

if (isset($_GET['move']) && $_GET['move'] == "down"){

 

$connector->query("UPDATE `TopTips` SET `order` = `order` + 1 WHERE `order` = " . $_GET['order']-1);

$connector->query("UPDATE `TopTips` SET `order` = `order` - 1 WHERE `id` = " . $_GET['id']);

 

print "<meta http-equiv=\"refresh\" content=\"0;URL=index.php\">";

 

}

 

 

?>

Open in new window

0
Comment
Question by:zollgut
  • 6
  • 4
10 Comments
 
LVL 18

Accepted Solution

by:
Matthew Kelly earned 500 total points
ID: 21809180
Untested, but try this. The basic concept is you get the last and next id's so you know which ones you need to update.

Let me know if you have any problems. Both files are in the snippet.
<?php
 

// Create an object (instance) of the DbConnector

$connector = new DbConnector();
 

// Execute the query to retrieve articles

$result = $connector->query('SELECT `id`,`day`,`month`,`year`,`location`,`venue` FROM `TopTips` ORDER BY `order` ASC LIMIT 0,1000');
 

// Get an array containing the results.

// Loop for each item in that array

echo '<h3>Top Tips</h3>';
 

$num = mysql_num_rows($result);

if ( $result && $num > 0 )

{

	$lastid = "";

	for ( $i=0; $i < $num; $i++ )

	{

		$id = mysql_result($result,$i,"id");

		$day = mysql_result($result,$i,"day");

		$month = mysql_result($result,$i,"month");

		$year = mysql_result($result,$i,"year");

		$location = mysql_result($result,$i,"location");

		$venue = mysql_result($result,$i,"venue");
 

		if ( ($i+1) != $num )

		{

			$nextid	= mysql_result($result,$i+1,"id");

		}
 

		echo '<h6>';

		echo '<span class="courselist">';

		echo $day;

		echo '</span>';

		echo '<span class="courselist">';

		echo $month;

		echo '</span>';

		echo '<span class="courselist">';

		echo $year;

		echo '</span>';

		echo '<span class="courselist">';

		echo $location;

		echo '</span>';

		echo '<span class="courselist">';

		echo $venue;

		echo '</span>';

		echo '<span class="courselist">';

		echo '<a href="edit_toptip.php?id='.$id.'">EDIT</a> /';

		echo '</span>';

		echo '<span class="courselist">';

		echo '<a href="delete_toptip.php?id='.$id.'">DELETE</a>';
 

		if ( $i != 0 )

		{

			echo '<span class="sorting"> ';

			echo ' <a href="sort_toptip.php?id='.$id.'&lastid='.$lastid.'&move=up"><img src="../images/up.gif" border="0" /></a>';

			echo '</span>';

		}
 

		if ( ($i+1) != $num )

		{

			echo '<span class="sorting">';

			echo '<a href="sort_toptip.php?id='.$id.'&nextid='.$nextid.'&move=down"><img src="../images/down.gif" border="0" /></a>';

			echo '</span>';

		}

		echo '</span>';

		echo '</h6>';

		$lastid = $id;

	}

}

?>
 

<?php

 

// Require the database class

require_once('../includes/DbConnector.php');

 

// Create an object (instance) of the DbConnector

$connector = new DbConnector();

 

 

if (isset($_GET['move']) )

{

	if ( $_GET['move'] == "up")

	{

 		$connector->query("UPDATE `TopTips` SET `order` = `order` - 1 WHERE `id` = " . $_GET['lastid']);

		$connector->query("UPDATE `TopTips` SET `order` = `order` + 1 WHERE `id` = " . $_GET['id']); 

	}

 	else if ( $_GET['move'] == "down")

	{ 

		$connector->query("UPDATE `TopTips` SET `order` = `order` + 1 WHERE `order` = " . $_GET['nextid']);

		$connector->query("UPDATE `TopTips` SET `order` = `order` - 1 WHERE `id` = " . $_GET['id']);

 	}

}

print "<meta http-equiv=\"refresh\" content=\"0;URL=index.php\">"; 

?>

Open in new window

0
 

Author Comment

by:zollgut
ID: 21809559
Works like a charm!! :D Exactly what i needed

Had 1 bug but i managed to solve it. Thanks a lot!

0
 
LVL 18

Expert Comment

by:Matthew Kelly
ID: 21809610
Could you post the fix for the error and award the points?
0
 

Author Comment

by:zollgut
ID: 21809706
Hi, the solution worked great, but the order only works if the records all have sequential order numbers. I cannot set the order field to auto increment as it has to be the primary key.

So i guess i will need to find the highest number in the order field and add 1 to it whenever a new course is created. Could you help me out with this also (sorry i'm new to php!)

Thanks
0
 
LVL 18

Expert Comment

by:Matthew Kelly
ID: 21809763
Not a problem do this, and assume you had a GET variable "add" or something like that. The day, month etc variables can be set to whatever you would like the default to be.
<?php
 

// Require the database class

require_once('../includes/DbConnector.php');

 

// Create an object (instance) of the DbConnector

$connector = new DbConnector();
 

if ( isset ( $_GET['add'] ) )

{

	$day = date("d");

	$month = date("m");

	$year = date("y");

	$location = "Default Location";

	$venue = "Default Venue";
 

	$result = $connector->query('SELECT MAX(`order`) FROM `TopTips`');

	if ( $result && mysql_num_rows($result) > 0 )

	{

		$max = mysql_result($result,0,0) + 1;

	}

	else

	{

		$max = 0;

	}

	$result = $connector->query("INSERT INTO `TopTips` (`order`,`day`,`month`,`year`,`location`,`venue`) VALUES ('".$max."','".$day."','".$month."','".$year."','".$location."','".$venue."')");

 

}

?>

Open in new window

0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:zollgut
ID: 21809973
Hi I've been trying to make yours work with my existing code but its not working.

Do you know why?

Thanks
<?php

// Get the PHP file containing the DbConnector class

require_once('../includes/DbConnector.php');
 

// Check whether a form has been submitted. If so, carry on

if ($HTTP_POST_VARS){
 

// Create an instance of DbConnector

$connector = new DbConnector();
 

$result = $connector->query('SELECT MAX(`order`) FROM `TopTips`');

	if ( $result && mysql_num_rows($result) > 0 )

	{

		$max = mysql_result($result,0,0) + 1;

	}

	else

	{

		$max = 0;

	}
 
 

// Create an SQL query (MySQL version)

$insertQuery = "INSERT INTO TopTips (day,month,year,location,venue,order) VALUES (".

"'".$HTTP_POST_VARS['day']."', ".

"'".$HTTP_POST_VARS['month']."', ".

"'".$HTTP_POST_VARS['year']."', ".

"'".$HTTP_POST_VARS['location']."', ".

"'".$HTTP_POST_VARS['venue']."', ".

"'".$max."')";
 

// Save the form data into the database 

if ($result = $connector->query($insertQuery)){
 

// It worked, give confirmation

  print "<meta http-equiv=\"refresh\" content=\"0;URL=index.php\">";
 

}else{
 

// It hasn't worked so stop. Better error handling code would be good here!

exit('<center>Sorry, there was an error saving to the database</center>');
 

}
 

}

?>

Open in new window

0
 
LVL 18

Expert Comment

by:Matthew Kelly
ID: 21810013
Get rid of "$result = " in the if statement at the end
if ($result = $connector->query($insertQuery)){

Open in new window

0
 

Author Comment

by:zollgut
ID: 21810021
managed to get it working!

Thanks for all your help!!!!!!!! :D

0
 

Author Comment

by:zollgut
ID: 21811689
Another thing i noticed is now when i delete a record there is a gap in the sequence of order numbers so the records arent moved correctly afterwords.

Example
record A = 13
record B = 14
record C = 15
record D = 16

If I delete record B there is no order number of 14 so then if i move record C up or record A down, they both end up with the same value of 14.

Thanks

0
 

Author Comment

by:zollgut
ID: 21813783
Any idead how i can overcome this?

Thanks
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

CCModeler offers a way to enter basic information like entities, attributes and relationships and export them as yEd or erviz diagram. It also can import existing Access or SQL Server tables with relationships.
Shadow IT is coming out of the shadows as more businesses are choosing cloud-based applications. It is now a multi-cloud world for most organizations. Simultaneously, most businesses have yet to consolidate with one cloud provider or define an offic…
Video by: Steve
Using examples as well as descriptions, step through each of the common simple join types, explaining differences in syntax, differences in expected outputs and showing how the queries run along with the actual outputs based upon a simple set of dem…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

743 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

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now