1

I have the following code

<?php

        $result = mysql_query("SELECT * FROM table1");
        $row = mysql_fetch_row($result);

        while($row = mysql_fetch_array($result))
        { 
            //Do some process

            //Then delete this row 
        }

I need to delete each row within the while loop.

is it possible?there is no primary key for this table

Linto P D
  • 8,839
  • 7
  • 30
  • 39

3 Answers3

1

You can't, MySQL would have no clue on which record to delete.

You either use the primary key, or you add all fields and add a LIMIT, and even then you have no way of knowing for sure it is that row.

If you want to delete all records from a table, use

TRUNCATE TABLE table1

So, if you are actually doing SELECT * FROM table1, I'd code it as such:

$result = mysql_query("SELECT * FROM table1");
$row = mysql_fetch_row($result);

while($row = mysql_fetch_array($result))
{ 
    //Do some process

}
mysql_query("TRUNCATE TABLE table1");

(of course, don't use the mysql_* functions, but MySQLi or PDO)

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
1

Please, don't use mysql_* functions in new code. They are no longer maintained and the deprecation process has begun on it. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which.

You could use the following MySQLI code:

$query = "SELECT * FROM tablename";
$result= $mysqli -> query($query);

while($row = $result -> fetch_object()){

      $row_identifier = $row -> column_with_unique_id;

      // Do the processing bit here.

      // Now Delete
      $del_query = "DELETE FROM tablename WHERE column_with_unique_id = ".$row_identifier;
      $del_result= $mysqli -> query($del_query);

}
Community
  • 1
  • 1
ajtrichards
  • 29,723
  • 13
  • 94
  • 101
-1

From your code it looks like you wish to delete all entries from the table. (Because that's what your code/pseudocode does.) You can do that much easier with:

 DELETE FROM table

And please don't use mysql_* functions anymore. They are marked as deprecated and will eventually be removed from PHP. Use MySQLi or PDO instead.

Till Helge
  • 9,253
  • 2
  • 40
  • 56