JWally
JWally

Reputation: 592

Get Fetch_Assoc results by numerical index

Is there a way to access the results of 'fetch_assoc()'
by number? For instance, I'd expect the following to give me

1.) Array
2.) 25
3.) 'First Element'
Instead, it throws the following error:

Notice: Undefined offset: 0 in C:\xampp\htdocs_notesale\index.php on line 22

Any idea how to do this?
thanks
JW

<?php
$db = new mysqli('CONN','USER','PW','DB');
$rs = $db->query("SELECT * FROM `checklist`");
$r_count = $rs->num_rows;
$c_count = $rs->field_count;

?> ...

    <?php
        for($i=0;$i<$r_count;$i++)
        {
        $row = $rs->fetch_assoc();
        echo "<tr>";
            echo "1 - ".$row."<br />";
            echo "2 - ".count($row)."<br />";
            echo "3 - ".$row[0]."<br />";
            echo "</tr>";
            }
        ?>

Upvotes: 1

Views: 3998

Answers (3)

wsher
wsher

Reputation: 21

This would be helpful for "looking ahead" at the next/upcoming row that WILL be fetched in the next WHILE loop iteration. It's useful at the end of a while iteration to see if the current iteration is the last of a group and then print a footer or subtotal before proceeding with the rest of the Results

Upvotes: 0

Mark Baker
Mark Baker

Reputation: 212522

$row = $rs->fetch_assoc(); 
$keys = array_keys($row);
echo $row[$keys[0]];

Though why you want to retrieve assoc and then access by numeric key escapes me

Upvotes: 1

DaveRandom
DaveRandom

Reputation: 88697

You have called fetch_assoc(), and yet expect the result to be indexed?

Try fetch_row() or fetch_array()

Upvotes: 4

Related Questions