I have the following form on my website where it adds a supplier to the database. The database suppliers table has
id(AI),
name(varchar),
company(varchar),
phone(int),
avatar(varchar)
Nothing is allowed to be null, the avatar column is a path to an image that the admin uploads, I have a DEFAULT path to an image called "def.jpg", now if I upload an image it inserts to the database successfully, but whenever I send it null, MySQL does not use the DEFAULT path set and hence why it also fails to insert the record at all, it is 100% correct path.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$uploadError = '';
if (isset($_POST['submit'])) {
include 'db.php';
$sName = $_POST['sName'];
$company = $_POST['sCmp'];
$phone = $_POST['sNumber'];
$type = isset($_FILES['sPhoto']) ? (explode('.', $_FILES['sPhoto']['name'])) : null;
if (!empty($type)) { //a file was upload
$type = end($type); //get the extension
$allowed = ['png', 'jpg'];
if (in_array($type, $allowed)) { //type is allowed
$tmp_name = $_FILES['sPhoto']['tmp_name'];
$name = $_FILES['sPhoto']['name'];
$target_dir = 'assets/images/suppliers/';
//move the file to the target location
$target_file = $target_dir . basename($_FILES["sPhoto"]["name"]);
move_uploaded_file($tmp_name, $target_file);
} else { //not allowed so we set error message
$uploadError = 'This type isnt allowed!';
echo($uploadError);
}
} else { //no file was passed in so we let it continue to insert
$target_file = null;
}
if (empty($uploadError)) { //no errors, so we insert
$sql = "INSERT INTO suppliers (name,company,phone,avatar) VALUES (?,?,?,COALESCE(?, avatar, DEFAULT(avatar)));";
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "ssis", $sName, $company, $phone, $target_file);
mysqli_stmt_execute($stmt);
}
} else {
if (isset($_POST['delSubmit'])) {
include 'db.php';
$name = $_POST['name'];
$sql = "DELETE FROM suppliers WHERE name = ?;";
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "s", $name);
mysqli_stmt_execute($stmt);
}
}
?>
<!-- ***** Preloader Start ***** -->
<div id="preloader">
<div class="jumper">
<div></div>
<div></div>
<div></div>
</div>
</div>
<!-- ***** Preloader End ***** -->
<!-- Header -->
<header class="">
<?php
session_start();
if (isset($_SESSION['email'])) {
if ($_SESSION['email'] === 'admin@allday.com') {
include 'navadmin.php';
} else {
include 'navuser.php';
}
} else {
include 'nav.php';
}
?>
After I've read some comments below, I've checked that whenever I do not upload an image , it goes into " this type is not allowed " block, instead of using MySQL's DEFAULT value.