· 5 years ago · Oct 13, 2020, 08:12 AM
1<?php include "../inc/dbinfo.inc"; ?>
2<html>
3 <body>
4 <h1>Sample page</h1>
5 <?php
6/* Connect to MySQL and select the database. */
7$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
8
9if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
10$database = mysqli_select_db($connection, DB_DATABASE); /* Ensure that the EMPLOYEES table exists. */
11VerifyEmployeesTable($connection, DB_DATABASE); /* If input fields are populated, add a row to the EMPLOYEES table. */
12$employee_name = htmlentities($_POST['NAME']);
13$employee_address = htmlentities($_POST['ADDRESS']);
14if (strlen($employee_name) || strlen($employee_address))
15{
16 AddEmployee($connection, $employee_name, $employee_address);
17}
18
19?>
20
21<form action="<?PHP echo $_SERVER['SCRIPT_NAME'] ?>" method="POST"> <table border="0"> <tr> <td>NAME</td> <td>ADDRESS</td> </tr> <tr> <td> <input type="text" name="NAME" maxlength="45" size="30" /> </td> <td> <input type="text" name="ADDRESS" maxlength="90" size="60" /> </td> <td> <input type="submit" value="Add Data" /> </td> </tr> </table> </form> <!-- Display table data. --> <table border="1" cellpadding="2" cellspacing="2"> <tr> <td>ID</td> <td>NAME</td> <td>ADDRESS</td> </tr>
22
23<?php
24$result = mysqli_query($connection, "SELECT * FROM EMPLOYEES");
25
26while ($query_data = mysqli_fetch_row($result))
27{
28 echo "<tr>";
29 echo "<td>", $query_data[0], "</td>", "<td>", $query_data[1], "</td>", "<td>", $query_data[2], "</td>";
30 echo "</tr>";
31} ?>
32
33</table>
34
35<!-- Clean up. --> <?php mysqli_free_result($result);
36mysqli_close($connection); ?> </body> </html> <?php /* Add an employee to the table. */
37function AddEmployee($connection, $name, $address)
38{
39 $n = mysqli_real_escape_string($connection, $name);
40 $a = mysqli_real_escape_string($connection, $address);
41 $query = "INSERT INTO EMPLOYEES (NAME, ADDRESS) VALUES ('$n', '$a');";
42 if (!mysqli_query($connection, $query)) echo ("<p>Error adding employee data.</p>");
43} /* Check whether the table exists and, if not, create it. */
44function VerifyEmployeesTable($connection, $dbName)
45{
46 if (!TableExists("EMPLOYEES", $connection, $dbName))
47 {
48 $query = "CREATE TABLE EMPLOYEES ( ID int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY, NAME VARCHAR(45), ADDRESS VARCHAR(90) )";
49 if (!mysqli_query($connection, $query)) echo ("<p>Error creating table.</p>");
50 }
51}
52
53function TableExists($tableName, $connection, $dbName)
54{
55 $t = mysqli_real_escape_string($connection, $tableName);
56 $d = mysqli_real_escape_string($connection, $dbName);
57 $checktable = mysqli_query($connection, "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = '$t' AND TABLE_SCHEMA = '$d'");
58 if (mysqli_num_rows($checktable) > 0) return true;
59 return false;
60} ?>
61