Image Change name on server - PHP

4

Updated: Someone who can help me with this code friends, I have to save an image in server and database. The problem is that it saves the image on the server, but the insert query that I have is not executed.

//*--------------------------------Se guarda la imagen----------------------------*
$file = $_FILES["file"];
$nombre = getUniqueName()."";
$tipo = $file["type"];
$ruta_provisional = $file["tmp_name"];
$size = $file["size"];
$carpeta = "upload/";

switch ($tipo) {
    case 'image/jpg':
        $tipo = JPG;
        break;
    case 'image/jpeg':
        $tipo = JPEG;
        break;
    case 'image/png':
        $tipo = PNG;
        break;
    case 'image/gif':
        $tipo = GIF;
        break;
    default:
        die("Error, el archivo no es una imagen"); 
}  


$src = $carpeta.$nombre;
move_uploaded_file($ruta_provisional, $src);
changeSize($src, 500, $tipo);
echo "<img src='$src'>";

  //Aqui necesito ingresar $src a la bd, pero no se ejecuta(La sentencia esta probada y funciona correctamente)

 $con = Conectar();
    $sql = 'INSERT INTO bolsa (id, tipo_bolsa, titulo, imagen, descripcion, categoria, fecha, sueldo) VALUES (:id, :tipo_bolsa, :titulo, :imagen, :descripcion, :categoria, :fecha, :sueldo)';
    $q = $con->prepare($sql);
    $q->execute(array(':id'=>$id, ':tipo_bolsa'=>$tipo_bolsa, ':titulo'=>$titulo, ':imagen'=>$src, ':descripcion'=>$descripcion, ':categoria'=>$categoria, ':fecha'=>$fecha, ':sueldo'=>$sueldo));
    
asked by Agustin Acosta 05.01.2016 в 16:36
source

2 answers

2

Something is not clear. You say: " The problem is that if you save them but with a different name ... I have a function which gives you a unique name " and then you answer this " Well, what I really want is to give it a unique name, so that when they could upload two identical images they will not be overwritten "to @rodrigomx.

Your logic is fine. You should call the function getUniqueName () , save the name in a variable and use it as a parameter in the insert and when saving the image in the server. Unique names / id's must be assigned when saving images on your server so that they are not overwritten.

If the problem is another I think you should explain yourself better.

    
answered by 06.01.2016 в 16:31
0

I think your code works well as it should. The reason why the saved with different name is so that if they upload an image with the same name, these two images are not overwritten.

What you can do is change the following line:

$nombre = getUniqueName();

In a similar way to:

$file = $_FILES["file"];
$nombre = basename($file["name"]);

So it will use the name of the file you uploaded.

You have to notice that your code is not validating that you have actually uploaded or sent an image, so add the validations or you will have errors.

    
answered by 06.01.2016 в 01:06