· 6 years ago · Nov 06, 2019, 10:48 AM
1<?php
2$host = "localhost";
3$username = "sylvia";
4$password = "sylvia2424";
5$dbname="sly";
6
7// Create connection
8$conn = mysqli_connect($host, $username, $password, $dbname);
9
10// Check connection
11
12if (!$conn) {
13 die("Connection failed: " . mysqli_connect_error());
14}
15//create a table
16$sql = "CREATE TABLE IF NOT EXISTS user (
17id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
18firstname VARCHAR(30) NOT NULL,
19lastname VARCHAR(30) NOT NULL,
20email VARCHAR(50),
21reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
22)";
23mysqli_query($conn, $sql);
24$firstname='';
25$lastname='';
26$email='';
27$reg_date='';
28
29
30 // die("Sylvia: ".json_encode($_POST));
31// REGISTER USER
32// insert data
33if (isset($_POST['submit'])) {
34 // receive all input values from the form
35 $firstname = mysqli_real_escape_string($conn, $_POST['Firstname']);
36 $lastname = mysqli_real_escape_string($conn, $_POST['Lastname']);
37 $email = mysqli_real_escape_string($conn, $_POST['email']);
38 $reg_date = mysqli_real_escape_string($conn, $_POST['reg_date']);
39
40 // form validation: ensure that the form is correctly filled ...
41 // by adding (array_push()) corresponding error unto $errors array
42 if (empty($firstname)) { array_push($errors, "firstname is required"); }
43 if (empty($lastname)) { array_push($errors, "lastname is required"); }
44 if (empty($email)) { array_push($errors, "email is required"); }
45 if (empty($reg_date)) { array_push($errors, "reg_date require");}
46
47
48
49 $query = "INSERT INTO user (firstname, lastname, email, reg_date)
50 VALUES('$firstname', '$lastname', '$email', '$reg_date')";
51
52if (mysqli_query($conn, $query))
53{
54 echo "user registered ";
55} else {
56 echo "Error: " . mysqli_error($conn);
57}
58}
59
60//use this for selecting data and creating a table
61$db = "SELECT id, Firstname, email FROM user";
62$result = mysqli_query($conn, $db);
63include'style.css';
64if (mysqli_num_rows($result) > 0)
65{
66 echo "<table>";
67 echo "<tr>";
68 echo "<th>id</th>";
69 echo "<th>firstname</th>";
70 echo "<th>email</th>";
71 echo "</tr>";
72 while($row = mysqli_fetch_array($result)){
73 echo "<tr>";
74 echo "<td>" . $row['id'] . "</td>";
75 echo "<td>" . $row['Firstname'] . "</td>";
76 echo "<td>" . $row['email'] . "</td>";
77 echo "</tr>";
78 }
79 echo "</table>";
80 }
81 else{
82 echo "0 results";
83 }
84 //use this code when displaying selected items without the table
85 // output data of each row
86 //while($row = mysqli_fetch_assoc($result)) {
87 //echo "id: " . $row["id"]. " - Name: " . $row["Firstname"]. " " . $row["email"]. "<br>";
88 //}
89//} else {
90 //echo "0 results";
91//}
92
93mysqli_close($conn);
94?>