简体   繁体   中英

PHP updating large database

I have a large database (28k entries in this particular table one table) and I need to append some HTML tags to the front and back of every column in a table.

Here is my code:

try
{
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    if(!$conn)
    {
        echo "Error in connecting to the database.";
    }
    $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );  

    $query = $conn->query("SELECT `id`, `introtext` FROM *TABLE* WHERE id >= 41155");
    $query->setFetchMode(PDO::FETCH_OBJ);

    //For each row in the table
    while($row = $query->fetch())
    {
        $introtext = '<span class="*SPAN CLASS*">' . $row->introtext . '</span>';
        $update_query = $conn->prepare("UPDATE *TABLE* SET introtext = ? WHERE id = ?");

        if ($query->execute(array($introtext, $row->id))) 
            echo $row->id . " Done <br>";
        else 
            echo $row->id . " Err<br>";
    }

} catch(PDOexception $e) {
    echo $e->getMessage();
}

$conn = null;

When I run the script, it outputs 41155 Done 4132 times. I'm not sure the logic here, but any help to get this working is appreciated.

I agree with Dagon that the database is not the place for that (what if tomorrow you decide that <span> should wrap another HTML tag?).

Anyway, it sounds like a one-time operation, so I wouldn't use PHP. Just run a MySQL client (the command line mysql , or Workbench, and use a query like this:

UPDATE *TABLE* 
SET introtext = CONCAT('<span class="*SPAN CLASS*">', introtext, '</span>') 
WHERE id >= 41155

One note about your current code: you're never executing the UPDATE query! You just prepare the statement, then instead of executing $update_query , you're executing $query again! That's why you're always printing the same id.

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