Link to home
Start Free TrialLog in
Avatar of zollgut
zollgut

asked on

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

ASKER CERTIFIED SOLUTION
Avatar of Matthew Kelly
Matthew Kelly
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of zollgut
zollgut

ASKER

Works like a charm!! :D Exactly what i needed

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

Could you post the fix for the error and award the points?
Avatar of zollgut

ASKER

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
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

Avatar of zollgut

ASKER

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

Get rid of "$result = " in the if statement at the end
if ($result = $connector->query($insertQuery)){

Open in new window

Avatar of zollgut

ASKER

managed to get it working!

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

Avatar of zollgut

ASKER

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

Avatar of zollgut

ASKER

Any idead how i can overcome this?

Thanks