Make an Insert if there is no value in a column, but make an update

1

Hi, I wanted to tell you that I want to do an Insert but check if there is a value in a column of the table before doing it, if it is an update only in the value of the column of the same.

I pass the code to you as I have it:

if(in_array($type, array('gif', 'jpg', 'jpeg', 'png', 'php'))) {


if (!file_exists($carpeta)) {
mkdir($carpeta, 0777, true);

}


    if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
        if(move_uploaded_file($_FILES['userImage']['tmp_name'], $url)) {

            // AHORA TENDRIA q verrificar si existe el nombre del archivo en 
 //la TABLA ARCHIVOS y hago un update a la fechamod del mismo/


$cnombre= "SELECT idarchivo,nombre FROM archivos WHERE nombre = '$nombre' 
AND idpersona = '$idpersona' AND idcategoria = '$idcategoria' AND idcarpeta 
= '$idcarpeta'";
if($conn->query($cnombre) === TRUE) {

$sql="UPDATE archivos set nombre='$nombre'


            where idarchivo='$row[idarchivo]'";}else{






// sino existe lo inserto 


            $sql = "INSERT INTO archivos 
(idpersona,idcategoria,idcarpeta,nombre,url,tipo,tama,fechamod,fecha,estado) 

                    VALUES 






    ('$idpersona','$idcategoria','$idcarpeta','$nombre',
    '$url','$type','$tama','$fechamod','$fecha','$estado')";


            if($conn->query($sql) === TRUE) {
                $valid['success'] = true;
                $valid['messages'] = "Successfully Uploaded";
            } 

            else  {

                $valid['success'] = false;
                $valid['messages'] = "Error while uploading";

                  }

            $conn->close();

        }
        else {
            $valid['success'] = false;
            $valid['messages'] = "Error while uploading";

        }
    }
}

echo json_encode($valid);

// upload the file 
}

I'm still loading another record ... Well, if someone can give me a solution I'm grateful for. I hope the question is understood. Greetings to the whole community!

    
asked by Santiago Gonzalez 28.09.2017 в 05:36
source

2 answers

0

You could try this way, the code is commented, I think it is a logical error more than everything.

   <?php
if(in_array($type, array('gif', 'jpg', 'jpeg', 'png', 'php'))) {


    if (!file_exists($carpeta)) {
        mkdir($carpeta, 0777, true);

    }


    if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
        if(move_uploaded_file($_FILES['userImage']['tmp_name'], $url)) {

            // AHORA TENDRIA q verrificar si existe el nombre del archivo en 
 //la TABLA ARCHIVOS y hago un update a la fechamod del mismo/

//declarar variable booleana
            $existe = false;

            $cnombre= "SELECT idarchivo,nombre FROM archivos WHERE nombre = '$nombre' 
            AND idpersona = '$idpersona' AND idcategoria = '$idcategoria' AND idcarpeta 
            = '$idcarpeta'";
//ejecutar query
            $result = $conn->query($cnombre);
//tienes que revisar estar parte porque no conozco la forma en que esta construido, lo que quiero validar es si la consulta tiene 1 es que ya existe, si tiene 0 no existe
            $count=mysqli_num_rows($result);

            if($count > 0) {
                $existe = true;
            }

            if($existe == true){
                while ($row=mysqli_fetch_array($result)){
                    $idArchivo = $row['idarchivo'];
                }

                $sql="UPDATE archivos set nombre='$nombre' where idarchivo='$idarchivo'";
            }

            if($existe == false){
               while ($row=mysqli_fetch_array($result)){
                $idArchivo = $row['idarchivo'];
                $nombre = $row['nombre'];

            }
            $sql = "INSERT INTO archivos 
            (idpersona,idcategoria,idcarpeta,nombre,url,tipo,tama,fechamod,fecha,estado) 

            VALUES 

            ('$idpersona','$idcategoria','$idcarpeta','$nombre',
            '$url','$type','$tama','$fechamod','$fecha','$estado')";
        }
// sino existe lo inserto 




        if($conn->query($sql) === TRUE) {
            $valid['success'] = true;
            $valid['messages'] = "Successfully Uploaded";
        } 

        else  {

            $valid['success'] = false;
            $valid['messages'] = "Error while uploading";

        }

        $conn->close();

    }
    else {
        $valid['success'] = false;
        $valid['messages'] = "Error while uploading";

    }
}
}

echo json_encode($valid);

// upload the file 
}
?>

Test and comment.

    
answered by 28.09.2017 / 06:54
source
0

Good, it is not necessary to check beforehand if you have a primary key as a file, you can use REPLACE INTO , in your case as you use only one column it is more correct to make an insert with insert .. on duplicate key

For your example:

    INSERT INTO t1 (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;
    
answered by 28.09.2017 в 16:01