NtnRanger NtnRanger - 2 years ago 93
PHP Question

mysql_ to PDO migration issue

I'm having some issue trying to migrating from mysql_ to PDO (I'm new with it).

I've already done the most of the work, but there's a function that's driving me crazy.

Here it is:

function fields($thequery) /* SELECT * FROM table */
for ($i = 0; $i < $fields['num']; $i++) {
$fields['data'][]=mysql_fetch_field($result, $i);
return $fields;

I've tried to read some other posts but I can't figure it out.

This is the best I can at the moment, but I always get undefined index "num".

function fields($thequery)
global $pdo; /* Connection */

$result = $pdo->prepare($thequery);
$fields['num'] = $result->rowCount();
for ($i = 0; $i < $fields['num']; $i++) {
return $fields;

What am I doing wrong with this?
Thanks in advance!

Answer Source

You have a couple of problems. First, you don't declare the fields array in your second function, $fields = array();, and then you have an issue when counting the rows:


Your query is likely a SELECT query, which will not work with rowCount()

From the docs

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

For SELECT when you are not doing a COUNT() query you can return the number of rows like this after $result->execute();

$rows = $result->fetchAll();
$num_rows = count($rows);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download