Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP DELETE immediately after select

I have a PHP server script that SELECTs some data from a MySQL database.

As soon as I have the result from mysql_query and mysql_fetch_assoc stored in my own local variables, I want to delete the row I just selected.

The problem with this approach is that it seems that PHP has done pass-by-reference to my local variables instead of pass-by-value, and my local variables become undefined after the delete command.

Is there anyway to get around this? Here is my code:

    $query="SELECT id, peerID, name FROM names WHERE peer = $userID AND docID = '$docID' AND seqNo = $nid";
    $result = mysql_query($query);

    if (!$result)
        self::logError("FAIL:1 getUsersNamesUpdate() query: ".$query."\n");     

    if (mysql_num_rows($result) == 0)
        return array();

    $row = mysql_fetch_assoc($result);
    $result = array();
    $result["id"] = $row["id"];
    $result["peerID"] = $row["peerID"];
    $result["name"] = $row["name"];

    $query="DELETE FROM names WHERE id = $result[id];";
    $result = mysql_query($query);

    if (!$result)
        self::logError("FAIL:2 getUsersNamesUpdate() query: ".$query."\n");         

    return $result;
like image 896
14 revs, 12 users 16% Avatar asked Apr 02 '26 05:04

14 revs, 12 users 16%


1 Answers

You are overwriting your $result variable with your second statement:

$query="DELETE FROM names WHERE id = $result[id];";
$result = mysql_query($query); // result does not contain the array anymore

Change the name to something else. It has nothing to do with call-by-reference or such.


Actually, your first assignment of the values is unnecessary as $row is already an array:

$row = mysql_fetch_assoc($result);
$result = array();
$result["id"] = $row["id"];
$result["peerID"] = $row["peerID"];
$result["name"] = $row["name"];

You could just do:

$row = mysql_fetch_assoc($result);
// at the end
return $row;

Then you don't even have to change your variable name for the second statement. But consider to use meaningful variable names.

like image 124
Felix Kling Avatar answered Apr 03 '26 19:04

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!