0
6.8kviews
Write a program to accept username and password field from user in form, store and display it using PHP-MySQL.
1 Answer
written 6.2 years ago by | • modified 6.2 years ago |
<!DOCTYPE html>
<html>
<head>
<title>PHP Form</title>
</head>
<body>
<?php
if(isset($_POST['submit'])) {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// sql to create table
$sql = "CREATE TABLE MyUsers (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
username VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL,
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyUsers created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
// Get values from form
$name=$_POST['name'];
$lastname=$_POST['lastname'];
$username=$_POST['username'];
$password=$_POST['password'];
// Insert data into mysql
$sql="INSERT INTO MyUsers (firstname, lastname, username, password)VALUES('$name', '$lastname', '$username', '$password')";
if (mysqli_query($conn, $sql)) {
echo "New user data inserted successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Display data
$sql = "SELECT id, firstname, lastname, username, password FROM MyUsers";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) { // output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]." - USERNAME: " . $row["username"]. " PASSWORD: " . $row["password"]."<br>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
}else {
?>
<Center>
<form name="form1" method="post" action = "<?php $_PHP_SELF ?>">
<h1>Insert Data Into MySQL Database </h1></td>
Name : <input name="name" type="text" id="name"><br><br>
Lastname : <input name="lastname" type="text" id="lastname"><br><br>
Username : <input name="username" type="text" id="username"><br><br>
Password: <input name="password" type="text" id="password"><br><br>
<input type="submit" name="Submit" value="Submit">
</form></center>
<?php
}
?>
</body>
</html>