So weird well annoying problem, I'm trying to upload images from a form (all works fine) However when there is no image it should set itself to NULL, but because i'm using $target_dir . basename it keeps taking the last part of the $target_dir instead of setting to NULL and inserting the word products into the database instead of nothing. But obv need the $target_dir for when the upload takes place to put in correct place. Please see code below, all help much appreciated.
$target_dir = "../images/products/";
if (!isset ($_FILES["img1"]["name"])) {
$target_file1 = NULL;
} else {
$target_file1 = $target_dir . basename($_FILES["img1"]["name"]);
}
if (!isset ($_FILES["img2"]["name"])) {
$target_file2 = NULL;
} else {
$target_file2 = $target_dir . basename($_FILES["img2"]["name"]);
}
if (!isset ($_FILES["img3"]["name"])) {
$target_file3 = NULL;
} else {
$target_file3 = $target_dir . basename($_FILES["img3"]["name"]);
}
if (!isset ($_FILES["img4"]["name"])) {
$target_file4 = NULL;
} else {
$target_file4 = $target_dir . basename($_FILES["img4"]["name"]);
}
SQL query and relevant info
<pre>
$image1 = basename($target_file1);
$image2 = basename($target_file2);
$image3 = basename($target_file3);
$image4 = basename($target_file4);
echo $image1;
echo $image2;
echo $image3;
echo $image4;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO products (product_code, product_name, category,
filter, description, specification, img1, img2, img3, img4, price)
VALUES('$product_code', '$product_name', '$category', '$filter',
'$description', '$specification', '$image1', '$image2', '$image3',
'$image4', '$price')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
</pre>
K, changed it to set the values first and only assign value if isset
same thing, see screenshot of output below.
