I've decided to build a website for fantasy football for my family but am getting stuck with returning multiple rows from the database.
What I want: to make a single sql call and get the entire list of players so I can populate an object or list of objects. (if the whole table could be returned that would be great...). My goal is to have the list of available players to be drafted simply displayed to the user.
Currently I can somewhat see some results when testing by the following method (credit: from the php docs...). However I can't help be feel lost as to what is going on.. I can't make this make sense in my brain.
// My query
$sql = mysql_query("SELECT * FROM players");
//$data = mysql_fetch_array($sql);
while ($row = mysql_fetch_array($sql, MYSQL_NUM)) {
printf("Name: %s <br/>", $row[1]);
}
This seems to print the names of each player. However how does 'mysql_fetch_array()' iterate each row as the while loop iterates? Further, since there are multiple columns how can I access each column... does this have to be hardcoded such as:
while ($row = mysql_fetch_array($sql, MYSQL_NUM)) {
printf("Name: %s <br/>", $row[1]);
printf("Team: %s <br/>", $row[2]);
..
.
printf("Team: %s <br/>", $row[5]);
}
Eventually I will replace the print statements with code that will store relevant date in a roster object or something:
class Roster(){
$playerName;
$team;
$etc.
}
The while loop method above feels difficult and clunky. Is there a better way to access all returned rows? How would someone else attempt this? My limited experience is C# and sql server, which can do some amazing stuff with some effortless configuration... immediately return a list ^
If I'm not clear I will check back soon and comment further. I'm still a CS student. Thank you for your patience.
mysql_*
functions will be deprecated in PHP 5.5. It is not recommended for writing new code as it will be removed in the future. Instead, either the MySQLi or PDO and be a better PHP Developer. – Jason McCreary Jan 2 at 5:17