Hello, I am trying to create a system to upload images to my website with PHP and SQL, I managed to get the destination system to work (that the image is stored in a folder on the server) but I have an error and it is that the information of the image is not displayed. image in the database.
CODE: create.php
<form method="post" action="./guardar_post.php" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Titulo</label>
<input type="text" id="title" class="form-control" name="title" placeholder="Titulo">
</div>
<div class="form-group">
<label for="description">Descripcion</label>
<textarea class="form-control" name="description" id="description" placeholder="Descripcion"></textarea>
</div>
<div class="form-group">
<label for="description">PORTADA</label>
<input type="file" name="image" id="image"></select>
</div>
<button type="submit" class="btn btn-primary">Agregar</button>
</form>
CODE: save_post.php
<?php
if(!empty($_POST)){
include "connection.php";
$con = connect();
var_dump($_POST["image"]);
$sql = "insert into post (title,description,image,created_at) value (\"".$_POST["title"]."\",\"".$_POST["description"]."\",\"".$_POST["image"]."\",NOW())";
if (!empty($_FILES['image']['name'])) {
$image_name = time() . '_' . $_FILES['image']['name'];
$destination = "../images/" . $image_name;
$result = move_uploaded_file($_FILES['image']['tmp_name'], $destination);
if ($result){
$_POST['image'] = $image_name;
} else {
array_push($errors, "¡Algo fallo al subir la imagen!");
}
}
$con->query($sql);
$last_id = $con->insert_id;
$categorias = get_categorias();
foreach($categorias as $cat){
if(isset($_POST["category_".$cat->id])){
var_dump($_POST["image"]);
$sql = "insert into post_category (post_id,category_id,image) value (".$last_id.",".$cat->id.",".$_POST["image"].")";
$con->query($sql);
}
}
header("Location: index.php");
}
?>
Currently the image is stored correctly on the server but it is not displayed in the database.
Your problem is that at the moment of the construction of the query that does the insert you use $_POST['image'] and at this moment that variable does not exist. You can simply replace $_POST['image'] with $_FILES['image']['name'].
This will be enough to save the image name to the database, which I assume is what you want.
I've modified your code to make a couple of recommendations. You must add a "mime_type" column to the post table that will be used later to know how to display/manipulate the image
Well, the quickest answer is the following.
first then fix the name of the file and then fix the path
I hope this is of some use to you at this point.
Edit: the tmp_name that is observed is required and cannot be modified, since it is the name that your file will be loading. Yes, you can rename the file itself by declaring a variable that stores the names