create a folder called products in c:\wamp64\www
php files should be placed at c:\wamp64\www\products
Explanation of codes for List All Products
#1 Create a php file called db_connect.php
<?php /** * A class file to connect to database */ class DB_CONNECT { var $myconn; /** * Function to connect with the database */ function connect() { define('DB_USER', "root"); // db user define('DB_PASSWORD', ""); // db password (mention your db password here) define('DB_DATABASE', "mydatabase"); // database name define('DB_SERVER', "localhost"); // db server // import database connection variables //require_once __DIR__ . '/db_config.php'; // Connecting to mysql database $con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD,DB_DATABASE) or die(mysqli_error($con)); $this->myconn = $con; // returning connection cursor return $this->myconn; } /** * Function to close db connection */ function close($myconn) { // closing db connection mysqli_close($myconn); } } ?>
These 4 lines contains the username and password to the wampserver,
the database name and server location
in this case is locahost (if need server is at remote site enter URL or the ip address instead)
define('DB_USER', "root"); // db user define('DB_PASSWORD', ""); // db password (mention your db password here) define('DB_DATABASE', "mydatabase"); // database name define('DB_SERVER', "localhost"); // db server
#2 List All Products Create a php file called get_all_products.php
<html>
<body>
<?php
/*
* Following code will list all the products
*/
$htmlDisplay="<h1> Search Results: </h1>";
$htmlDisplay= $htmlDisplay. "<table border='1'>";
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db= new DB_CONNECT();
$db->connect();
// get all products from products table
$sqlCommand="SELECT *FROM products";
$result =mysqli_query($db->myconn, "$sqlCommand");
/*
CREATE TABLE IF NOT EXISTS `products` (
`pid` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`price` decimal(10,2) NOT NULL,
`description` text,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`pid`)
)
*/
// printing table headers
$htmlDisplay = $htmlDisplay ."<th> Pid </th><th> Name </th>";
// check for empty result
if (mysqli_num_rows($result) > 0) {
// looping through all results
foreach($result as $row)
{
$htmlDisplay = $htmlDisplay ."<tr> <td>".$row["pid"]. "</td>";
$htmlDisplay = $htmlDisplay ."<td>".$row["name"]. "</td></tr>";
//Modify the codes...to include other columns like price, decription
//See the expected output as shown in the picture below:
}
$htmlDisplay =$htmlDisplay."</table>";
echo $htmlDisplay;
} else {
// no products found
echo "<h1> Not found </h1>";
}
$db->close($db->myconn);
?>
</body>
</html>
</table>
Expected Output
Explanation of codes for Search Product
html codes for the form
<html> <body> <h2>Search Product Details</h2> <form action="get_product_details.php" method="post"> Product ID:<br> <input type="text" name="pid" required> <br> <br> <input type="submit" value="Submit"> </form> <br> <a href="get_all_products.php"> List All Products </a> </body> </html>
Create a file called get_product_details.php:
Copy and paste the codes from get_all_products.php and save it to searchProduct.php
and modify as follows:
Add the follow codes :
// check for post data
if (isset($_POST["pid"])) {
$pid = $_POST['pid'];
as shown below:
and the closing braces }
$db->close($db->myconn);
}
?>
</body>
</html>
</table>
Modify the Sql statement to
// get all products from products table
$sqlCommand="SELECT *FROM products WHERE pid = $pid";
#4 Now you are ready to test searchProduct.php
Explanation of codes for Add and Update Product
#5 Add Products Create a php file called addProduct.php
Add Products
Complete Codes for addProduct.php<html> <body> <h2>Add Product</h2> <?php /* * Following code will create a new product row * All product details are read from HTTP Post Request */ // check for required fields if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) { $name = $_POST['name']; $price = $_POST['price']; $description = $_POST['description']; // include db connect class require_once __DIR__ . '/db_connect.php'; // connecting to db $myConnection= new DB_CONNECT(); $myConnection->connect(); // mysql inserting a new row $sqlCommand="INSERT INTO products(name, price, description) VALUES('$name', '$price', '$description')"; $result =mysqli_query($myConnection->myconn, "$sqlCommand"); // check if row inserted or not if ($result) { // successfully inserted into database echo "Product successfully created."; } else { // failed to insert row echo "Oops! An error occurred."; } } else {
?>
<!-- Your HTML Code area -->
<form action="addProduct.php" method ="post">
Name:<br>
<input type="text" name="name" value="Thai Fragrance Rice">
<br>
Price:<br>
<input type="text" name="price" value="10.80">
<br>
Description:<br>
<input type="text" name="description" value="10kg">
<br>
<br>
<input type="submit" value="Submit">
</form>
<?php
}
?>
<!-- Your HTML Code area -->
</body>
</html>
Refer to the codes above
Note: We placed the above html codes under the else condition of
if (isset($_POST['name']) && isset($_POST['price']) && isset($_POST['description'])) { }
isset — Determine if a variable is declared and is different than NULL
if addProduct was run for the first time and it will go to else conditions
which the php page will show the html form
#6 Update Products
Create a php file called updateProduct.php
<!DOCTYPE html> <html> <body> <h2>Update Product Details</h2> <?php /*/* * Following code will update single product details* Following code will g * A product is identified by product id (pid) */ // check for post data if (isset($_POST["pid"])) { $pid = $_POST['pid']; /* * Following code will list all the products */ // include db connect class require_once __DIR__ . '/db_connect.php'; // connecting to db $db= new DB_CONNECT(); $db->connect(); // get a product from products table $sqlCommand="SELECT *FROM products WHERE pid = $pid"; $result =mysqli_query($db->myconn, "$sqlCommand"); if($result->num_rows == 0) { echo "PID: $pid Not Found"; } else { $result = mysqli_fetch_array($result); ?> <h2> Edit Product </h2> <form action="updateDetails.php" method ="post"> <input type="hidden" name="pid" value="<?php echo $pid ?>"> Name:<br> <input type="text" name="name" value= "<?php echo $result["name"] ?>" > <br> Price:<br> <input type="text" name="price" value= "<?php echo $result["price"] ?>"> <br> Description:<br> <input type="text" name="description" value= "<?php echo $result["description"] ?>"> <br> <br> <input type="submit" value="Submit"> </form> <?php } $db->close($db->myconn); } else { ?> <form action="updateProduct.php" method="post"> product ID:<br> <input type="text" name="pid" required> <br> <br> <input type="submit" value="Submit"> </form> <?php } ?>
#7 Update Product Details Create a php file called updateDetails.php
<?php /* * Following code will update a product information * A product is identified by product id (pid) */ //check for empty entries if ($_POST['pid']=='') { echo( "Required field(s) is missing"); } else { $pid = $_POST['pid']; $name = $_POST['name']; $price = $_POST['price']; $description = $_POST['description']; // include db connect class require_once __DIR__ . '/db_connect.php'; // connecting to db $db= new DB_CONNECT(); $db->connect(); // mysql update row with matched pid $sqlCommand="UPDATE products SET name = '$name', price = '$price', description = '$description' WHERE pid = $pid"; $result =mysqli_query($db->myconn, "$sqlCommand"); // check if row update or not if ($result) { // successfully updated into database echo "<h1> Data updated successfully </h1>"; } else { // failed to insert row echo "<h1> Oops! An error occurred. </h1>"; } } ?>
No comments:
Post a Comment
Note: only a member of this blog may post a comment.