Affichage des articles dont le libellé est php. Afficher tous les articles
Affichage des articles dont le libellé est php. Afficher tous les articles

PHP - Database Navigation and CRUD Operations

How to Navigate Through Database Records and Execute CRUD Operations in PHP with JavaScript



In this php tutorial, we will see how to use create a dynamic web application that displays product details in an HTML table and allows users to add, edit, or remove products. 
It also provides navigation buttons for browsing through the product list using JavaScript.



Project Source Code:

db_connect.php script


<?php

// Define database connection parameters
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "product_db";

try
{
// Create a new PDO instance
$conn = new PDO("mysql: host=$servername; dbname=$dbname", $username, $password);
// Set PDO error mode to exception
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
// If a connection error occurs, display it
echo "connection failde: " . $e->getMessage();
}

?>


operations.php script

<?php

require_once 'db_connect.php';

// Check if form is submitted - add
if(isset($_POST['add']))
{
$name = $_POST['product-name'];
$price = $_POST['product-price'];

// insert data
$stmt = $conn->prepare('INSERT INTO `product`(`name`, `price`) VALUES (:name, :price)');
$stmt->bindParam(":name", $name);
$stmt->bindParam(":price", $price);

session_start();

try{

if($stmt->execute())
{
$_SESSION['success_message'] = 'Data inserted successfully';
header('Location: nav-crud.php');
exit();
}
else
{
$_SESSION['warnning_message'] = 'Data NOT inserted';
header('Location: nav-crud.php');
exit();
}
}
catch(PDOException $e){
$_SESSION['error_message'] = "Error: Data NOT inserted - " . $e->getMessage();
header('Location: nav-crud.php');
exit();
}


}

// Check if form is submitted - edit
elseif(isset($_POST['edit']))
{
$id = $_POST['product-id'];
$name = $_POST['product-name'];
$price = $_POST['product-price'];
// edit data
$stmt = $conn->prepare('UPDATE `product` SET `name`=:name,`price`=:price WHERE `id`=:id');
$stmt->bindParam(":name", $name);
$stmt->bindParam(":price", $price);
$stmt->bindParam(":id", $id);
session_start();

try
{
if($stmt->execute())
{
if( $stmt->rowCount() > 0 ){
$_SESSION['success_message'] = 'Data Updated successfully';
header('Location: nav-crud.php');
exit();
}
else
{
$_SESSION['warnning_message'] = 'Data NOT Updated';
header('Location: nav-crud.php');
exit();
}
}
}
catch(PDOException $e){

$_SESSION['error_message'] = "Error: Data NOT updated - " . $e->getMessage();
header('Location: nav-crud.php');
exit();

}


}

// Check if form is submitted - remove
elseif(isset($_POST['remove']))
{
$id = $_POST['product-id'];
// remove data
$stmt = $conn->prepare('DELETE FROM `product` WHERE `id`=:id');
$stmt->bindParam(":id", $id);
session_start();

try{

if($stmt->execute())
{
if( $stmt->rowCount() > 0 ){
$_SESSION['success_message'] = 'Data Deleted successfully';
header('Location: nav-crud.php');
exit();
}
else
{
$_SESSION['warnning_message'] = "Data NOT deleted";
header('Location: nav-crud.php');
exit();
}
}
}
catch(PDOException $e){

$_SESSION['error_message'] = "Error: Data NOT deleted - " . $e->getMessage();
header('Location: nav-crud.php');
exit();

}

}

?>


nav-crud.php page script

<?php

// Connect to the database
require_once 'db_connect.php';

// Define the SQL query to select all products from the "product" table
// Prepare the SQL statement
$stmt = $conn->prepare('SELECT * FROM `product`');

// Execute the SQL statement
$stmt -> execute();

// Fetch all the results from the statement and store them in an array
$results = $stmt -> fetchAll(PDO::FETCH_ASSOC);

// Initialize an empty array to store the products
$products = array();

foreach($results as $row)
{
$product = array("id"=>$row["id"],
"name"=>$row["name"],
"price"=>$row["price"]
);

// Add the product array to the products array
array_push($products, $product);

}


?>

<!DOCTYPE html>
<html>
<head>
<title>Product Information</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>

<div class="container">

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

<?php

// Start the session
session_start();

// Check if the success message is set
if(isset($_SESSION['success_message'])){

// Display the success message
echo '<div class="alert success">
<p>'.$_SESSION['success_message'].'</p>
<span class="close">&times;</span>
</div>';

// Unset the success message
unset($_SESSION['success_message']);

}

// Check if the warnning message is set
elseif(isset($_SESSION['warnning_message'])){

// Display the warnning message
echo '<div class="alert warnning">
<p>'.$_SESSION['warnning_message'].'</p>
<span class="close">&times;</span>
</div>';

// Unset the warnning message
unset($_SESSION['warnning_message']);

}

// Check if the error message is set
elseif(isset($_SESSION['error_message'])){

// Display the error message
echo '<div class="alert error">
<p>'.$_SESSION['error_message'].'</p>
<span class="close">&times;</span>
</div>';

// Unset the error message
unset($_SESSION['error_message']);

}


?>

<h1>Product Information</h1>
<div class="form-row">
<label for="product-id">Product ID:</label>
<input type="number" name="product-id" id="product-id" required>
</div>
<div class="form-row">
<label for="product-name">Product Name:</label>
<input type="text" name="product-name" id="product-name" required>
</div>

<div class="form-row">
<label for="product-price">Product Price:</label>
<input type="text" name="product-price" id="product-price" required>
</div>
<div class="form-row">
<button type="button" id="btn-first">First</button>
<button type="button" id="btn-next">Next</button>
<button type="button" id="btn-previous">Previous</button>
<button type="button" id="btn-last">Last</button>
</div>
<div class="form-row">
<button type="submit" id="btn-add" name="add">Add</button>
<button type="submit" id="btn-edit" name="edit">Edit</button>
<button type="submit" id="btn-remove" name="remove">Remove</button>
</div>
</form>

<div id="table-container">
<table id="products-table">

<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php
// display all products from the database
foreach($results as $row)
{
echo '<tr onclick="getRowData(this)">';
echo '<td>'.$row['id'].'</td>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['price'].'</td>';
echo '</tr>';
}

?>
</tbody>

</table>
</div>

</div>


<script>

/* get the selected html table row */

function getRowData(row)
{
// Get the cells in the clicked row
const cells = row.getElementsByTagName("td");
// Extract the data from each cell
const id = cells[0].textContent;
const name = cells[1].textContent;
const price = cells[2].textContent;

// Populate the input fields with the data
document.getElementById("product-id").value = id;
document.getElementById("product-name").value = name;
document.getElementById("product-price").value = price;

}

/**************/


/* close the message alert */

document.querySelectorAll(".close").forEach(function(closeButton){
closeButton.addEventListener('click', function(){

closeButton.parentElement.style.display = "none";

});

});

/**************/



/*** navigation buttons ***/

// convert the PHP array to a JavaScript object in JSON format.
const products = <?php echo json_encode($products); ?>
// Get the buttons
const btnFirst = document.getElementById('btn-first');
const btnNext = document.getElementById('btn-next');
const btnPrevious = document.getElementById('btn-previous');
const btnLast = document.getElementById('btn-last');

// Define a variable to keep track of the current index
let currentIndex = 0;

// Function to update the form fields based on the current index
function updateForm(){

const product = products[currentIndex];
document.getElementById('product-id').value = product.id;
document.getElementById('product-name').value = product.name;
document.getElementById('product-price').value = product.price;

}

function handleButtonClick(e)
{
switch(e.target.id)
{
case'btn-first':
currentIndex = 0;
break;
case'btn-next':
currentIndex = Math.min(currentIndex + 1, products.length - 1);
break;
case'btn-previous':
currentIndex = Math.max(currentIndex - 1, 0);
break;
case'btn-last':
currentIndex = products.length - 1;
break;
default:
break;
}

updateForm();

}

// Add event listeners to the buttons
btnFirst.addEventListener('click', handleButtonClick);
btnNext.addEventListener('click', handleButtonClick);
btnPrevious.addEventListener('click', handleButtonClick);
btnLast.addEventListener('click', handleButtonClick);


// Initialize the form
updateForm();


</script>

</body>
</html>





Code Explanation:

Database Connection and Data Retrieval: The code establishes a connection to a database through the 'db_connect.php' file and subsequently executes a SQL query aimed at fetching all product records from the "product" table, with the retrieved results being stored in an array.

Displaying Products: Displays product information in an HTML table, including ID, name, and price, and allows users to click on a row to select a product, which populates the input fields for editing.

Navigation Buttons: Implement navigation buttons such as 'First,' 'Next,' 'Previous,' and 'Last' to facilitate browsing through the product list. 
These buttons enable users to switch between products displayed in the HTML form input fields.

CRUD Operations: This interface contains input fields for product ID, name, and price, along with corresponding buttons to add, edit, or remove products. The "Add" button inserts new products, "Edit" updates existing product details, and "Remove" deletes products from the database.

Form Submission Handling (operations.php): In the operations.php file, form submissions for adding, editing, and removing products are managed securely using prepared statements to interact with the database. 
The code includes checks for successful or failed database operations and sets appropriate session messages based on the outcomes.

Message Alerts: The code checks session variables containing success, warning, or error messages, and showcases them in colored alert boxes, usually linked to database operations.

JavaScript Code: The getRowData function is employed to retrieve data from the selected row in the product table and populate the input fields.



OUTPUT:










if you want the source code click on the download button below










PHP CRUD Application with PDO and OOP

How to Create a CRUD Application with PHP, PDO, and OOP

How to Build a CRUD Application with PHP, PDO, and OOP


In this PHP tutorial we will see how to create a CRUD (Create, Read, Update, Delete) project with mysql database using PHP PDO and OOP (object oriented programming).

What We Will Use To Build This Project ? :
- PHP Programming Language.
- JavaScript Programming Language.
- HTML & CSS.
- VSCode Editor.
- MySQL Database.
- PhpMyAdmin.







Project Source Code:


------------ Create A Class "db_connect" To Connect Our Form With Database

This file establishes a connection to a MySQL database using PDO (PHP Data Objects). 
It sets up the connection parameters like the server name, username, password, and database name.

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "products_manager";

try{
$conn = new PDO("mysql: host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex){
echo"connection failed: " . $ex->getMessage();
die();
}

?>


------------ On The Index Page ------------

This file starts a PHP session, displays a form for searching, adding, editing, and removing products, and pre-populates form fields with product details if a search result is found in the session.

<?php

session_start();

?>

<!DOCTYPE html>
<html>
<head>
<title>Index</title>
<link rel="stylesheet" href="style.css">

</head>
<body>

<h1>CRUD POO</h1>
<div class="form-container">

<?php

$id = "";
$name = "";
$description = "";
$category = "";
$price = "";

if(isset($_SESSION['search-result']))
{
$product = $_SESSION['search-result'];
$id = $product['id'];
$name = $product['name'];
$description = $product['description'];
$category = $product['category'];
$price = $product['price'];
}

?>


<form action="functions.php" method="post">
<div class="search-container">
<input type="number" name="id" id="product-id" value="<?php echo $id ?>"
placeholder="id">
<input type="submit" name="search" value="Search" id="search-button">
</div>
<input type="text" name="name" id="product-name" value="<?php echo $name ?>"
placeholder="name">
<input type="text" name="category" id="product-category" value="<?php echo $category ?>"
placeholder="category">
<input type="text" name="description" id="product-description"
value="<?php echo $description ?>" placeholder="description">
<input type="text" name="price" id="product-price" value="<?php echo $price ?>"
placeholder="price">

<input type="submit" name="add" value="Add Product" id="add-button">
<input type="submit" name="edit" value="Edit Product" id="edit-button">
<input type="submit" name="remove" value="Remove Product" id="remove-button">
</form>
</div>

<?php

unset($_SESSION['search-result'])
?>

</body>

</html>



------------ The Product Class ------------

This file defines a Product class with private properties for product details such as name, description, category, and price. 
This class provides methods to save new products to the database, update existing product records, remove products from the database, and search for products by their unique ID.

<?php

// Including the required database connection file
require_once 'db_connect.php';

// Class definition for the Product entity
class Product
{
private $name;
private $description;
private $category;
private $price;

// Constructor to initialize the Product object with provided values
public function __construct($name, $description, $category, $price)
{
$this->name = $name;
$this->description = $description;
$this->category = $category;
$this->price = $price;
}

// Method to save the Product to the database
public function saveToDatabase()
{
global $conn;
$stmt = $conn->prepare("INSERT INTO `products2`(`name`, `category`, `description`, `price`)
VALUES (:name, :category, :description, :price)");
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':category', $this->category);
$stmt->bindParam(':description', $this->description);
$stmt->bindParam(':price', $this->price);

return $stmt->execute();
}

// Method to update the Product in the database
public function updateInDatabase($productId)
{
global $conn;
$stmt = $conn->prepare("
UPDATE `products2` SET `name`=:name,`category`=:category,
`description`=:description,`price`=:price WHERE `id`=:id");
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':category', $this->category);
$stmt->bindParam(':description', $this->description);
$stmt->bindParam(':price', $this->price);
$stmt->bindParam(':id', $productId);

return $stmt->execute();
}

// Static method to remove a Product from the database
public static function removeFromDatabase($productId)
{
global $conn;
$stmt = $conn->prepare("DELETE FROM `products2` WHERE `id`=:id");
$stmt->bindParam(':id', $productId);
return $stmt->execute();
}

// Static method to search for a Product by its ID
public static function searchById($productId)
{
global $conn;
$stmt = $conn->prepare("SELECT * FROM `products2` WHERE `id`=:id");
$stmt->bindParam(':id', $productId);
$stmt->execute();
return $stmt->fetch(PDO::FETCH_ASSOC);
}

}

?>

------------ The Functions File ------------

This file includes the Product class definition and the db_connect file and handles form submissions from the index page. 
If the "Add Product" button is clicked, it creates a new Product instance and saves it to the database. 
If the "Edit Product" button is clicked, it creates a new Product instance and updates the product in the database. 
If the "Remove Product" button is clicked, it removes the product from the database. 
If the "Search" button is clicked, it searches for a product by ID, stores the result in a session variable, and redirects back to the index page to display the search result.


<?php

require_once 'Product.php';

// Add a new product
if(isset($_POST['add']))
{
// Get product details from the form
$productName = $_POST['name'];
$productCategory = $_POST['category'];
$productDescription = $_POST['description'];
$productPrice = $_POST['price'];

// Create a new Product instance
$product = new Product($productName, $productDescription, $productCategory, $productPrice);

// Save the product to the database
if($product->saveToDatabase())
{
echo'product inserted';
}
else{
echo'product not inserted';
}
}

// Edit an existing product
if(isset($_POST['edit']))
{
// Get product details from the form
$productId = $_POST['id'];
$productName = $_POST['name'];
$productCategory = $_POST['category'];
$productDescription = $_POST['description'];
$productPrice = $_POST['price'];

// Create a new Product instance
$product = new Product($productName, $productDescription, $productCategory, $productPrice);

// Update the product in the database
if($product->updateInDatabase($productId))
{
echo'product updated';
}
else{
echo'product not updated';
}
}


// Remove a product
if(isset($_POST['remove']))
{
// Get the product ID from the form
$productId = $_POST['id'];

// Remove the product from the database
if(Product::removeFromDatabase($productId))
{
echo'product removed';
}
else{
echo'product not removed';
}
}


// Search for a product
if(isset($_POST['search']))
{
// Get the product ID from the form
$productId = $_POST['id'];
// Search for products by ID
$product = Product::searchById($productId);
// Start a session
session_start();
// Store the search result in a session variable
$_SESSION['search-result'] = $product;

/* $test = $_SESSION['search-result'];
echo $test['name'].'<br>';
echo $test['price']; */

// Redirect to the next page to display the search results in a form
header("Location: index.php");
exit();
}

?>



                                          


////// OUTPUT : 


How to Implement CRUD Operations with PDO and OOP in PHP