Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Konrad Pilch
Konrad Pilch
2,435 Points

PHP mysqli_fetch_assoc . I dont get this code

HI,

<div id="shoutss">
                <ul>
                    <?php while($row = mysqli_fetch_assoc($shouts)) : ?>
                        <li class="shout">
                            <span><?php echo $row['time'] ?> - </span><strong><?php echo $row['user'] ?>:</strong> <?php echo $row['message'] ?>
                        </li>
                    <?php endwhile; ?>
                </ul>
            </div><!-- /shouts -->

I do understand all the code here apart from

($row = mysqli_fetch_assoc($shouts))

I dont get this , what does it do? i did research but i coudnt find it .

Konrad Pilch
Konrad Pilch
2,435 Points

Oh as well as this

mysqli_real_escape_string

And $con stands for the code where the database is connection.

1 Answer

mysqli_fetch_assoc() is a function that fetches a result row in a associative array.

$shouts = mysqli_query($connect, "SELECT * FROM user WHERE firstname='someone' lastname='myname' "); //This will run a query against mysql database. it will request the row with user = someone and password = password.

while ($row = mysqli_fetch_assoc($shouts)) // mysqli_fetch_assoc() will fetches result row in an associative array and its value will be assigned to $row like $row['firstname'] will be someone and $row['lastname'] will be myname. This is helpfull when the are multiple results.

For example - Suppose you have 3 rows with same information where firstname='someone' lastname='myname' but different id in this case you have to use while loop and mysqli_fetch_assoc(). So, that you can loop through each array. In first loop the $row['id'] could be 1, In second loop it could be 2 and in third it could be something else.

This could be bit complicated in the beginning.

Konrad Pilch
Konrad Pilch
2,435 Points

Thank you!

I get it better now. I saw that there are a lot fo these kind of long commands : p .

They should make an documentation from treehouse that assigns this answer, in this case your answer to the command yo udescribed : p that way this would be very easy : p