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.

3
  • 3
    You should stop using mysql_* functions. They're being deprecated. Instead use PDO (supported as of PHP 5.1) or mysqli (supported as of PHP 4.1). If you're not sure which one to use, read this SO article. Commented Aug 2, 2012 at 20:51
  • 2
    Please don't use mysql_* functions in new code. They were removed from PHP 7.0.0 in 2015. Instead, use prepared statements via PDO or MySQLi. See Why shouldn't I use mysql_* functions in PHP? for more information. Commented Aug 2, 2012 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. Commented Aug 2, 2012 at 21:00

1 Answer 1

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
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.