Monday, December 21, 2015

Access and show content of a database in MySQL with PHP

This post shows how to access a database in MySQL and print the data of the database on a PHP web page:

1. Make sure that Apache+MySQL+PHP (LAMP) and phpMyAdmin have been installed.


3. Create the fruit.php file with this command:

sudo nano /var/www/fruit.php

4. Edit and save the file as below:

<html><head><title>Fruit</title></head>
<body>
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";

$connection = mysql_connect($servername, $username, $password) or die("No MySQL Connection: " . mysql_error());

print "MySQL Connection OK";
mysql_select_db("mydatabase", $connection) or die("<br>No Database: " . mysql_error());

print "<br>Database OK";

$query = "select * from fruit";
$result = mysql_query($query) or die("<br>Query Error: " . mysql_error());

$FieldTotal = mysql_num_fields($result);

print "<P>There are $FieldTotal columns in the table.</P>";
print "<Table border=1><tr align=center>";

//loop through column names
for ($count = 0; $count < $FieldTotal; $count++) {
    $field = mysql_fetch_field($result, $count) or die("Field error!");    
    print "<td width=120>$field->name</td>";
}
print "</tr>";
$RowTotal = mysql_num_rows($result);

//loop through rows
for ($RowCount = 0; $RowCount < $RowTotal; $RowCount++) {
    print "<tr align=center>";
    $row = mysql_fetch_row($result) or die("Row error!");

    //loop through columns
    for ($ColCount = 0; $ColCount < $FieldTotal; $ColCount++) {
        print "<td>$row[$ColCount]</td>";
    }
    print "</tr>";
}
print "</table>";

print "<br>end";
?>
</body></html>

5. Use the browser to open this URL:

http://192.168.xx.xx/fruit.php

The result:


Reference:

No comments:

Post a Comment