| |
|
Created: Oct 28, 2008 |
By: Adam Khoury |
Views: 128 |
Here are PHP & MySQL code examples on the various ways you can select data from your database. You can run certain operations within your SQL statements to create specific result sets.
| Here is a standard select all [*] from a database table |
<?php
// First connect to your database, we have a lesson on that too here // Now make the query // Select all and count the number of rows in the result set $sql = mysql_query("SELECT * FROM table_name"); $rowCount = mysql_num_rows($sql); // Print the amount of rows that are in the table print "$rowCount ";
?>
|
|
| |
| |
| Here we are building a result set to display only countries that people are from. Then we take it a step further and find the number count for each country that happens to be in the list we loop through below and order by highest to lowest on the html page. |
<?php
// Make the query $sql = mysql_query("SELECT count(user_country) as countryCount, user_country FROM table_name GROUP by user_country order by countryCount DESC"); // Initiate the $countries variable $countries = ""; // Begin the while loop to iterate through all result sets while($row = mysql_fetch_array($sql)){ // Place the row value into a local php variable $user_country = $row["user_country"]; $sqlCountryCount = mysql_query("SELECT * FROM table_name WHERE user_country ='$user_country'"); // Get the count for this country running through the loop right now $countryCount = mysql_num_rows($sqlCountryCount); // Place each country name and count running through the loop right now into my $countries // variable which can be easily displayed in our HTML sections of the web page $countries .= "$user_country has $countryCount members<br />"; } // The result is a list from highest to lowest with country name and table row count // Print it to the page print "$countries";
?>
|
|
|
|
|