Here is my code:

$sql = <<<END
Select Sum(p)/Sum(w)*100 as present FROM attendance group by month
$query = mysql_query($sql) or die($sql . ' - ' . mysql_error());
$names = array();
while ($row = mysql_fetch_array($query)) {
   $names[] = $row[0];
  • \$\begingroup\$ Don't use mysql_* functions, are deprecated. Use mysqli_* or PDO. \$\endgroup\$
    – geomo
    Mar 3, 2014 at 16:28
  • \$\begingroup\$ @geomo I know that I shouldn't. As I understand mysql_function better, so I use it. However there might be time when I must move to PDO or mysqli. \$\endgroup\$
    – Mawia HL
    Mar 3, 2014 at 16:31
  • 2
    \$\begingroup\$ @MawiaHL: That time has come... that time was yesterday, to be honest. It's been three years(!) since mysql_* was first put up for deprecation, and not a moment too soon. Saying you're reluctant to change because the old extension feels familiar is understandable, but that attitude is like us still living in caves, because it felt familiar to our cave-men ancestors. Moving with the times is what gets you ahead \$\endgroup\$ Mar 4, 2014 at 9:37

1 Answer 1


Regardless of how well you know the mysql_* functions, you shouldn't use them. There are counterparts within PDO. See this answer on stackoverflow for why.

This is how you'd do that in PDO:

$db = new PDO("mysql:localhost;dbname=database", $user, $password);

// set the default for ->fetch() and ->fetchAll() to associative array
// throw an exception instead of an error on fail

try {
    $sql = "(select sum(p) / sum(w) * 100) as present from attendance group by month";

    // make sure you have php5-mysqlnd installed.
    // (MySQL native driver. It makes upgrading PHP easy as there's no library conflicts).
    // You can also work with different versions of MySQL without errors.
    $names = $db->query($sql)->fetchAll();

    // array_column will take an associative array and a key and flatten it into an array
    return array_column($names, "present");
} catch (PDOException $e) {
    echo "<pre>" . $e->getTraceAsString() . "</pre>";

For error-handling, you should really use exceptions. Otherwise, check the value of $db->errorInfo()


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.