We help IT Professionals succeed at work.
Get Started

MYSQL - PHP Record Update problem

tnowacoski asked
Last Modified: 2012-05-12
I have a MYSQL table called 'news' that has the following fields:

id - int(10) - Primary Key
message - varchar(500)
order - in(2)
active - tinyint(1)

With the following code, I was hoping to be able to insert a new record and have the 'order' field automatically increment on any conflicting records and all other ascending records.  Basically allowing a reorder of the records during the insertion of a new record.  

By this, I mean, if the order already exists in the table, it and all other ascending records would be incremented by one before the new record is inserted.

The records are being inserted into the table but the reorder is not happening, what am I doing wrong?

The first function is addnews and is called from a submit.


function addnews($message, $order, $active) {
	$message = mysql_real_escape_string($message);
	$order = mysql_real_escape_string($order);
	if (orderexists($order, $active) === true) {
		$pass = orderrenum($order, $active);
	$sql = "INSERT INTO news VALUES ('','$message', '$order', '1')";
	$result = mysql_query($sql);
	if (!empty($result)) {
		return true;
	} else {
		return $result;

function orderexists($order, $active) {
	$sql = "SELECT order FROM news WHERE order= " . $order . " AND active = 1";
	$result = mysql_query($sql);
	$num = mysql_numrows($result);
	if ($num > 0) {
		return true;
	} else {
		return false;

function orderrenum($order, $active) {
	$sql = "SELECT id, order FROM news WHERE order >= " . $order . " AND active = 1";
	$result = mysql_query($sql);
	while ($row = mysql_fetch_assoc($result)) {
		$sql = "UPDATE news SET order = " . $row['order']+1 . " WHERE id = " . $row['id'];
		$result = mysql_query($sql);

Open in new window

Watch Question
This problem has been solved!
Unlock 1 Answer and 13 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE