Vocademy

PHP and MySQL Tips and Hacks

Renumber the primary index

SET @i=0;
UPDATE table_name SET column_name=(@i:=@i+1);

Using PDO in the same style as mysql_

If you need to convert a page from the defunct mysql_ method of communicating with a MySQL database to the PDO method, the following example shows how to use a similar syntax.

//The first three lines are as usual
$query = "SELECT * FROM contacts";
$stmt = $pdo->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$numrows = count($result);

for ($i = 0; $i < $numrows; $i++) {
    $name = $result[$i]['name'];
    print "$name";
}

Caveats:

Do not use $numrows = $stmt->rowCount($result);. Just use "...count($result)." Sometimes rowCount($result) returns the correct number, sometimes it returns 0, depending on the driver.

Be sure to include PDO::FETCH_ASSOC in the fetchall statement. This ensures you get the associative arrays only, which matches the old mysql behavior. Without it you may get numeric indexes.

Vocademy