php: iterate recordset - easier way?
i've just changed from ASP to php and i'm a bit confused about the way php is handling recordsets. i'd like to know if there's an easier way to iterate a recordset by creating a php class. he开发者_StackOverflow中文版re's the ASP syntax to show what i mean:
sq = "select * from myData"
set rs = db.execute(sq)
do while not rs.eof
response.write rs("name") // output data (response.write = echo)
rs.movenext
loop
any ideas? thanks
You'd pretty much do the same thing...
$sql = "select * from myData";
$result = mysql_query($sql) or die(mysql_error()); //executes query
while($row = mysql_fetch_array($result)){ //will automatically return false when out of records
echo $row['name'];
}
You're probably looking for a function contains word fetch
in it's name.
E.g. mysql_fetch_assoc()
or $pdo->fetchAll()
.
Most of database API functions in PHP returns some sort of pointer variable called "resource", which can be passed to the fetch-family function, like this:
$res = mysql_query();
while($row = mysql_fetch_assoc($res)){
echo $row['name'];
}
However, some of them (like PDO's fetchAll method) returns but regular PHP array, which you can iterate using as regular foreach
operator.
精彩评论