Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 9146
  • Last Modified:

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

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
zollgut
Asked:
zollgut
  • 6
  • 4
1 Solution
 
Matthew KellyCommented:
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
 
zollgutAuthor Commented:
Works like a charm!! :D Exactly what i needed

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

0
 
Matthew KellyCommented:
Could you post the fix for the error and award the points?
0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
zollgutAuthor Commented:
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
 
Matthew KellyCommented:
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
 
zollgutAuthor Commented:
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
 
Matthew KellyCommented:
Get rid of "$result = " in the if statement at the end
if ($result = $connector->query($insertQuery)){

Open in new window

0
 
zollgutAuthor Commented:
managed to get it working!

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

0
 
zollgutAuthor Commented:
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
 
zollgutAuthor Commented:
Any idead how i can overcome this?

Thanks
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

  • 6
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now