Affichage des articles dont le libellé est Create an Array Navigation Form with JavaScript. Afficher tous les articles
Affichage des articles dont le libellé est Create an Array Navigation Form with JavaScript. 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










JavaScript - Array Navigation Form with JavaScript and HTML

How to Create an Array Navigation Form with JavaScript and HTML 


How to Create an Array Navigation Form with JavaScript and HTML


In this Javascript Tutorial, we will see how to create an interactive form for navigating through an array of data.
Users can click navigation buttons to view the details of different people from the array, the form fields and image are updated accordingly.



Project Source Code:



<!DOCTYPE html>
<html>
<head>
<title>Array Navigation Form</title>

<style>
*{margin: 0; padding: 0; box-sizing: border-box;}

body{ font-family: Arial, sans-serif; background-color: #f2f2f2; }

.container{ background-color: #fff; padding: 20px; margin: 50px auto;
width: 50%; border-radius: 5px; box-shadow: 0 0 10px rgba(0, 0, 0, 0.2)
}

form button{ padding: 10px 20px; background-color: #4caf50; color: #fff;
border: none; border-radius: 5px; margin: 10px; width: 21%;
cursor: pointer; text-transform: uppercase;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
transition: all 0.3s ease-in-out;
}
form button:hover{ background-color: #3e8e41; }

div label{ display: inline-block; margin: 10px 0; font-weight: bold; color: #444;
text-align: right; width: 22%; font-size: 20px;
}

div input[type="text"]{ display: inline-block; margin: 10px; padding: 10px; border: none;
border-radius: 5px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
transition: all 0.3s ease-in-out; width: 70%; }

div input[type="text"]:focus{ outline: none; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);}
#image{ display: flex; align-items: flex-start; }
#image label{margin-right: 10px;}

#image img{ margin: 10px; width: 30%; border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}


</style>

</head>
<body>

<div class="container">
<form>
<button id="first-btn">First</button>
<button id="next-btn">Next</button>
<button id="prev-btn">Previous</button>
<button id="last-btn">Last</button>
</form>
<div class="inputs">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br>
<label for="age">Age:</label>
<input type="text" id="age" name="age">
<br>
<label for="dob">Date of Birth:</label>
<input type="text" id="dob" name="dob">
<br>
<div id="image">
<label for="pic">Image:</label>
<img id="pic" src="">
</div>
</div>
</div>


<script>

// Define an array of objects with properties name, age, dob and image
const peoples = [
{name:"Alice", age:25, dob:new Date("1997-03-15"), image:"images/avatar1.png"},
{name: "Bob", age: 32, dob: new Date("1990-09-02"), image: "images/avatar2.png"},
{name: "Charlie",age: 42,dob: new Date("1980-05-20"),image: "images/avatar3.png"},
{name: "David",age: 28,dob: new Date("1994-12-06"),image: "images/avatar4.png"},
{name: "Emma",age: 35,dob: new Date("1987-07-19"),image: "images/avatar5.png"},
{name: "Frank",age: 50,dob: new Date("1972-10-31"),image: "images/avatar6.png"},
{name: "Grace",age: 22,dob: new Date("2000-01-01"),image: "images/avatar7.png"}
];

// Initialize the currentIndex variable to 0
let currentIndex = 0;

// Define a function to navigate through the array
function navigateArray(event){
event.preventDefault();

// Check which button was clicked and update the currentIndex accordingly
switch(event.target.id){
case 'first-btn':
currentIndex = 0;
break;
case 'next-btn':
currentIndex = currentIndex <peoples.length-1 ? currentIndex + 1 : peoples.length - 1;
break;
case 'prev-btn':
currentIndex = currentIndex > 0 ? currentIndex - 1 : 0;
break;
case 'last-btn':
currentIndex = peoples.length - 1;
break;

}

// Update the UI with the current item by setting the value of input elements
// and image source to corresponding properties
document.getElementById('name').value = peoples[currentIndex].name;
document.getElementById('age').value = peoples[currentIndex].age;
// Display date in yyyy-mm-dd format
document.getElementById('dob').value = peoples[currentIndex].dob.toLocaleDateString();
document.getElementById('pic').src = peoples[currentIndex].image;

}


// Add click event listeners to navigation buttons
document.getElementById('first-btn').addEventListener('click', navigateArray);
document.getElementById('next-btn').addEventListener('click', navigateArray);
document.getElementById('prev-btn').addEventListener('click', navigateArray);
document.getElementById('last-btn').addEventListener('click', navigateArray);

// Initialize the UI with the values of the first object in the array
document.getElementById('name').value = peoples[currentIndex].name;
document.getElementById('age').value = peoples[currentIndex].age;
// Display date in yyyy-mm-dd format
document.getElementById('dob').value = peoples[currentIndex].dob.toLocaleDateString();
document.getElementById('pic').src = peoples[currentIndex].image;

</script>
</body>
</html>





Code Explanation:

this JavaScript code, allows users to navigate through an array of data and images by clicking on navigation buttons.

This JavaScript code performs the following actions:

1 - Create an array called 'peoples,' containing objects with properties such as name, age, date of birth (dob), and an image URL for each person.

2 - Create a function called navigateArray(event) that handles button clicks and updates the form based on the clicked button.

3 - Event listeners are added to each of the navigation buttons to trigger the navigateArray function when they are clicked.

4 - The initial values in the input fields and the image source are set to the properties of the first person in the peoples array.




OUTPUT:

Array Navigation Form with JavaScript and HTML