简体   繁体   中英

Update table based on condition (While Loop)

So I am trying to update my table based on a singe parameter:

The dateEntered field must be blank.

And I want to randomly select 50 rows, and update the blank ownerID fields to "Tester"

Here is what I have:

<?php
include("includes/constants.php");
include("includes/opendb.php");



$query = "SELECT * FROM contacts WHERE dateEntered='' ORDER BY RAND() LIMIT 50";
$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_assoc($result)){
        $firstid = $row['id'];

        $query2 = mysql_query("UPDATE contacts 
                        SET ownerID = 'Tester' 
                   WHERE id = '$firstid'");

        $result2 = mysql_query($query2) or die(mysql_error());

        }

?>

It will update a single record, then quit and give me:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1

The first part that selects the records works fine, its query2 that won't update all 50 records, just one. Maybe I am writing this wrong.

mysql_query needs only one time

    $query2 = mysql_query("UPDATE contacts 
                    SET ownerID = 'Tester' 
               WHERE id = '$firstid'");

    $result2 = mysql_query($query2) or die(mysql_error());

to

    $result2 = mysql_query("UPDATE contacts 
                    SET ownerID = 'Tester' 
               WHERE id = '$firstid'");

These answers are spot on, so I will only add some additional information, and a suggestion. When you are querying mysql the first time, $query1 is being set to the result resource, which for

   $query1 = mysql_query("UPDATE contacts SET ownerID = 'Tester' WHERE id = '$firstid'");

returns a result of 1 (Boolean TRUE), which is why your second query failed, cause "1" isn't a valid mysql query string. As Greg P stated, you can fix your current script by eliminating the secondary mysql query.

However, you could improve the script entirely, and make fewer sql calls, by using this.

    <?php

    include("includes/constants.php");
    include("includes/opendb.php");

    $query = "UPDATE contacts SET owenerID='Tester' WHERE dateEntered='' ORDER BY RAND() LIMIT 50";
    $result = mysql_query($query) or die(mysql_error());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM