I'm trying to validate the user input and query to delete the record which have the same name. I'm using phpStorm for coding
I have tried to go over the typo, format of the code and check the query in phpAdmin and it's working fine
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 3/24/2019
* Time: 4:38 PM
*/
// Include config file
require_once "config.php";
$product_name= '';
$product_name_err = '';
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
if(empty(trim($_POST["product_name"]))){
$product_name_err = "Please enter the product name.";
} else{
$product_name = trim($_POST["product_name"]);
}
//Delete the data in the product table
$sql = "DELETE FROM `products` WHERE `name` = '$product_name'";
if ($product_name_err =''){
mysqli_query($link,$sql);
}
}
?>
<?php include "header_admin.php"?>
<div class="wrapper">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group" <?php echo (!empty($product_name_err)) ? 'has-error' : ''; ?>>
<label>Product name</label>
<input type="text" name="product_name" class="form-control" >
<span class="help-block"><?php echo $product_name_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Delete Item">
</div>
</form>
</div>
<?php include "footer.php"?>
I expect the preceding code to check if the field is blank and the query delete that matched record on the database but either of them seem to work properly. The $product_name seem not received any value at all.
The below code should work correctly. There was a typo in your confition: if ($product_name_err =''){
should be if ($product_name_err ==''){
Also, your code was vunerable to injection attacks, which is fixed below by using the mysqli_escape_string
function.
if($_SERVER["REQUEST_METHOD"] == "POST") {
$product_name = mysqli_escape_string($link, trim($_POST["product_name"]));
if(empty($input)){
$product_name_err = "Please enter the product name.";
}
//Delete the data in the product table
$sql = "DELETE FROM `products` WHERE `name` = '$product_name'";
if($product_name_err == ''){
mysqli_query($link,$sql);
}
}
Your if condition is incorrect, use '==' instead of '='.
if ($product_name_err ==''){
mysqli_query($link,$sql);
}
also you should really consider using prepared statements to prevent sql injection attacks and it does other nice things for you like you not having to escape ' or " characters from your strings.
Php code check will help to check your PHP code. May be it will help you.
An advanced, custom PHP code checker that searches your code for common, hard to find typos and mistakes; includes a syntax check.