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

Friday, July 19, 2024

FORM AND DATABASE CONNECTIVITY With CRUD Operations (Using Procedural approach)

  

FORM AND DATABASE CONNECTIVITY

With  CRUD Operations 

Using Procedural approach

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.

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 = mysqli_connect($servername, $username, $password,$dbname);


// Check connection

if (!$conn) {

  die("Connection failed: " . mysqli_connect_error());

}

echo "Connected successfully";

?> 

 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 to the Database

$conn = mysqli_connect($servername, $username, $password, $dbname);

mysqli_connect($servername, $username, $password, $dbname); attempts to establish a connection to the MySQL database using the provided server name, username, password, and database name.

$conn: The function returns a connection object ($conn) if the connection is successful or false if it fails.

Step 3: Checking the Connection

if (!$conn) {

  die("Connection failed: " . mysqli_connect_error());

}

if (!$conn) checks if the connection failed by testing if $conn is false.

If the connection failed, die("Connection failed: " . mysqli_connect_error()); terminates the script and outputs an error message. mysqli_connect_error() returns a string describing the error.


Step 4: Outputting a Success Message

echo "Connected successfully";

If the connection is successful (i.e., $conn is not false), this line outputs "Connected successfully" to indicate that the connection to the database was established successfully.

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

Summary

  1. The script defines the necessary parameters to connect to a MySQL database  using the MySQLi extension ($servername, $username, $password, $dbname).
  2. It attempts to establish a connection to the database using mysqli_connect().
  3. It checks if the connection was successful.
  4. If not, it outputs an error message and terminates the script.
  5. If successful, it outputs a success message.

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="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 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.

Summary:

  1. This HTML code creates a user registration form that collects the user's first name, last name, email, and registration date. 
  2. When the form is submitted, the data is sent to the process.php script using the POST method. 
  3. 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/





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'];
    $reg_date = $_POST['reg_date'];
    $sql = "INSERT INTO MyGuests(firstname,lastname, email, reg_date) VALUES ('$firstname', '$lastname','$email', '$reg_date')";

if (mysqli_query($conn, $sql)) {
  echo "Registration successful";
else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}


mysqli_close($conn);
}

?> 

 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.

Step 3: Retrieve Form Data

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

These lines retrieve the values from the POST request and store them in PHP variables:

$firstname = $_POST['firstname']; assigns the submitted value for the first name to the $firstname variable.

$lastname = $_POST['lastname']; assigns the submitted value for the last name to the $lastname variable.

$email = $_POST['email']; assigns the submitted value for the email to the $email variable.

$reg_date = $_POST['reg_date']; assigns the submitted value for the registration date to the $reg_date variable.

Step 4: Insert Data into Database/Construct SQL query

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

This line constructs an SQL query to insert a new record into the MyGuests table. The INSERT INTO statement specifies the table (MyGuests) and the columns (firstname, lastname, email, reg_date) to which the values should be inserted.

The values are taken from the PHP variables ($firstname, $lastname, $email, $reg_date) and inserted into the query.

Execute the SQL query and handle the result:

if (mysqli_query($conn, $sql)) {
  echo "Registration successful";
} else {
  echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}

if (mysqli_query($conn, $sql)) { ... } attempts to execute the SQL query using the mysqli_query() function.

If the query is successful, it outputs "Registration successful".

If the query fails, it outputs an error message that includes the SQL query and the error returned by mysqli_error($conn). This helps in diagnosing the problem by providing details of the SQL query and the specific error message.

Close the database connection:

mysqli_close($conn);
This line closes the database connection using mysqli_close($conn), ensuring that the connection is properly terminated and resources are freed.
Summary
  1. The script starts by including a database connection script to establish a connection to the database.
  2. It then checks if the request method is POST, indicating that the form has been submitted.
  3. It retrieves the form data from the POST request.
  4. It constructs an SQL INSERT INTO query to add the new record to the MyGuests table.
  5. It executes the SQL query and outputs a success or error message based on the result.
  6. Finally, it closes the database connection to free up resources.
  7. By following these steps, the script ensures that data submitted via a form is safely inserted into the database and handles any errors that may occur during the process.


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, reg_date FROM MyGuests";

// Step 3: Execute the query

$result = mysqli_query($conn, $sql);

// Step 4: Check if the query was successful and there are results

if (mysqli_num_rows($result) > 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>Registration Date</th>

    </tr>";

    while ($row = mysqli_fetch_assoc($result)) {

        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 "</tr>";

    }

    echo "</table>";

} else {

    echo "0 results";

}

// Step 6: Close the database connection

mysqli_close($conn);

?>


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, 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.

Step 3: Execute the SQL query:

$result = mysqli_query($conn, $sql);

This line executes the SQL query using the mysqli_query() function and stores the result in the $result variable. This variable will contain the data returned by the query or false if the query failed.

Step 4: Check if the query was successful and there are results:

if (mysqli_num_rows($result) > 0) {

if (mysqli_num_rows($result) > 0) checks if the query returned any rows by counting the number of rows in the result set. If there are more than 0 rows, it proceeds to process the results.

Step 5: Output table headers:

// 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>Registration Date</th>
    </tr>";


These lines start an HTML table with a border and define the table headers: ID, First Name, Last Name, Email, and Registration Date.

Step 6: Output data of each row:

 while ($row = mysqli_fetch_assoc($result)) {
        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 "</tr>";
    }

while ($row = mysqli_fetch_assoc($result)) fetches each row of the result set as an associative array and stores it in the $row variable.
Inside the loop, it outputs each row's data in a table row (<tr>), with each cell (<td>) containing the corresponding value from the $row array.
For example, echo "<td>" . $row["id"] . "</td>"; outputs the id value in a table cell.

Step 7: Close the table and handle no results:

echo "</table>";
} else {
    echo "0 results";

}
After the loop, echo "</table>"; closes the HTML table.
If there are no results, else { echo "0 results"; } outputs "0 results".

Step 8: Close the database connection:

mysqli_close($conn);
?>
This line closes the database connection using mysqli_close($conn), ensuring that the connection is properly terminated and resources are freed.
Summary
Step 1: Includes a file that establishes the database connection.
Step 2: Defines an SQL query to select specific columns from the MyGuests table.
Step 3: Executes the SQL query and stores the result.
Step 4: Checks if there are any results.
If there are results, it proceeds to output them.
If there are no results, it outputs "0 results".
Step 5: Outputs the data in an HTML table format.
Step 6: Closes the database connection to free up resources.


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> 
        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>

        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>

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.

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, 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'];
    $reg_date = $_POST['reg_date'];
    // Create SQL update query
    $sql = "UPDATE MyGuests SET firstname='$firstname', lastname='$lastname', email='$email', reg_date='$reg_date' WHERE id=$id";
    // Execute the update query
if (mysqli_query($conn, $sql)) {
  echo "Record updated successfully";
else {
  echo "Error updating record: " . mysqli_error($conn);
}
// Close the database connection
mysqli_close($conn);
?>

 

Strep-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: 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.

Step 3: Retrieve Form Data

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

    $firstname = $_POST['firstname'];

    $lastname = $_POST['lastname'];

    $email = $_POST['email'];

    $reg_date = $_POST['reg_date'];

The values submitted through the form are retrieved from the $_POST superglobal array and stored in variables.

$id contains the ID of the record to be updated.

$firstname, $lastname, $email, and $reg_date contain the new values for the record.

Step 4: Create SQL Update Query

    // Create SQL update query

    $sql = "UPDATE MyGuests SET firstname='$firstname', lastname='$lastname', email='$email', 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, and reg_date columns to the new values provided by the user.

Step 5:Execute the update query:

if (mysqli_query($conn, $sql)) {

  echo "Record updated successfully";

} else {

  echo "Error updating record: " . mysqli_error($conn);

The mysqli_query($conn, $sql) function executes the SQL update query.

If the query is successful, it echoes "Record updated successfully".

If there is an error executing the query, it echoes "Error updating record: " followed by the error message from the database.

Step 6: Close the database connection:

mysqli_close($conn);
?>
This line closes the database connection using mysqli_close($conn), ensuring that the connection is properly terminated and resources are freed.
Summary

  1. Include the database connection script to establish a connection to the database.
  2. Check if the request method is POST to ensure the form was submitted using the POST method.
  3. Retrieve form data from the $_POST array and store it in variables.
  4. Create the SQL update query to update the specified record in the database.
  5. Execute the update query and handle success or error messages.
  6. Close the database connection to free up resources.

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:



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 (mysqli_query($conn, $sql)) {
            echo "Record deleted successfully";
        } else {
    die("Connection failed: " . mysqli_connect_error()); 

        }
    }
     
    // Close the database connection
    mysqli_close($conn);

    ?>

     

    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'];

    The value submitted through the form is retrieved from the $_POST superglobal array and stored in the $id variable.

    $id contains the ID of the record to be deleted.

    Create SQL Delete Query

       // Create the SQL delete query

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

    This line constructs an SQL DELETE query to delete the record from the MyGuests table where the id matches the provided $id.

    Execute the delete query:

    if (mysqli_query($conn, $sql)) {

            echo "Record deleted successfully";

        } else {

            echo "Error deleting record: " . mysqli_error($conn);

        }

    The mysqli_query($conn, $sql) function executes the SQL delete query.

    If the query is successful, it echoes "Record deleted successfully".

    If there is an error executing the query, it echoes "Error deleting record: " followed by the error message from the database connection mysqli_error($conn).

    Close the database connection:

    mysqli_close($conn);

    ?>

    This line closes the database connection using mysqli_close($conn), ensuring that the connection is properly terminated and resources are freed.

    Summary

    1. Include the database connection script to establish a connection to the database.
    2. Check if the request method is POST to ensure the form was submitted using the POST method.
    3. Retrieve form data from the $_POST array and store it in the $id variable.
    4. Create the SQL delete query to delete the specified record from the database.
    5. Execute the delete query and handle success or error messages.
    6. Close the database connection to free up resources.



    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 press Delete button ...

    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 the database connection script

    include 'db_connect.php';

    // Query to select data from the table

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

    $result = mysqli_query($conn, $sql);

    // Check if there are results

    if (mysqli_num_rows($result) > 0) {

        // Start the table and add table headers

        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>";

        // Loop through each row and output data

        while($row = mysqli_fetch_assoc($result)) {

            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>";

        }

        // End the table

        echo "</table>";

    } else {

        // No results found

        echo "0 results";

    }

    // Close the database connection

    mysqli_close($conn);

    ?>

     


    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 = mysqli_query($conn, $sql);
    This line executes the SQL query using the mysqli_query function. The result of the query is stored in the $result variable.

    Check if There Are Results:

    if (mysqli_num_rows($result) > 0) {
    This condition checks if the number of rows in the result set is greater than 0, indicating that there are records in the MyGuests table.

    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 = mysqli_fetch_assoc($result)) {
    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

    mysqli_close($conn);
    This line closes the database connection to free up resources.
    Summary
    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


    function get_record($conn, $id) {

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

        return mysqli_query($conn, $sql);

    }


    function update_record($conn, $id, $firstname, $lastname, $email, $reg_date) {

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

        return mysqli_query($conn, $sql);

    }


    if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {

        $id = $_GET['id'];

        $result = get_record($conn, $id);


        if (mysqli_num_rows($result) == 1) {

            $row = mysqli_fetch_assoc($result);

        } else {

            echo "Record not found.";

            mysqli_close($conn);

            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'];


        if (update_record($conn, $id, $firstname, $lastname, $email, $reg_date)) {

            echo "Record updated successfully";

        } else {

            echo "Error updating record: " . mysqli_error($conn);

        }


        mysqli_close($conn);

        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 isset($row['id']) ? $row['id'] : ''; ?>">

            First Name: <input type="text" name="firstname" value="<?php echo isset($row['firstname']) ? $row['firstname'] : ''; ?>"><br>

            Last Name: <input type="text" name="lastname" value="<?php echo isset($row['lastname']) ? $row['lastname'] : ''; ?>"><br>

            Email: <input type="email" name="email" value="<?php echo isset($row['email']) ? $row['email'] : ''; ?>"><br>

            Registration Date: <input type="date" name="reg_date" value="<?php echo isset($row['reg_date']) ? $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

    // Function to delete a record from the database

    function delete_record($conn, $id) {

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

    return mysqli_query($conn, $sql);

    }

    if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {

        $id = $_GET['id'];

        if (delete_record($conn, $id) === TRUE) {

            echo "Record deleted successfully";

        } else {

            echo "Error deleting record: " . $delete_result;

        }

        mysqli_close($conn);

        header("Location: view_records.php");

        exit();

    }

    ?>

     

     

    Step-By-Step Code Explanation

    Include the database connection script:

    include 'db_connect.php'; // Include the database connection script
    This line includes an external file db_connect.php, which contains the code to establish a connection to the MySQL database.

    Define delete_record function:

    function delete_record($conn, $id) {
        $sql = "DELETE FROM MyGuests WHERE id = $id";
        return mysqli_query($conn, $sql);
    }
    This function, delete_record, takes two parameters: $conn (the database connection) and $id (the ID of the record to delete).
    It constructs an SQL DELETE query to remove the record from the MyGuests table where the id matches the provided $id.
    The mysqli_query function executes the SQL query and returns the result. If the query is successful, it returns TRUE; otherwise, it returns FALSE.

    Check the Request Method and ID Parameter:

    if ($_SERVER["REQUEST_METHOD"] == "GET" && isset($_GET['id'])) {
    This condition checks if the request method is GET and if the id parameter is set in the $_GET superglobal array. It ensures that the script will only proceed if these conditions are met.

    Retrieve and Delete the Record:

    $id = $_GET['id'];
    if (delete_record($conn, $id) === TRUE) {
        echo "Record deleted successfully";
    } else {
        echo "Error deleting record: " . mysqli_error($conn);
    }
    The id value is retrieved from the $_GET array and stored in the $id variable.
    The delete_record function is called with $conn and $id as arguments to delete the specified record.
    If the deletion is successful (delete_record returns TRUE), it echoes "Record deleted successfully".
    If the deletion fails, it echoes "Error deleting record: " followed by the error message using mysqli_error($conn). This provides details about why the deletion failed.

    Close the Database Connection:

    mysqli_close($conn);
    This line closes the database connection using mysqli_close($conn), freeing up resources and closing the connection to the MySQL server.

    Redirect to Another Page:

    header("Location: view_records.php");
    exit();
    The header function sends an HTTP header to redirect the user to view_records.php.
    exit() ensures that no further code is executed after the redirect, effectively ending the script execution.
    Summary
    1. Include the database connection script to establish a connection.
    2. Define a function to delete a record from the database using the DELETE SQL query.
    3. Check if the request method is GET and if the id parameter is provided.
    4. Retrieve the record ID and call the delete function, handling success or failure.
    5. Close the database connection and redirect to another page, ending the script execution.


    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