Sample Code

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Create PHP form and check for validation which includes username,

password and email.

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
/* define variables and set to empty values */
$nameErr = $emailError = $mobileError ="";
$name = $email = $mobile = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
}
else {
$name = test_input($_POST["name"]);
/* check if name only contains letters and whitespace */
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["name"])) {
$mobileError = "Name is required";
} else {
$mobile = test_input($_POST["mobile"]);
/* check if name only contains letters and whitespace */
if (!preg_match('/^[0-9]{10}+$/', $mobile)) {
$mobileError = "10 digit Number";
}
}
if (empty($_POST["email"])) {
$emailError = "Email is required";
} else {
$email = test_input($_POST["email"]);
/* check if e-mail address is well-formed */
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailError = "Invalid email format";
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Mobile: <input type="text" name="mobile" value="<?php echo $mobile;?>">
<span class="error">* <?php echo $mobileError;?></span>
<br><br>
E-mail: <input type="text" name="email" value="<?php echo $email;?>">
<span class="error">* <?php echo $emailError;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>

What is CRUD?

CRUD refers to the four basic types of Database operations: Create, Read, Update, Delete. Most
applications and projects perform some kind of CRUD functionality. Once you learn about these
CRUD operations, you can use them for many projects. For an example, if you learn how to
create student table with multiple columns, you can use similar approach to create employee
table or customers table.

1) Write a PHP script to create login page with SQL database connectivity
Login1.php
<html>
<head>
<title>PHP login system</title>
<link rel = "stylesheet" type = "text/css" href = "style.css">
</head>
<body>
<div id = "frm">
<h1>Login</h1>
<form name="f1" action = "authentication.php" onsubmit = "return validation()" method =
"POST">
<p>
<label> UserName: </label>
<input type = "text" id ="user" name = "user" />
</p>
<p>
<label> Password: </label>
<input type = "password" id ="pass" name = "pass" />
</p>
<p>
<input type = "submit" id = "btn" value = "Login" />
</p>
</form>
</div>
// validation for empty field
<script>
function validation()
{
var id=document.f1.user.value;
var ps=document.f1.pass.value;
if(id.length=="" && ps.length=="") {
alert("User Name and Password fields are empty");
return false;
}
else
{
if(id.length=="") {
alert("User Name is empty");
return false;
}
if (ps.length=="") {
alert("Password field is empty");
return false;
}
}
}
</script>
</body>
</html>

connection.php
<?php
$host = "localhost";
$user = "root";
$password = '';
$db_name = "logindb";

$con = mysqli_connect($host, $user, $password, $db_name);


if(mysqli_connect_errno()) {
die("Failed to connect with MySQL: ". mysqli_connect_error());
}
?>

Authentication.php
<?php
include('connection.php');
$username = $_POST['user'];
$password = $_POST['pass'];

//to prevent from mysqli injection


$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysqli_real_escape_string($con, $username);
$password = mysqli_real_escape_string($con, $password);

$sql = "select *from login where username = '$username' and password = '$password'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);

if($count == 1){
echo "<h1><center> Login successful </center></h1>";
}
else{
echo "<h1> Login failed. Invalid username or password.</h1>";
}
?>

2) Write a php script to retrieve student data from MySQL database using PHP CRUD
Operation

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "studentdb";

// connect the database with the server


$conn = new mysqli($servername,$username,$password,$dbname);

// if error occurs
if ($conn -> connect_errno)
{
echo "Failed to connect to MySQL: " . $conn -> connect_error;
exit();
}

$sql = "select * from student";


$result = ($conn->query($sql));
//declare array to store the data of database
$row = [];

if ($result->num_rows > 0)
{
// fetch all data from db into array
$row = $result->fetch_all(MYSQLI_ASSOC);
}
?>

<!DOCTYPE html>
<html>
<style>
td,th {
border: 1px solid black;
padding: 10px;
margin: 5px;
text-align: center;
}
</style>

<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Branch</th>
<th>Roll Number</th>
</tr>
</thead>
<tbody>
<?php
if(!empty($row))
foreach($row as $rows)
{
?>
<tr>

<td><?php echo $rows['name']; ?></td>


<td><?php echo $rows['branch']; ?></td>
<td><?php echo $rows['rollno']; ?></td>

</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>

<?php
mysqli_close($conn);
?>
3) Write a php script display name, mobileno, email address and perform CRUD
operation using SQL database

Form.php
<?php
// Create database connection using config file
include_once("connect.php");

// Fetch all users data from database


$result = mysqli_query($mysqli, "SELECT * FROM users ORDER BY id DESC");
?>

<html>
<head>
<title>Homepage</title>
</head>

<body>
<a href="add.php">Add New User</a><br/><br/>

<table width='80%' border=1>

<tr>
<th>Name</th> <th>Mobile</th> <th>Email</th> <th>Update</th>
</tr>
<?php
while($user_data = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$user_data['name']."</td>";
echo "<td>".$user_data['mobile']."</td>";
echo "<td>".$user_data['email']."</td>";
echo "<td><a href='edit.php?id=$user_data[id]'>Edit</a> | <a href='delete.php?
id=$user_data[id]'>Delete</a></td></tr>";
}
?>
</table>
</body>
</html>

Connect.php
<?php
/**
* using mysqli_connect for database connection
*/

$databaseHost = 'localhost';
$databaseName = 'crud_db';
$databaseUsername = 'root';
$databasePassword = '';

$mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword,


$databaseName);

?>

Add.php
<html>
<head>
<title>Homepage</title>
</head>

<body>
<a href="add.php">Add New User</a><br/><br/>

<table width='80%' border=1>

<tr>
<th>Name</th> <th>Mobile</th> <th>Email</th> <th>Update</th>
</tr>
<?php
while($user_data = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$user_data['name']."</td>";
echo "<td>".$user_data['mobile']."</td>";
echo "<td>".$user_data['email']."</td>";
echo "<td><a href='edit.php?id=$user_data[id]'>Edit</a> | <a href='delete.php?
id=$user_data[id]'>Delete</a></td></tr>";
}
?>
</table>
</body>
</html>

<html>
<head>
<title>Add Users</title>
</head>
<body>
<a href="form.php">Go to Home</a>
<br/><br/>

<form action="add.php" method="post" name="form1">


<table width="25%" border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Add"></td>
</tr>
</table>
</form>

<?php

// Check If form submitted, insert form data into users table.


if(isset($_POST['Submit'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$mobile = $_POST['mobile'];

// include database connection file


include_once("connect.php");

// Insert user data into table


$result = mysqli_query($mysqli, "INSERT INTO users(name,email,mobile)
VALUES('$name','$email','$mobile')");

// Show message when user added


echo "User added successfully. <a href='form.php'>View Users</a>";
}
?>
</body>
</html>

Edit.php
<?php
// include database connection file
include_once("connect.php");
// Check if form is submitted for user update, then redirect to homepage after update
if(isset($_POST['update']))
{
$id = $_POST['id'];

$name=$_POST['name'];
$mobile=$_POST['mobile'];
$email=$_POST['email'];

// update user data


$result = mysqli_query($mysqli, "UPDATE users SET
name='$name',email='$email',mobile='$mobile' WHERE id=$id");

// Redirect to homepage to display updated user in list


header("Location: form.php");
}
?>
<?php
// Display selected user data based on id
// Getting id from url
$id = $_GET['id'];

// Fetech user data based on id


$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while($user_data = mysqli_fetch_array($result))
{
$name = $user_data['name'];
$email = $user_data['email'];
$mobile = $user_data['mobile'];
}
?>
<html>
<head>
<title>Edit User Data</title>
</head>
<body>
<a href="form.php">Home</a>
<br/><br/>

<form name="update_user" method="post" action="edit.php">


<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value=<?php echo $name;?
>></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value=<?php echo $email;?
>></td>
</tr>
<tr>
<td>Mobile</td>
<td><input type="text" name="mobile" value=<?php echo
$mobile;?>></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo
$_GET['id'];?>></td>
<td><input type="submit" name="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>

Delete.php
<?php
// include database connection file
include_once("connect.php");

// Get id from URL to delete that user


$id = $_GET['id'];

// Delete user row from table based on given id


$result = mysqli_query($mysqli, "DELETE FROM users WHERE id=$id");

// After delete redirect to Home, so that latest user list will be displayed.
header("Location:form.php");
?>

You might also like