0

I've been working on a OOP method that is supposed to return the rows of a MySQL query. I have to have the data array in the format:

$rows = array('row'=> rownum, 'fld1'=> fldval .... 'fldn' => fldval);

What I have encountered are the two problems of either:

returns

$rows = array('0'=>fldval, 'fld1'=> fldval .... 'n'=> fldval, 'fldn' => fldval);

or single row of

$rows = array('fld1'=> fldval .... 'fldn' => fldval);

Little frustrated as every PHP mysql function I have tried has some sort to goofy crap flaw and will not do a straight out process.

I assume there is a good example somewhere, that can get me past the crap limitations, but haven't found anything useful yet!

I've tried all of the following:

$row = mysql_result($db_res,$n);
$row = mysql_fetch_array($db_res);
$row = mysql_fetch_assoc($db_res);
$row = mysql_fetch_object($db_res);
$row = mysql_fetch_row($db_res);  

None have worked successfully! For getting out the bogus "numeric" array entries. I wrote:

foreach ($row as $k => $v)
   if (is_numeric($k)) { continue; }
   $result[$k] = $v;
}  // end foreach $row
$row = array_push($row, 'row'=>$rownum, $result);

Hoping someone has a link.

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
OldManRiver
  • 128
  • 1
  • 6
  • 3
    You should stop using `mysql_*` functions. They're being deprecated. Instead use [PDO](http://php.net/manual/en/book.pdo.php) (supported as of PHP 5.1) or [mysqli](http://php.net/manual/en/book.mysqli.php) (supported as of PHP 4.1). If you're not sure which one to use, [read this SO article](http://stackoverflow.com/questions/13569/mysqli-or-pdo-what-are-the-pros-and-cons). – Matt Aug 02 '12 at 20:51
  • 2
    Please, don't use `mysql_*` functions to write new code. They are no longer maintained and the community has begun [deprecation process](http://goo.gl/KJveJ). See the *[red box](http://goo.gl/GPmFd)*? Instead you should learn about [prepared statements](http://goo.gl/vn8zQ) and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you can't decide which, [this article](http://goo.gl/3gqF9) will help you. If you pick PDO, [here is good tutorial](http://goo.gl/vFWnC). – Madara's Ghost Aug 02 '12 at 20:53
  • 1
    What crap limitations? mysql_fetch_array returns both numeric+string keyed array. mysql_fetch_assoc only string, and mysql_fetch_row only numeric. They only ever return a single row. You need to fetch in a loop to retrieve the rows. Reading the documentation would've told you this. – Marc B Aug 02 '12 at 21:00

1 Answers1

2
$list = array();
$query = "SELECT value FROM table";
$resource = mysql_query($query);
while($row = mysql_fetch_assoc($resource))
{
   $list['fld' . (1 + count($list))] = $row['value'];
}
$list = array('row' => count($list)) + $list;

if table have 3 row, the code above is going to give you a array like:

array(
    'row' => 3,
    'fld1' => 12,
    'fld2' => 34,
    'fld3' => 56
);
Puggan Se
  • 5,738
  • 2
  • 22
  • 48