retrieving data from mysql using php

Questions about other topics - please check if your question fits better in another category before posting here
Forum rules
Before you post please read how to get help
Post Reply
karuga
Level 3
Level 3
Posts: 113
Joined: Wed May 12, 2010 1:49 am

retrieving data from mysql using php

Post by karuga »

Look at this code. It picks some data from a mySQL table called Persons of the database my_db

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("my_db", $con);

$result = mysql_query("SELECT * FROM Persons");

while($row = mysql_fetch_array($result))

{
echo $row['FirstName'] . " " . $row['LastName'];
echo "<br />";
}

mysql_close($con);
?>
// the above code retrieves data nicely from a database,however unexpected happens when i do this:

while($row = mysql_fetch_array(mysql_query("SELECT * FROM Persons")))

The code picks the first entry in the database and the loop to infinity,each time picking the first value. Are these statements not the same? Please make me understand what is happening.

User avatar
xenopeek
Level 24
Level 24
Posts: 24518
Joined: Wed Jul 06, 2011 3:58 am
Location: The Netherlands

Re: retrieving data from mysql using php

Post by xenopeek »

You could visit PHP forums instead: http://www.phphelp.com/forum/index.php.

As far as I understand PHP, the change you do makes PHP rerun the mysql_query each iteration of mysql_fetch_array. So restarting it each iteration, so yes an infinite loop from which you only get the first row of the query. The PHP example code has a static mysql_query stored in $result, so each iteration gets the next row.
Last edited by xenopeek on Fri Aug 05, 2011 5:12 am, edited 1 time in total.
Image

User avatar
Oscar799
Level 19
Level 19
Posts: 9924
Joined: Tue Aug 11, 2009 9:21 am
Location: United Kingdom

Re: retrieving data from mysql using php

Post by Oscar799 »

Moved here from Code & Patches
Image

User avatar
DataMan
Level 6
Level 6
Posts: 1234
Joined: Thu Dec 04, 2008 6:47 am
Location: Carmel, Midwest USA at /var/www
Contact:

Re: retrieving data from mysql using php

Post by DataMan »

Basically your "while statement is iterating based on the populated array from the query. In your second example, you have not populated the array beyond the initialization (1st record).

Stay with the conventional approach (1st example). There are limits to code smashing and compacting... :lol: .

-DataMan
Linux'd since 2005 Linux ID 422356 Ubuntu ID 15015

Post Reply

Return to “Other topics”