FORM AND DATABASE CONNECTIVITY
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
1.1 Create a Database:
- Open your MySQL management tool (like phpMyAdmin, MySQL Workbench, or use command-line interface).
- 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.
- 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).
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
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).
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> |
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 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 $email = $_POST['email']; $password= $_POST['password']; $reg_date = $_POST['reg_date'];
|
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:
- Includes the database connection script to connect to the database.
- Checks if the form was submitted using the POST method.
- Retrieves the submitted form data.
- Creates an SQL query to insert the retrieved data into the database.
- 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.
- 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-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>
</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:
- Includes the db_connect.php script to connect to the database.
- Writes an SQL query to select specific columns (id, firstname, lastname, email,password, reg_date) from the MyGuests table.
- Executes the SQL query and stores the result in the $result variable.
- Checks if the query returned any rows.
If there are rows:
- Outputs an HTML table with a border.
- Creates a header row with columns: ID, First Name, Last Name, Email, Registration Date.
- Loops through each row in the result set and outputs the data in table rows.
If there are no rows:
- 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>
|
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?
- This HTML code creates a form for editing a record.
- When the form is submitted, the data is sent to edit_data.php using the POST method.
- The form includes input fields for the user to enter the record's ID, first name, last name, email,password and registration date.
- 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 |
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:
- Includes the db_connect.php script to connect to the database.
- Checks if the form was submitted using the POST method.
- 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.
- Creates an SQL query to update the specified record in the MyGuests table with the new values.
- 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.
- 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/...
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:
delete_data.html
<!DOCTYPE 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?
- This HTML code creates a simple form for deleting a record.
- 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.
- 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
|
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:
- The user enters the ID of the record they want to delete in the form on the HTML page.
- When the user submits the form, the data is sent to delete_data.php using the POST method.
- delete_data.php retrieves the ID from the form data.
- It creates and executes an SQL query to delete the record with the specified ID from the database.
- It checks if the query was successful and outputs a corresponding message.
- 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
- Retrieve and display records from the database.
- Provide "Edit" and "Delete" buttons for each record.
- Create separate scripts to handle the editing and deleting operations.
- Snapshot:
Here are the steps :
Step 1: Establish Database Connection
Step 2: Display Records with Edit and Delete Options
<?php
|
Include Database Connection Script
Create SQL Query
Execute SQL Query
Check if Query Returned Any Results
Output Data of Each Row
- <tr> creates a table row.
- <th>ID</th> creates a table header cell for the ID column.
- <th>First Name</th> creates a table header cell for the First Name column.
- <th>Last Name</th> creates a table header cell for the Last Name column.
- <th>Email</th> creates a table header cell for the Email column.
- <th>Registration Date</th> creates a table header cell for the Registration Date column.
- <th>Action</th> creates a table header cell for the Action column (which will contain Edit and Delete links).
- <td> creates a table cell and outputs the value of the id column.
- <td> creates a table cell and outputs the value of the firstname column.
- <td> creates a table cell and outputs the value of the lastname column.
- <td> creates a table cell and outputs the value of the email column.
- <td> creates a table cell and outputs the value of the reg_date column.
- <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.
- <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>"; closes the HTML table.
- } else { echo "0 results"; } outputs "0 results" if there are no rows returned by the query.
Close the Database Connection
Here is the PHP script does in sequence:
- Includes the db_connect.php script to connect to the database.
- Defines an SQL query to select specific columns (id, firstname, lastname, email, reg_date) from the MyGuests table.
- Executes the SQL query and stores the result in the $result variable.
- Checks if the query returned any rows. If it did:
- Outputs an HTML table with a border.
- Creates a header row with columns: ID, First Name, Last Name, Email, Registration Date, and Action.
- Loops through each row in the result set and outputs the data in table rows.
- Adds Edit and Delete links in the Action column for each row. The Delete link includes a confirmation dialog.
- If no rows are returned, it outputs "0 results".
- Closes the database connection.
Step 3: Edit Record Script (edit_record.php)
<?php
|
delete_record.php
<?php
|
Step-By-Step Code Explanation
Include Database Connection Script
include 'db_connect.php'; // Include the database connection scriptThis 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:
- Includes the db_connect.php script to connect to the database.
- Checks if the request method is GET and if the id parameter is set in the GET request.
- Retrieves the ID from the GET request.
- Defines an SQL query to delete the record with the specified ID from the MyGuests table.
- Executes the SQL query and checks if it was successful. Outputs a success or error message accordingly.
- Closes the database connection.
- 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