Upload MySQL PHP server image - form / data

0

I have a form to upload the data of a cabin to a table called "cabins" and the images chosen through the input property "file" to the table "images".

The problem I have is that I do not upload the images. What am I doing wrong?

Screen output: Ocurrió algun error al copiar el archivo. Always!

Code of the HTML + PHP form:

<?php
    header("Content-Type: text/html;charset=utf-8");
    require_once "Clases/BD.php";
    require_once "Clases/Cabanas.php";
    require_once "conexion.php";

    //Iniciar una nueva sesión o reanudar la existente.
    session_start();
    //Si existe la sesión "administrador"..., la guardamos en una variable.
    if (isset($_SESSION['administrador'])){
        $administrador = $_SESSION['administrador'];
    }

    //Si pulsamos el botón "Guardar"... 
    //Realizamos el "INSERT" antes que el "SELECT" para que se actualice la tabla correctamente.
    if(isset($_POST["guardar"])){
        $nombre = $_POST["nombre"];
        $capacidad = $_POST["capacidad"];
        $descripcion = $_POST["descripcion"];
        $precio = $_POST["precio"];
        //Llamamos al método "anadirCabana" y le pasamos los parámetros del formulario.
        BD::anadirCabana($nombre, $capacidad, $descripcion, $precio);
        //Llamamos al método "insertarImagen" y le pasamos los parámetros del formulario.
        //BD::insertarImagen($idimagen, $ruta, $idcabana);

        // Comprobamos si ha ocurrido un error.
        if (!isset($_FILES["imagen"]) || $_FILES["imagen"]["error"] > 0){
            echo "Ha ocurrido un error.";
        }else{
            // Verificamos si el tipo de archivo es un tipo de imagen permitido.
            // y que el tamaño del archivo no exceda los 16MB
            $permitidos = array("image/jpg", "image/jpeg", "image/gif", "image/png");
            $limite_kb = 16384;

            if (in_array($_FILES['imagen']['type'], $permitidos) && $_FILES['imagen']['size'] <= $limite_kb * 1024){
                // Archivo temporal
                $imagen_temporal = $_FILES['imagen']['tmp_name'];

                // Tipo de archivo
                $tipo = $_FILES['imagen']['type'];

                // Leemos el contenido del archivo temporal en binario.
                $fp = fopen($imagen_temporal, 'r+b');
                $imagen = fread($fp, filesize($imagen_temporal));
                fclose($fp);

                //Podríamos utilizar también la siguiente instrucción en lugar de las 3 anteriores.
                // $imagen=file_get_contents($imagen_temporal);

                // Escapamos los caracteres para que se puedan almacenar en la base de datos correctamente.
                $imagen = mysql_escape_string($imagen);

                // Insertamos en la base de datos.
                $sql = BD::anadirImagen($imagen, 4);
                if($sql==1){
                    echo "El archivo ha sido copiado exitosamente.";
                }else{
                    echo "Ocurrió algun error al copiar el archivo.";
                }
            }else{
                echo "Formato de archivo no permitido o excede el tamaño límite de $limite_kb Kbytes.";
            }
        }
    }
?>

<!DOCTYPE html>
<html lang="es">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Panel del administrador</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <script type="text/javascript" src="js/validar_formulario_cabana.js"></script>
        <script type="text/javascript" src="js/ocultar_mostrar.js"></script>
    </head>
    <body>
        <div id="sesion_administrador">
            <?php 
            if(isset($_SESSION['administrador'])){
                echo "Bienvenido ".$administrador."&nbsp;&nbsp;&nbsp;";
                echo "<a href='salir_administrador.php?salir=1'>Salir</a>"; //GET
                //_REQUEST = $_POST o $_GET
                if(isset($_REQUEST["salir"])){
                    unset($_SESSION["administrador"]);
                    header("Refresh:0; url=iniciar_sesion_administrador.php");
                }
            }
            ?>
        </div>

        <form action="<?php echo $_SERVER['PHP_SELF'];?>" name="tabla_datos_cabana" id="tabla_datos_cabana" method="POST">
            <div id="mostrar_cabanas">
            <br/><br/><br/>
                <table class="table table-striped" name="tabla" width="600" border="2" cellspacing="3" cellpadding="3" style="font-size: 10pt">
                    <center>
                        <tr>
                            <thead style="background-color:#A9F5A9">
                                <td width=\"150\">
                                    <font face="verdana" color="blue"><b><center>ID Cabaña</center></b></font>
                                </td>
                                <td width=\"250\">
                                    <font face="verdana" color="blue"><b><center>Nombre</center></b></font>
                                </td>
                                <td width=\"150\">
                                    <font face="verdana" color="blue"><b><center>Modificar</center></b></font>
                                </td>
                                <td width=\"150\">
                                    <font face="verdana" color="blue"><b><center>Eliminar</center></b></font>
                                </td>
                            </thead>
                        </tr>
                        <?php
                        $datos = BD::obtenerCabanas();
                        foreach($datos as $cabana){
                            echo "<tr>";
                                echo "<td width=\"150\"><font face=\"verdana\"><font size='2'><center>".$cabana->getIdcabana()."</center></font></font></td>";
                                echo "<td width=\"250\"><font face=\"verdana\"><font size='2'><center>".$cabana->getNombre()."</center></font></font></td>";
                                echo "<td width=\"150\"><font face=\"verdana\"><font size='2'><center>"?> 
                                    <a href="modificar.php?idcabana=<?=$cabana->getIdcabana();?>">
                                        <img src="imagenes/modificar.png" height='24' width='26' onmouseover="this.src='imagenes/modificar_in.png';" onmouseout="this.src='imagenes/modificar.png';">
                                    </a> <?php "</center></font></font></td>";
                                echo "<td width=\"150\"><center><input type='checkbox' name='marcados[]' id='marcados[]' value=".$cabana->getIdcabana()."></center>";
                            echo "</tr>";
                        }
                        ?>
                    </center>
                </table>

                <!-- Botón NUEVA cabaña -->
                <div class="boton_anadir" class="table-responsive" align="left">
                    <font face="verdana">
                        <b><input type="button" style="width:200px; height:28px;" name="nueva_cabana" id="nueva_cabana" value="Añadir cabaña" /></b>
                    </font>
                </div>

                <!-- Botón ELIMINAR cabaña/s -->
                <div class="boton_eliminar" class="table-responsive" align="left">
                    <font face="verdana">
                        <b><input type="submit" style="width:200px; height:28px;" name="eliminar_cabanas" id="eliminar_cabanas" onclick="return confirm('¿Deseas realmente eliminar estas cabañas?');" value="Eliminar cabañas" /></b>
                    </font><br/>
                </div>

                <?php
                //Si pulsamos el botón "Eliminar cabañas"...
                if(isset($_POST['eliminar_cabanas'])){
                    if(empty($_POST['marcados'])){
                        echo "<h4><center>No se ha seleccionado ninguna cabaña.</center></h4>";
                    }else{
                        foreach($_POST['marcados'] as $valor){
                            //Nos conectamos a la base de datos.
                            $conexion = mysqli_connect("localhost", "root", "root", "osmarrural");
                            //Realizamos la consulta.
                            $sql = sprintf("DELETE FROM cabanas WHERE idcabana='%d'", $valor);
                            $resultado = mysqli_query($conexion, $sql);
                            /*
                            $mysqli = new mysqli_connect("localhost", "root", "root", "osmarrural");
                            $stmt = $mysqli->prepare("DELETE FROM cabanas WHERE idcabana = ?");
                            $stmt->bind_param('i', $valor);
                            $stmt->execute();
                            $stmt->close();
                            */
                        }
                        echo "<meta http-equiv=\"refresh\" content=\"0; URL=panel_administrador.php\">";
                    }
                }
                ?>
            </div>
        </form>

        <br/><br/><br/>
        <!-- Añadir una cabaña -->
        <form action="<?php echo $_SERVER['PHP_SELF'];?>" enctype="multipart/form-data" name="anadir" id="anadir" method="POST" onsubmit="return validar_formulario_cabana();">
            <label for="nombre">Nombre: </label>
                <input type="text" id="nombre" name="nombre" />
            <br/><br/>
            <label for="capacidad">Capacidad: </label>
                <?php
                echo "<select name='capacidad'>";
                for($i=1; $i<11; $i++){
                    if($i==1){
                        echo "<option value='$i' selected='selected'>$i</option>";
                    }else{
                        echo "<option value='$i'>$i</option>";
                    }
                }
                echo "</select>";
                ?>
            <br/><br/>
            <label for="descripcion">Descripción: </label>
                <input type="text" id="descripcion" name="descripcion" />
            <br/><br/>
            <label for="precio">Precio: </label>
                <input type="text" id="precio" name="precio" onkeypress="return soloNumeros(event);" />
            <br/><br/>

            <!-- Subir archivos chmod("./carpeta_upload/",755); -->
            <label for="imagen">Imagen:</label>
                <input type="file" name="imagen" id="imagen" /> <!-- multiple="multiple" -->
            <br/><br/>

            <input type="submit" value="Guardar" id="guardar" name="guardar" />
            <input type="reset" value="Resetear" id="resetear" name="resetear" />
        </form>
    </body>
</html>

PHP code in the .sql file called BD

 static public function anadirCabana($nombre, $capacidad, $descripcion, $precio){
        $ejecucion = self::Conexion();
        $sql = "INSERT INTO cabanas (nombre, capacidad, descripcion, precio) VALUES ('".$nombre."', ".$capacidad.", '".$descripcion."', ".$precio.")";
        $ok = $ejecucion->exec($sql);
        if($ok==1){
            return true;
        }else{
            return false;
        }
    }


    static public function anadirImagen($ruta, $idcabana){
        $ejecucion = self::Conexion();
        $sql = "INSERT INTO imagenes (ruta, idcabana) VALUES ('".$ruta."', ".$idcabana.")";
        $ok = $ejecucion->exec($sql);
        if($ok==1){
            return true;
        }else{
            return false;
        }
    }

I add screenshot of the value I get in "echo $ image" to see what it gives me back ...

    
asked by omaza1990 07.12.2017 в 17:21
source

1 answer

3

You must arm the variable $ images with the name you need to save, try first sending a string of test text such as "images.jpg" if you save it means you are wrongly arming the name, as I said I do not see where you arm it, it should be like this:

$imagen = $filename.'.'.$type; 

And this you send in the function:

$sql = BD::anadirImagen($imagen, 4);

Now if you want to encrypt the name or pass it to another format, it would be about the variable $ image already with the name well armed and depending on the format, you should change the data type of the field in your table.

    
answered by 07.12.2017 / 19:46
source