"Welcome to our PHP 101 blog, where we demystify the world of web development. "

Tuesday, January 30, 2024

FORM AND DATABASE CONNECTIVITY WITH CRUD Operation (Query method)

 

FORM AND DATABASE CONNECTIVITY

With  CRUD Operations 

Using Object-Oriented type

Using Query method

Prerequisite:

Before you can test your PHP and MySQL application using XAMPP, you need to ensure that both Apache and MySQL services are running.

Here are the steps:

1.   Step 1. Start XAMPP:

  • Open the XAMPP Control Panel. You can do this by navigating to the directory where XAMPP is installed and running xampp-control.exe.

2.   Step 2:   Start Apache:

  • In the XAMPP Control Panel, find the "Apache" module.
  • Click the "Start" button next to "Apache." This will start the Apache web server.

3.   Step 3:  Start MySQL:

  • In the XAMPP Control Panel, find the "MySQL" module.
  • Click the "Start" button next to "MySQL." This will start the MySQL database server.

4.   Step 4: Verify Running Services:

  • After starting both Apache and MySQL, you should see "Running" next to their respective modules in the XAMPP Control Panel.
  • Now that Apache and MySQL are running, you can open your web browser and access your PHP application by navigating to the appropriate URL.
  • If your XAMPP installation is on your local machine, the URL might be http://localhost/your-directory/index.html,   where "your-directory" is the folder where you've placed your files.


How to create a form and connect it to the database table using php and mysql .

Step 1: Set Up Your Database

Step 2: Create a Connection Script

Step 3: Create HTML Form

Step 4: Create PHP Processing Script

Step 5: Test Your Form

 

Step 1: Set Up Your Database

 In Step 1, you'll be setting up your MySQL database, which includes creating a new database and defining a table within that database.

1.1 Create a Database:

  1. Open your MySQL management tool (like phpMyAdmin, MySQL Workbench, or use command-line interface).
  2. Once you're connected to your MySQL server, find an option to create a new database. In phpMyAdmin, there is typically a "New Database" button.
  3. Choose a name for your database, for example, let's call it mydatabase.

 

Creating a Database Using phpMyAdmin


phpMyAdmin is a web-based tool that provides a graphical interface to manage MySQL databases.

Steps to create a database using phpMyAdmin:

1. Access phpMyAdmin: Open phpMyAdmin in your web browser (typically accessed via http://localhost/phpmyadmin).





2. Select the "Databases" Tab: Click on the "Databases" tab at the top of the page.


3. Create a Database:

o In the "Create database" field, enter the name of the database you want to create. suppose here your database name is my_DB


o Click the "Create" button.


Once you click "Create," phpMyAdmin will execute the necessary SQL command to create the database.

1.2 Create a Table:

Type 1 : Creating Tables Using phpMyAdmin

phpMyAdmin provides a user-friendly interface to create tables. The steps are :

1. Access phpMyAdmin: Open phpMyAdmin in your web browser (typically accessed via http://localhost/phpmyadmin). 





2. Select the Database: Click on the database in which you want to create the table.




3. Create a Table:

o Click on the "Structure" tab if you’re not already there.


o Enter the table name and the number of columns in the "Create table" section, then click "Go".


Define the columns: name, type, length, and other attributes for each column.

o Click "Save" to create the table.



With these steps, you've created a database named my_DB and a table named myGuests within that database.

Create myGuests  table with following fields:

id int(10) Primary key

firstname varchar(255)

lastname varchar(255)

email varchar(255)

password varchar(255)

reg_date date


You can create also using SQL command:

CREATE TABLE myGuests (

    id INT(10) PRIMARY KEY AUTO_INCREMENT,

    firstname VARCHAR(255) NOT NULL,

    lastname VARCHAR(255) NOT NULL,

    email VARCHAR(255) NOT NULL,

    password VARCHAR(255) NOT NULL,

    reg_date DATE NOT NULL

);

Explanation:

id INT(10) PRIMARY KEY AUTO_INCREMENT:

Defines id as an integer that will serve as the primary key.

The AUTO_INCREMENT keyword automatically increments the value of id for each new record, ensuring it is unique.

firstname VARCHAR(255) NOT NULL:

firstname is a variable character field that can hold up to 255 characters.

NOT NULL means this field cannot be empty.

lastname VARCHAR(255) NOT NULL:

Similar to firstname, but for the last name.

email VARCHAR(255) NOT NULL:

This field stores the email addresses and also cannot be empty.

You might consider adding a UNIQUE constraint if each email should be unique across the table.

password VARCHAR(255) NOT NULL:

Stores hashed passwords; also cannot be empty.

Make sure to hash passwords before storing them for security reasons.

reg_date DATE NOT NULL:

Stores the registration date.

The myGuests table is where you'll store information about guests who submit data through your form.

 

Step 2: Create a Connection Script

In Step 2, you will create a PHP script to establish a connection to the MySQL database. This script will be responsible for connecting your PHP application to the MySQL database, allowing you to perform operations like inserting data into the database or retrieving data from it.

Before save the connection script you have to create a folder according to name of your project ,i.e; here MyGuests .So i make a folder named as myGuests in C:\\XaMPP\Htdocs\ .Save all the file inside myGuests folder.

2.1 Create a Connection Script:

Open your preferred text editor or integrated development environment (IDE).

Create a new PHP file, for example, db.php.

In this file, you'll define the necessary variables for connecting to your MySQL database, such as the server name, username, password, and database name.

FileName for connection script should be : db_connect.php/database_connect.php/config.php

Here I Save db_connect.php in  myGuests folder.

<?php

$servername = "localhost";  // Replace with your server name if different

$username = "root";         // Replace with your MySQL username

$password = "";             // Replace with your MySQL password

$dbname = "my_DB";     // Replace with your database name

// Create connection

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

// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

echo "database connected";

?> 

 Save the db_connect.php file.

Step by Step Explanation:

Step 1: Setting Up Variables

$servername = "localhost";  // Replace with your server name if different

$username = "root";         // Replace with your MySQL username

$password = "";             // Replace with your MySQL password

$dbname = "my_DB";          // Replace with your database name

$servername: This variable holds the name of the server where your MySQL database is located. localhost means your database is on the same machine as the script.

$username: This variable stores the username you use to log in to the MySQL server. The default username for many MySQL installations is root.

$password: This variable holds the password for your MySQL user. It's currently empty, which is common for local development setups, but should be set to a secure password in a production environment.

$dbname: This variable contains the name of the database you want to connect to. Here, it's set to my_DB.

Step 2: Creating the Connection

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

$conn: This variable will store the connection object created by the new mysqli() constructor.

new mysqli($servername, $username, $password, $dbname): This function attempts to create a new connection to the MySQL server using the provided server name, username, password, and database name.

Step 3: Checking the Connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

$conn->connect_error: This property of the connection object ($conn) will contain an error message if the connection attempt failed.

if ($conn->connect_error): This condition checks if there was an error during the connection attempt.

die("Connection failed: " . $conn->connect_error): If the connection failed, this function outputs an error message and stops the execution of the script.

Step 4: Outputting a Success Message

echo "database connected";

echo "database connected": If the connection was successful (i.e., there was no error), this line outputs the message "database connected".

This PHP script connects to a MySQL database using the MySQLi extension. 

It sets up connection parameters, attempts to connect, checks for errors, and outputs a success message if the connection is successful. If there is an error, it outputs the error message and stops the script.

Output:

Run this file to check database connectivity.

Open your web browser and navigate to the location where you placed the files. For example, if you're running a local server, the URL might be something like http://localhost/your-directory/db_connect.php



Step 3: Create HTML Form

In Step 3, you will create an HTML form to collect user input. This form will serve as the interface through which users can enter their information. The form will later be processed by a PHP script to insert the data into the MySQL database.

3.1 Create HTML Form:

Open your preferred text editor or integrated development environment (IDE).

Create a new HTML file, for example, index.html.

In this file, you'll define an HTML form with input fields for the user to enter their name, email, and password.

Filename: index.html

Save index.html in myGuests floder.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User Registration</title>
</head>
<body>
    <form action="process.php" method="post">
        <label for="name">First Name:</label>
        <input type="text" name="firstname" required><br>
        <label for="name">Last Name:</label>
        <input type="text" name="lastname" required><br>
        <label for="email">Email:</label>
        <input type="email" name="email" required><br>
     <label for="name">Password:</label>
        <input type="text" name="password" required><br>
        <label for="password">Reg Date:</label>
        <input type="date" name="reg_date" required><br>
        <input type="submit" value="Register">
    </form>
</body>
</html> 

 Save the index.html file.

Step-by-Step Explanation

Document Type Declaration

<!DOCTYPE html>

This tells the web browser that the document is an HTML5 document.

HTML Tag and Language Attribute

<html lang="en">

The <html> tag is the root element of the HTML document.

The lang="en" attribute specifies the language of the document as English.

Head Section

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>User Registration</title>

</head>

<head>: This section contains meta-information about the document.

<meta charset="UTF-8">: Sets the character encoding to UTF-8, which includes most characters from all languages.

<meta name="viewport" content="width=device-width, initial-scale=1.0">: Ensures the page is responsive and adjusts its layout based on the device's width.

<title>User Registration</title>: Sets the title of the document, which appears in the browser tab.

Body Section

<body>

    ...

</body>

The <body> tag contains the content of the HTML document that is visible to the user.

Form Tag

<form action="process.php" method="post">

    ...

</form>

<form>: This tag creates a form for user input.

action="process.php": Specifies the server-side script (process.php) that will handle the form data.

method="post": Specifies the HTTP method to use when sending the form data (POST method is used here).

Label and Input for First Name

<label for="firstname">First Name:</label>

<input type="text" id="firstname" name="firstname" required><br>

<label for="firstname">First Name:</label>: A label for the first name input field. The for attribute connects the label to the input field with the id firstname.

<input type="text" id="firstname" name="firstname" required>: A text input field for the user's first name. The id and name attributes are both set to "firstname". The required attribute means the user must fill out this field before submitting the form.

<br>: A line break to move the next element to a new line.

Label and Input for Last Name

<label for="lastname">Last Name:</label>

<input type="text" id="lastname" name="lastname" required><br>

Similar to the first name field, but for the last name. The id and name attributes are set to "lastname".

Label and Input for Email

<label for="email">Email:</label>

<input type="email" id="email" name="email" required><br>

<label for="email">Email:</label>: A label for the email input field.

<input type="email" id="email" name="email" required>: An email input field. The type="email" ensures that the input must be a valid email address.

Label and Input for Passwpord

<label for="password">Password:</label>

<input type="password" id="password" name="password" required><br>

<label for="password">password:</label>: A label for the passwordinput field.

<input type="password" id="password" name="password" required>: An password input field. The type="password" ensures that the input must be a valid password.

Label and Input for Registration Date

<label for="reg_date">Reg Date:</label>

<input type="date" id="reg_date" name="reg_date" required><br>

<label for="reg_date">Reg Date:</label>: A label for the registration date input field.

<input type="date" id="reg_date" name="reg_date" required>: A date input field. The type="date" allows the user to select a date from a date picker.

Submit Button

<input type="submit" value="Register">

<input type="submit" value="Register">: A submit button that submits the form. The value="Register" sets the text displayed on the button.

This HTML code creates a user registration form that collects the user's first name, last name, email, and registration date. 

When the form is submitted, the data is sent to the process.php script using the POST method. 

Each input field is labeled and required, ensuring that the user must fill out all fields before submitting the form.


Output:

Run this file to check the form .

Open your web browser and navigate to the location where you placed the files. For example, if you're running a local server, the URL might be something like http://localhost/your-directory/index.html  or http://localhost/your-directory/...Here my directory is myGuests...so http://localhost/myGuests/index.html or http://localhost/myGuests/










Step 4: Create PHP Processing Script

In Step 4, you will create a PHP script (process.php) to handle the form submissions and insert the data into the MySQL database.

4.1 Create PHP Processing Script:

Open your preferred text editor or integrated development environment (IDE).

Create a new PHP file, for example, process.php

In this file, you'll handle the form submission, retrieve data from the submitted form, and insert it into the MySQL database.

Filename: process.php

Save process.php in myGuests folder

<?php
include 'db_connect.php'; // Include the database connection script
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];

    $email = $_POST['email'];    

    $password= $_POST['password'];   

    $reg_date = $_POST['reg_date'];
    $sql = "INSERT INTO MyGuests(firstname,lastname, email,password, reg_date) VALUES ('$firstname', '$lastname','$email', '$password','$reg_date')";
    if ($conn->query($sql) === TRUE) {
        echo "Registration successful!";
    } else {
        echo "Error: " . $sql . "<br>" . $conn->error;
    }
}
$conn->close(); // Close the database connection
?> 

    

 Save the process.php file.
Step by Step Code Explanation:

Step 1:Include Database Connection Script

include 'db_connect.php';

This line includes the db_connect.php script, which is assumed to contain the code to establish a connection to the database.

Step 2: Check Request Method

if ($_SERVER["REQUEST_METHOD"] == "POST") {

This condition checks if the request method is POST. This means the following code block will only run if the form was submitted using the POST method.

The $_SERVER["REQUEST_METHOD"] variable in PHP is used to determine the request method used when a form is submitted or when a request is made to the server. The $_SERVER superglobal array contains information about headers, paths, and script locations. Specifically, $_SERVER["REQUEST_METHOD"] provides the request method used to access the page.

Detailed explanation of if ($_SERVER["REQUEST_METHOD"] == "POST"):

1. Understanding $_SERVER["REQUEST_METHOD"]

Purpose:

This variable tells you the HTTP request method used to access the page or submit a form. Common methods include GET, POST, PUT, DELETE, etc.

Values: The value of $_SERVER["REQUEST_METHOD"] is a string that represents the request method, such as "GET" or "POST".

2. The if ($_SERVER["REQUEST_METHOD"] == "POST") Condition

This condition is used to check if the current request is using the POST method.

Steps are: 

Step 1: Check the Request Method:

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Code to execute if the request method is POST

}

Condition: $_SERVER["REQUEST_METHOD"] is checked to see if it is equal to "POST".

Purpose: This condition is typically used to determine if the form data has been submitted via a POST request.

Why Use POST?

Security: POST is used to send data to the server in a way that is not visible in the URL. It’s suitable for operations that modify data, such as form submissions.

Data Size: POST allows sending larger amounts of data compared to GET.

Form Submission: When a form with method POST is submitted, the form data is included in the body of the request, not in the URL.


Step 3: Retrieve Form Data

$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$password = $_POST['password'];
$reg_date = $_POST['reg_date'];

These lines retrieve the data from the form fields submitted via POST. 

The data is stored in variables:

$firstname holds the user's first name.

$lastname holds the user's last name.

$email holds the user's email.

$reg_date holds the registration date.

Step 4: Insert Data into Database

$sql = "INSERT INTO MyGuests (firstname, lastname, email,password, reg_date) VALUES ('$firstname', '$lastname', '$email','$password', '$reg_date')";

This line creates an SQL query to insert the retrieved form data into the MyGuests table of the database. The query adds a new record with the values of $firstname, $lastname, $email, and $reg_date.

Step 5: Execute SQL Query and Check for Success

if ($conn->query($sql) === TRUE) {

    echo "Registration successful!";

} else {

    echo "Error: " . $sql . "<br>" . $conn->error;

}

$conn->query($sql) 

executes the SQL query.

if ($conn->query($sql) === TRUE) 

checks if the query execution was successful. If it was:

echo "Registration successful!"; 

outputs a success message.

If the query execution failed:

echo "Error: " . $sql . "<br>" . $conn->error; outputs an error message along with the SQL query and the specific error message from the database.

Step 6: Close the Database Connection

$conn->close();

This line closes the database connection to free up resources.

Here the  PHP script does in sequence:

  1. Includes the database connection script to connect to the database.
  2. Checks if the form was submitted using the POST method.
  3. Retrieves the submitted form data.
  4. Creates an SQL query to insert the retrieved data into the database.
  5. Executes the SQL query and checks if it was successful. If it is, it prints a success message; if not, it prints an error message.
  6. Closes the database connection.


Step 5. Test Your Form:

In Step 5, you will test your form by placing all the files in the same directory on your server and filling out the form to ensure that the data is submitted to the MySQL database.

5.1 Test Your Form:

Make sure you have all three files (db_connect.php, index.html, and process.php) in the same directory/folder on your server.

Steps to run your project : 

1. Open your web browser and navigate to the location where you placed the files. For example, if you're running a local server, the URL might be something like http://localhost/your-directory/index.html.

2. Open the index.html file in your web browser.

3. Fill out the form with a sample name, email, and password.

4. Click the "Register" button to submit the form.

5.If everything is set up correctly, you should see a message indicating whether the registration was successful or if there was an error. Check your MySQL database to see if the user's information has been inserted into the users table.

Output:



Congratulations! You've successfully tested your form, and the data entered should now be stored in your MySQL database. If you encounter any errors, double-check your code and ensure that your server environment is configured correctly. Additionally, check the error messages displayed by the script for any clues on what might be going wrong.


Data Retrieve From Database

Retrieve data from a table in PHP using the query() method. The Steps are


Step 1: Establish Database Connection

Here already you created db_connect.php to handle the database connection.Just access that one.

Step 2: Create the Main PHP Script to Retrieve Data

Now, create a file retrieve_data.php to retrieve and display the data from the table . And save this file in same project folder.

retrieve_data.php

<?php
//Step 1 include connection script file
include 'db_connect.php'; // Include the database connection script
 // Step 2: Write the SQL query
$sql = "SELECT id, firstname, lastname, email,password, reg_date FROM MyGuests";
 // Step 3: Execute the query
$result = $conn->query($sql);
 // Step 4: Check if the query was successful and there are results
if ($result->num_rows > 0) {
    // Step 5: Output data of each row
    echo "<table border='1'>
    <tr>
    <th>ID</th>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Email</th>
<th> Password</th>
    <th>Registration Date</th>
    </tr>";
 
    while ($row = $result->fetch_assoc()) {
        echo "<tr>";
        echo "<td>" . $row["id"] . "</td>";
        echo "<td>" . $row["firstname"] . "</td>";
        echo "<td>" . $row["lastname"] . "</td>";
        echo "<td>" . $row["email"] . "</td>";
        echo "<td>" . $row["password"] . "</td>";
        echo "<td>" . $row["reg_date"] . "</td>";
        echo "</tr>";
    }
 
    echo "</table>";
} else {
    echo "0 results";
}
// Step 6: Close the database connection
$conn->close();
?> 


Step-by-Step Explanation:

Step 1: Include Database Connection Script

include 'db_connect.php'; // Include the database connection script

This line includes the db_connect.php script, which establishes a connection to the database.

Step 2: Write the SQL Query

$sql = "SELECT id, firstname, lastname, email,password, reg_date FROM MyGuests";

This line defines an SQL query that selects the id, firstname, lastname, email,password and reg_date columns from the MyGuests table in the database.

Step 3: Execute the Query

$result = $conn->query($sql);

This line executes the SQL query and stores the result in the $result variable.

Step 4: Check if the Query was Successful and There are Results

if ($result->num_rows > 0) {

This line checks if the query returned any rows. If $result->num_rows is greater than 0, it means there are rows returned by the query.

Step 5: Output Data of Each Row

    echo "<table border='1'>

    <tr>

    <th>ID</th>

    <th>First Name</th>

    <th>Last Name</th>

    <th>Email</th>

    <th>Password</th>

    <th>Registration Date</th>

    </tr>";

 

    while ($row = $result->fetch_assoc()) {

        echo "<tr>";

        echo "<td>" . $row["id"] . "</td>";

        echo "<td>" . $row["firstname"] . "</td>";

        echo "<td>" . $row["lastname"] . "</td>";

        echo "<td>" . $row["email"] . "</td>";

        echo "<td>" . $row["password"] . "</td>";

        echo "<td>" . $row["reg_date"] . "</td>";

        echo "</tr>";

    }

 

    echo "</table>";

} else {

    echo "0 results";

}

This block of code executes if the query returned one or more rows.

echo "<table border='1'> ... </table>";: Creates an HTML table with a border.

<tr>: Table row.

<th>ID</th>: Table header for the ID column.

<th>First Name</th>: Table header for the First Name column.

<th>Last Name</th>: Table header for the Last Name column.

<th>Email</th>: Table header for the Email column.

<th>Password</th>: Table header for the password column.

<th>Registration Date</th>: Table header for the Registration Date column.

while ($row = $result->fetch_assoc()) { ... }: Loops through each row in the result set.

$row = $result->fetch_assoc(): Fetches a row as an associative array.

echo "<tr> ... </tr>";: Outputs a table row.

<td>" . $row["id"] . "</td>: Outputs the ID in a table cell.

<td>" . $row["firstname"] . "</td>: Outputs the First Name in a table cell.

<td>" . $row["lastname"] . "</td>: Outputs the Last Name in a table cell.

<td>" . $row["email"] . "</td>: Outputs the Email in a table cell.

<td>" . $row["password"] . "</td>: Outputs the password in a table cell.

<td>" . $row["reg_date"] . "</td>: Outputs the Registration Date in a table cell.

Step 6: Close the Database Connection

$conn->close();

This line closes the database connection to free up resources.

Here  the PHP script does:

  1. Includes the db_connect.php script to connect to the database.
  2. Writes an SQL query to select specific columns (id, firstname, lastname, email,password, reg_date) from the MyGuests table.
  3. Executes the SQL query and stores the result in the $result variable.
  4. Checks if the query returned any rows.
If there are rows:  

  1. Outputs an HTML table with a border.
  2. Creates a header row with columns: ID, First Name, Last Name, Email, Registration Date.
  3. Loops through each row in the result set and outputs the data in table rows.

If there are no rows:

  1. Outputs "0 results".

Step 7: Closes the database connection.


Step 3 : To view Output from Table

Open your web browser and navigate to the location where you placed the files. For example, if you're running a local server, the URL might be something like http://localhost/your-directory/retrive_data.php

Output:








Edit Data From Database

To edit data in a database using PHP and MySQL with the query() method, you'll follow these steps. Editing data involves updating existing records based on specific criteria, typically using SQL's UPDATE statement.

Step-by-Step Guide to Edit Data Using query() Method

Step 1: Establish Database Connection

First, ensure you have a db_connect.php file

Step 2: Create the HTML Form (Optional)

If you want to allow users to input data through an HTML form, you can create a form like this:

edit_data.html

<!DOCTYPE html> 
<html> 
<head> 
    <title>Edit Record</title> 
</head> 
<body> 
    <form action="edit_data.php" method="post"> 
        ID: <input type="text" name="id"><br> 
        First Name: <input type="text" name="firstname"><br> 
        Last Name: <input type="text" name="lastname"><br> 
        Email: <input type="email" name="email"><br>           Password: <input type="password" name="password"><br>
          Registration Date: <input type="date" name="reg_date"><br> 
        <input type="submit" value="Update"> 
    </form> 
</body> 
</html> 

 

Step-by-Step Code Explanation: 

Document Type Declaration

<!DOCTYPE html>

This tells the web browser that the document is an HTML5 document.

HTML Tag and Head Section

<html>

<head>

    <title>Edit Record</title>

</head>

The <html> tag is the root element of the HTML document.

The <head> section contains meta-information about the document, including the <title> tag, which sets the title of the document. In this case, the title is "Edit Record".

Body Section

<body>

    <form action="edit_data.php" method="post">

        ID: <input type="text" name="id"><br>

        First Name: <input type="text" name="firstname"><br>

        Last Name: <input type="text" name="lastname"><br>

        Email: <input type="email" name="email"><br>

        Password: <input type="password" name="password"><br>

        Registration Date: <input type="date" name="reg_date"><br>

        <input type="submit" value="Update">

    </form>

</body>

</html>

The <body> section contains the content of the HTML document that is visible to the user.

Inside the <body> tag, there's a <form> element.

Form Element

<form action="edit_data.php" method="post">

The <form> tag creates a form for user input.

action="edit_data.php" specifies that the form data will be sent to edit_data.php when the form is submitted.

method="post" specifies that the form will use the POST method to send data.

Form Fields

ID: <input type="text" name="id"><br>

First Name: <input type="text" name="firstname"><br>

Last Name: <input type="text" name="lastname"><br>

Email: <input type="email" name="email"><br>

Password: <input type="password" name="password"><br>

Registration Date: <input type="date" name="reg_date"><br>

These lines create input fields for the user to enter the record's ID, first name, last name, email, and registration date.

ID: <input type="text" name="id">: A text input field for the record ID. The name attribute is "id".

First Name: <input type="text" name="firstname">: A text input field for the first name. The name attribute is "firstname".

Last Name: <input type="text" name="lastname">: A text input field for the last name. The name attribute is "lastname".

Email: <input type="email" name="email">: An email input field for the email address. The name attribute is "email". The type="email" ensures that the input must be a valid email address.

Password: <input type="paassword" name="email">: An password input field for the password The name attribute is "password". The type="password" ensures that the input must be a valid password.

Registration Date: <input type="date" name="reg_date">: A date input field for the registration date. The name attribute is "reg_date". The type="date" allows the user to select a date from a date picker.

<br> tags are used to insert line breaks, so each input field appears on a new line.

Submit Button 

<input type="submit" value="Update">

<input type="submit" value="Update">: A submit button that submits the form. The value="Update" sets the text displayed on the button to "Update".

What does this form do?

  1. This HTML code creates a form for editing a record. 
  2. When the form is submitted, the data is sent to edit_data.php using the POST method. 
  3. The form includes input fields for the user to enter the record's ID, first name, last name, email,password and registration date. 
  4. Each field is labeled accordingly, and a submit button labeled "Update" is provided to submit the form.


Step 3: PHP Script to Handle Edit (edit_data.php)

Create a PHP script (edit_data.php) to handle the edit operation based on the submitted form data.

<?php
include 'db_connect.php'; // Include the database connection script
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $id = $_POST['id']; // The ID of the record to edit
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $email = $_POST['email'];  
    $password = $_POST['password'];
    $reg_date = $_POST['reg_date'];
    // Create SQL update query
    $sql = "UPDATE MyGuests SET firstname='$firstname', lastname='$lastname', email='$email', password='$password',reg_date='$reg_date' WHERE id=$id";
    // Execute the update query
    if ($conn->query($sql) === TRUE) {
        echo "Record updated successfully";
    } else {
        echo "Error updating record: " . $conn->error;
    }
}
// Close the database connection
$conn->close();
?>

 

Strep-by-Step Explanation:

Include Database Connection Script

include 'db_connect.php'; // Include the database connection script

This line includes the db_connect.php script, which establishes a connection to the database.

Check Request Method

if ($_SERVER["REQUEST_METHOD"] == "POST") {

This condition checks if the request method is POST. This means the following code block will only run if the form was submitted using the POST method.

Retrieve Form Data

    // Retrieve form data

    $id = $_POST['id']; // The ID of the record to edit

    $firstname = $_POST['firstname'];

    $lastname = $_POST['lastname'];

    $email = $_POST['email'];

    $password = $_POST['password'];

    $reg_date = $_POST['reg_date'];

These lines retrieve the data from the form fields submitted via POST. The data is stored in variables:

$id holds the ID of the record to be edited.

$firstname holds the user's first name.

$lastname holds the user's last name.

$email holds the user's email.

$password holds the user's password.

$reg_date holds the registration date.

Create SQL Update Query

    // Create SQL update query

    $sql = "UPDATE MyGuests SET firstname='$firstname', lastname='$lastname', email='$email',  password='$password', reg_date='$reg_date' WHERE id=$id";

This line creates an SQL query to update the record in the MyGuests table where the id matches the value of $id. It sets the firstname, lastname, email, password and reg_date columns to the new values provided by the user.

Execute the Update Query

    // Execute the update query

    if ($conn->query($sql) === TRUE) {

        echo "Record updated successfully";

    } else {

        echo "Error updating record: " . $conn->error;

    }

$conn->query($sql) executes the SQL query.

if ($conn->query($sql) === TRUE) checks if the query execution was successful. If it was:

echo "Record updated successfully"; outputs a success message.

If the query execution failed:

echo "Error updating record: " . $conn->error; outputs an error message along with the specific error message from the database.

Close the Database Connection

// Close the database connection

$conn->close();

This line closes the database connection to free up resources.


Here is the PHP script does in sequence:

  1. Includes the db_connect.php script to connect to the database.
  2. Checks if the form was submitted using the POST method.
  3. Retrieves the submitted form data, including the ID of the record to be edited and the new values for firstname, lastname, email, and reg_date.
  4. Creates an SQL query to update the specified record in the MyGuests table with the new values.
  5. Executes the SQL query and checks if it was successful. If it is, it prints a success message; if not, it prints an error message.
  6. Closes the database connection.

Step 3 : To Edit data in  Table

Open your web browser and navigate to the location where you placed the files. For example, if you're running a local server, the URL might be something like http://localhost/your-directory/edit_data.html

Output:

Input the id number which is existing in your table, i,e;myGuests table here  and Input the new values for the rest fields whatever you want to update and then press UPDATE button/...


Then u input the id which is already present in your database and also input other data to edit ...Then press update button...



after Update button clicked



Delete Data from Database


Deleting data from a database table in PHP involves using an SQL DELETE statement. 

Step-by-Step Guide to Delete Data Using PHP

Step 1: Establish Database Connection

First, ensure you have a db_connect.php file or similar to establish a connection to your MySQL database.

Step 2: Create the HTML Form or Determine Deletion Criteria

Decide how you will determine which records to delete. You can either:

Use an HTML form to allow users to input criteria for deletion using their id no.

delete_data.html

<!DOCTYPE html>
<html>
<head>
    <title>Delete Record</title>
</head>
<body>
    <form action="delete_data.php" method="post">
        ID: <input type="text" name="id"><br>
        <input type="submit" value="Delete">
    </form>
</body>
</html>

 

Step-By-Step Code Explanation:

Document Type Declaration

<!DOCTYPE html>

This tells the web browser that the document is an HTML5 document.

HTML Tag and Head Section

<html>

<head>

    <title>Delete Record</title>

</head>

The <html> tag is the root element of the HTML document.

The <head> section contains meta-information about the document, including the <title> tag, which sets the title of the document. In this case, the title is "Delete Record".

Body Section

<body>

    <form action="delete_data.php" method="post">

        ID: <input type="text" name="id"><br>

        <input type="submit" value="Delete">

    </form>

</body>

</html>

The <body> section contains the content of the HTML document that is visible to the user.

Inside the <body> tag, there's a <form> element.

Form Element

<form action="delete_data.php" method="post">

The <form> tag creates a form for user input.

action="delete_data.php" specifies that the form data will be sent to delete_data.php when the form is submitted.

method="post" specifies that the form will use the POST method to send data.

Form Fields

ID: <input type="text" name="id"><br>

This line creates an input field for the user to enter the record's ID.

ID: <input type="text" name="id">: A text input field for the record ID. The name attribute is "id".

<br> tag is used to insert a line break, so the submit button appears on a new line.

Submit Button

<input type="submit" value="Delete">

<input type="submit" value="Delete">: A submit button that submits the form. The value="Delete" sets the text displayed on the button to "Delete".

    What does this form do?

    1. This HTML code creates a simple form for deleting a record. 
    2. When the form is submitted, the data (specifically the ID of the record to be deleted) is sent to delete_data.php using the POST method. 
    3. The form includes an input field for the user to enter the record's ID and a submit button labeled "Delete".


    Step 3: PHP Script to Handle Deletion (delete_data.php)

    Create a PHP script (delete_data.php) to handle the deletion operation based on the submitted form data or predefined criteria.

    delete_data.php

    <?php
    include 'db_connect.php'; // Include the database connection script
     if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Retrieve form data or other criteria
        $id = $_POST['id']; // The ID of the record to delete
     
        // Create SQL delete query
        $sql = "DELETE FROM MyGuests WHERE id = $id";
     
        // Execute the delete query
        if ($conn->query($sql) === TRUE) {
            echo "Record deleted successfully";
        } else {
            echo "Error deleting record: " . $conn->error;
        }
    }
     
    // Close the database connection
    $conn->close();
    ?>

     

    Step-by-Step Code Explanation:

    Include Database Connection Script

    include 'db_connect.php';

    This line includes the db_connect.php script, which establishes a connection to the database.

    Check Request Method

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

    This condition checks if the request method is POST. This means the following code block will only run if the form was submitted using the POST method.

    Retrieve Form Data

        // Retrieve the ID from the form

        $id = $_POST['id'];

    This line retrieves the ID from the form field submitted via POST. The data is stored in the $id variable.

    Create SQL Delete Query

       // Create the SQL delete query

        $sql = "DELETE FROM MyGuests WHERE id=$id";

    This line creates an SQL query to delete the record from the MyGuests table where the id matches the value of $id.

    Execute the Delete Query

        // Execute the delete query

        if ($conn->query($sql) === TRUE) {

            echo "Record deleted successfully";

        } else {

            echo "Error deleting record: " . $conn->error;

        }

    $conn->query($sql) executes the SQL query.

    if ($conn->query($sql) === TRUE) checks if the query execution was successful. If it was:

    echo "Record deleted successfully"; outputs a success message.

    If the query execution failed:

    echo "Error deleting record: " . $conn->error; outputs an error message along with the specific error message from the database.

    Close the Database Connection

    // Close the database connection

    $conn->close();

    This line closes the database connection to free up resources.

    Here is the HTM page and  PHP script does in sequence:

      1. The user enters the ID of the record they want to delete in the form on the HTML page.
      2. When the user submits the form, the data is sent to delete_data.php using the POST method.
      3. delete_data.php retrieves the ID from the form data.
      4. It creates and executes an SQL query to delete the record with the specified ID from the database.
      5. It checks if the query was successful and outputs a corresponding message.
      6. It closes the database connection.

      Step 3 : To delete data in  Table/ or Test the delete 

      Open your web browser and navigate to the location where you placed the files. For example, if you're running a local server, the URL might be something like http://localhost/your-directory/delete_data.html

      Output:


      Input the id number which is existing in your table, i,e;myGuests table  and submit ...

      next



      Display all records from Database 

      with provided option to edit and delete

      To display all records in a table and provide options to delete and edit each record, you need to:
      1. Retrieve and display records from the database.
      2. Provide "Edit" and "Delete" buttons for each record.
      3. Create separate scripts to handle the editing and deleting operations.
      4. Snapshot:








      Here are the steps :

      Step 1: Establish Database Connection

      Ensure you have a db_connect.php file to establish a connection to your MySQL database.

      Step 2: Display Records with Edit and Delete Options

      Create a script (view_records.php) to retrieve and display all records with "Edit" and "Delete" buttons.
      view_records.php


      <?php
      include 'db_connect.php'; // Include the database connection script
      $sql = "SELECT id, firstname, lastname, email, reg_date FROM MyGuests";
      $result = $conn->query($sql);
       
      if ($result->num_rows > 0) {
          echo "<table border='1'>";
          echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Registration Date</th><th>Action</th></tr>";
          while($row = $result->fetch_assoc()) {
              echo "<tr>";
              echo "<td>" . $row["id"] . "</td>";
              echo "<td>" . $row["firstname"] . "</td>";
              echo "<td>" . $row["lastname"] . "</td>";
              echo "<td>" . $row["email"] . "</td>";
              echo "<td>" . $row["reg_date"] . "</td>";
              echo "<td>";
              echo "<a href='edit_record.php?id=" . $row["id"] . "'>Edit</a> | ";
              echo "<a href='delete_record.php?id=" . $row["id"] . "' onclick='return confirm(\"Are you sure you want to delete this record?\");'>Delete</a>";
              echo "</td>";
              echo "</tr>";
          }
          echo "</table>";
      } else {
          echo "0 results";
      }
       
      $conn->close();
      ?>
       

       
      Step-By-Step Code Explanation

      Include Database Connection Script

      include 'db_connect.php'; // Include the database connection script
      This line includes the db_connect.php script, which establishes a connection to the database.

      Create SQL Query

      $sql = "SELECT id, firstname, lastname, email, reg_date FROM MyGuests";
      This line defines an SQL query that selects the id, firstname, lastname, email, and reg_date columns from the MyGuests table in the database.

      Execute SQL Query

      $result = $conn->query($sql);
      This line executes the SQL query and stores the result in the $result variable.

      Check if Query Returned Any Results

      if ($result->num_rows > 0) {
      This condition checks if the query returned any rows.
      If $result->num_rows is greater than 0, it means there are rows returned by the query.

      Output Data of Each Row

          echo "<table border='1'>";
          echo "<tr><th>ID</th><th>First Name</th><th>Last Name</th><th>Email</th><th>Registration Date</th><th>Action</th></tr>";
      These lines start creating an HTML table with a border.
      1. <tr> creates a table row.
      2. <th>ID</th> creates a table header cell for the ID column.
      3. <th>First Name</th> creates a table header cell for the First Name column.
      4. <th>Last Name</th> creates a table header cell for the Last Name column.
      5. <th>Email</th> creates a table header cell for the Email column.
      6. <th>Registration Date</th> creates a table header cell for the Registration Date column.
      7. <th>Action</th> creates a table header cell for the Action column (which will contain Edit and Delete links).
          while($row = $result->fetch_assoc()) {
      This loop fetches each row from the result set as an associative array and stores it in the $row variable.
              echo "<tr>";
              echo "<td>" . $row["id"] . "</td>";
              echo "<td>" . $row["firstname"] . "</td>";
              echo "<td>" . $row["lastname"] . "</td>";
              echo "<td>" . $row["email"] . "</td>";
              echo "<td>" . $row["reg_date"] . "</td>";
              echo "<td>";
      These lines create a new table row for each record.
      1. <td> creates a table cell and outputs the value of the id column.
      2. <td> creates a table cell and outputs the value of the firstname column.
      3. <td> creates a table cell and outputs the value of the lastname column.
      4. <td> creates a table cell and outputs the value of the email column.
      5. <td> creates a table cell and outputs the value of the reg_date column.
              echo "<a href='edit_record.php?id=" . $row["id"] . "'>Edit</a> | ";
              echo "<a href='delete_record.php?id=" . $row["id"] . "' onclick='return confirm(\"Are you sure you want to delete this record?\");'>Delete</a>";
              echo "</td>";
              echo "</tr>";
          }
      These lines add an Edit and Delete link to the Action column.
      1. <a href='edit_record.php?id=" . $row["id"] . "'>Edit</a> creates an Edit link that redirects to edit_record.php with the id parameter set to the current record's ID.
      2. <a href='delete_record.php?id=" . $row["id"] . "' onclick='return confirm("Are you sure you want to delete this record?");'>Delete</a> creates a Delete link that redirects to delete_record.php with the id parameter set to the current record's ID. The onclick attribute adds a confirmation dialog that asks the user if they are sure they want to delete the record.
          echo "</table>";
      } else {
          echo "0 results";
      }
      1. echo "</table>"; closes the HTML table.
      2. } else { echo "0 results"; } outputs "0 results" if there are no rows returned by the query.

      Close the Database Connection

      $conn->close();
      This line closes the database connection to free up resources.
      Summary

      Here is the PHP script does in sequence:

      1. Includes the db_connect.php script to connect to the database.
      2. Defines an SQL query to select specific columns (id, firstname, lastname, email, reg_date) from the MyGuests table.
      3. Executes the SQL query and stores the result in the $result variable.
      4. Checks if the query returned any rows. If it did:
      5. Outputs an HTML table with a border.
      6. Creates a header row with columns: ID, First Name, Last Name, Email, Registration Date, and Action.
      7. Loops through each row in the result set and outputs the data in table rows.
      8. Adds Edit and Delete links in the Action column for each row. The Delete link includes a confirmation dialog.
      9. If no rows are returned, it outputs "0 results".
      10. Closes the database connection.

      Step 3: Edit Record Script (edit_record.php)

      Create a script (edit_record.php) to handle the editing of a record.

      HTML Form for Editing:
      edit_record.php

      <?php
      include 'db_connect.php'; // Include the database connection script
       
      if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {
          $id = $_GET['id'];
       
          $sql = "SELECT id, firstname, lastname, email, reg_date FROM MyGuests WHERE id = $id";
          $result = $conn->query($sql);
       
          if ($result->num_rows == 1) {
              $row = $result->fetch_assoc();
          } else {
              echo "Record not found.";
              exit();
          }
      } elseif ($_SERVER["REQUEST_METHOD"] == "POST") {
          // Handle the update operation
          $id = $_POST['id'];
          $firstname = $_POST['firstname'];
          $lastname = $_POST['lastname'];
          $email = $_POST['email'];
          $reg_date = $_POST['reg_date'];
           $sql = "UPDATE MyGuests SET firstname='$firstname', lastname='$lastname', email='$email', reg_date='$reg_date' WHERE id=$id";
           if ($conn->query($sql) === TRUE) {
              echo "Record updated successfully";
          } else {
              echo "Error updating record: " . $conn->error;
          }
           $conn->close();
          header("Location: view_records.php");
          exit();
      }
      ?>
       <!DOCTYPE html>
      <html>
      <head>
          <title>Edit Record</title>
      </head>
      <body>
          <form action="edit_record.php" method="post">
              <input type="hidden" name="id" value="<?php echo $row['id']; ?>">
              First Name: <input type="text" name="firstname" value="<?php echo $row['firstname']; ?>"><br>
              Last Name: <input type="text" name="lastname" value="<?php echo $row['lastname']; ?>"><br>
              Email: <input type="email" name="email" value="<?php echo $row['email']; ?>"><br>
              Registration Date: <input type="date" name="reg_date" value="<?php echo $row['reg_date']; ?>"><br>
              <input type="submit" value="Update">
          </form>
      </body>
      </html>
        

       
      Create a script (delete_record.php) to handle the deletion of a record.

      delete_record.php

      <?php
      include 'db_connect.php'; // Include the database connection script
       if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {
          $id = $_GET['id'];
           $sql = "DELETE FROM MyGuests WHERE id = $id";
           if ($conn->query($sql) === TRUE) {
              echo "Record deleted successfully";
          } else {
              echo "Error deleting record: " . $conn->error;
          } 
          $conn->close();
          header("Location: view_records.php");
          exit();
      }
      ?>

       

       

      Step-By-Step Code Explanation

      Include Database Connection Script

      include 'db_connect.php'; // Include the database connection script
      This line includes the db_connect.php script, which establishes a connection to the database.

      Handle GET Request

      if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {
          $id = $_GET['id'];
      This block checks if the request method is GET and if the id parameter is set in the GET request.
      $_SERVER["REQUEST_METHOD"] == "GET" checks if the request method is GET.
      isset($_GET['id']) checks if the id parameter is set in the GET request.
      $id = $_GET['id']; retrieves the ID from the GET request and stores it in the $id variable.

      Create SQL Query

          $sql = "DELETE FROM MyGuests WHERE id = $id";
      This line defines an SQL query that deletes the record with the specified ID from the MyGuests table.

      Execute SQL Query

          if ($conn->query($sql) === TRUE) {
              echo "Record deleted successfully";
          } else {
              echo "Error deleting record: " . $conn->error;
          }
      This block executes the SQL query and checks if it was successful.
      if ($conn->query($sql) === TRUE) executes the SQL query and checks if it was successful.
      echo "Record deleted successfully"; outputs a success message if the query was successful.
      else { echo "Error deleting record: " . $conn->error; } outputs an error message if the query failed.

      Close the Database Connection

        $conn->close();
      This line closes the database connection to free up resources.

      Redirect to View Records Page

          header("Location: view_records.php");
          exit();
      }
      header("Location: view_records.php"); redirects the user to the view_records.php page after the deletion.
      exit(); stops the execution of the script.

      Here is  the PHP script does in sequence:

      1. Includes the db_connect.php script to connect to the database.
      2. Checks if the request method is GET and if the id parameter is set in the GET request.
      3. Retrieves the ID from the GET request.
      4. Defines an SQL query to delete the record with the specified ID from the MyGuests table.
      5. Executes the SQL query and checks if it was successful. Outputs a success or error message accordingly.
      6. Closes the database connection.
      7. Redirects the user to view_records.php after the deletion.


      Step 3 : To view all the records from Table

      Open your web browser and navigate to the location where you placed the files. For example, if you're running a local server, the URL might be something like http://localhost/your-directory/view_records.php

      Output:


      Now if you click on edit then...

      Now if you click on Delete then



      Conclusion

      No comments:

      Post a Comment

      Pages

      SoraTemplates

      Best Free and Premium Blogger Templates Provider.

      Buy This Template