web4.cs.universityofgalway.ie

Home
This php code connects to a local MySQL database server and retrieves records
MySQL Server:localhost
Database:Southwind
Company nameContact NameTitleCity
Alfreds Futterkiste JnrMaria AndersSales RepresentativeBerlin
Ana Trujillo Emparedados y heladosAna TrujilloOwnerMéxico D.F.
Antonio Moreno TaqueríaAntonio MorenoOwnerMéxico D.F.
Around the HornThomas HardySales RepresentativeLondon
Berglunds snabbköpChristina BerglundOrder AdministratorLuleå
Blauer See DelikatessenHanna MoosSales RepresentativeMannheim
Blondesddsl père et filsFrédérique CiteauxMarketing ManagerStrasbourg
Bólido Comidas preparadasMartín SommerOwnerMadrid
Bon app'Laurence LebihanOwnerMarseille
Bottom-Dollar MarketsElizabeth LincolnAccounting ManagerTsawassen

The PHP Code for the above is shown below


<h2><?php print $_SERVER["HTTP_HOST"]; ?></h2>
<a href="/">Home</a><br />
<?php
// variables to hold the MySQL details
$db_server "localhost";
$db_name "Southwind";
$db_user "";
$db_pass "";


print(
"This php code connects to a local MySQL database server and retrieves records<br />");
print(
"MySQL Server:" $db_server."<br/>");
print(
"Database:".$db_name."<br/>");

// initialise the MySQL driver 
$mysqli = new mysqli($db_server,$db_user,$db_pass,$db_name);
// attempt a connection - if it fails print the error
if ($mysqli->connect_errno) {
    echo 
"Failed to connect to MySQL: (" $mysqli->connect_errno ") " $mysqli->connect_error;
}

// the SQL statement
$sql "SELECT CompanyName,ContactName,ContactTitle,City FROM Customers limit 10";

// Use the statment to query the MySQL server and retrive the result
$result $mysqli->query($sql);

// check if the result has any results/records
if (mysqli_num_rows($result) > 0) {
    
// use a simple table to display the data
    
printf("<table border=1><tr><td>Company name</td><td>Contact Name</td><td>Title</td><td>City</td></tr>");
    
// while there is a record to fetch, display its contents in the table
    
while ($myrow $result->fetch_assoc()) {
        
printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>"$myrow["CompanyName"], $myrow["ContactName"], $myrow["ContactTitle"], $myrow["City"]);
    }
    
/* free result set */
    
$result->free();

    
printf("</table>");
}

/* close connection */
$mysqli->close();

?>