Tuesday, 16 July 2013

Using PHP to access MySQL database

After we have setup the Apache httpd and php environment, we can write php script to access the MySQL database.

For example, we can build a MySQL database upfront. Then we use a php script to display the data items in the browser.

An example php script to do this. eg: display_worker.php

<?PHP

$user_name = "root";
$password = "xxxxxx";
$database = "dummyonly";
$server = "localhost";

$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);

if ($db_found) {

$SQL = "SELECT * FROM worker";
$result = mysql_query($SQL);

print "<table border=\"1\" style=\"border:1px solid black;\" cellspacing=\"2\" cellpadding=\"4\">";
print "<tr>";

print "<td>";
print "name<BR>";
print "birth<BR>";
print "skill<BR>";
print "</td>";

while ( $db_field = mysql_fetch_assoc($result) ) {

print "<td>";
print $db_field['name'] . "<BR>";
print $db_field['birth'] . "<BR>";
print $db_field['skill'] . "<BR>";
print "</td>";

}
print "</tr>";
print "</table>";

mysql_close($db_handle);

}
else {

print "Database NOT Found ";
mysql_close($db_handle);

}

?>

We can also use a php script to insert new data to the database.

Firstly, we need the HTML form. eg: insert_worker.html

<html>
<body>

<form action="insert_worker.php" method="post">
Name: <input type="text" name="name">
Birthdate: <input type="text" name="birth">
Skill: <input type="text" name="skill">
<input type="submit">
</form>

</body>
</html>

Then, the php script to insert new data. eg: insert_worker.php

<?php

$user_name = "root";
$password = "xxxxxx";
$database = "dummyonly";
$server = "localhost";

$db_handle = mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database, $db_handle);

if ($db_found) {

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$sql="INSERT INTO worker (name, birth, skill)
VALUES
('$_POST[name]','$_POST[birth]','$_POST[skill]')";

if (!mysql_query($sql))
  {
  die('Error: ' . mysql_error($db_handle));
  }
echo "1 record added";

mysql_close($db_handle);

}

?>

No comments:

Post a Comment