1

I am new to PHP, I make a form to insert in a database and I can not insert an error when I want to insert the image, in the database the type of the image is "longblob", I enclose the form and the. PHPto insert in the database.

Form:

<form align="center" action="guardar.php" method="POST" enctype="multipart/form-data">
    <input type="text" REQUIRED name="titulo" placeholder="Titulo.." value=""/><br><br>
    <input type="text" REQUIRED name="contenido" placeholder="Contenido.." value=""/><br><br>
    <input type="text" REQUIRED name="fecha" placeholder="Fecha.." value=""/><br><br>
    <input type="file" REQUIRED name="imagen" /><br><br>
    <input type="submit" name="Aceptar" />
</form>

PHP

<?php

include("conexion.php");

$titulo=$_POST['titulo'];
$contenido=$_POST['contenido'];
$fecha=$_POST['fecha'];
$imagen=addslashes(file_get_contents($_FILES['imagen']['tmp_name']));

$query="INSERT INTO articulos(titulo,contenido,fecha,imagen) VALUES('$titulo','$contenido','$fecha','$imagen')";

mysqli_query($conexion, $query);
$resultado=$conexion->query($query);

if($resultado){
    echo "INSERT";
}else{
    echo "No INSERT";
}

?>
3
  • 1
    Welcome to Stack Overflow! Your script is at risk for SQL Injection Attacks.. Simply put, don't use addslashes, mysql*_escape_string. You should be binding the actual variables to your query. Commented Oct 19, 2018 at 13:52
  • 1
    It's better to save image on the server and save in the db only a refer to the img Commented Oct 19, 2018 at 13:54
  • Why are you using file_get_contents()? Commented Oct 19, 2018 at 14:36

1 Answer 1

1

You should not use file_get_contents(), this is the wrong function for this - it does something else entirely (you can read the manual if you are curious what this function does). Instead of using a query that injects values directly, you should also use a prepared statement, as shown below.

This will prevent SQL-injection attacks, and make sure that no data will break the query.

<?php

include "conexion.php";

$titulo = $_POST['titulo'];
$contenido = $_POST['contenido'];
$fecha = $_POST['fecha'];
$imagen = $_FILES['imagen']['tmp_name'];

$query = "INSERT INTO articulos (titulo, contenido, fecha, imagen) VALUES (?, ?, ?, ?)";

if ($stmt = $conexion->prepare($query)) {
    $stmt->bind_param("ssss", $titulo, $contenido, $fecha, $imagen);
    if ($stmt->execute()) {
        echo "Inserted");
    } else {
        // Do some logging
        error_log($stmt->error);
        echo "Not inserted";
    }
} else {
    // Do some logging
    error_log($conexion->error);
    echo "Not inserted";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.