How to check if it has not already been inserted in PDO?

0

I need to check if it was already registered before entering the database, as you can see, I get an array of software and I need to validate all before inserting. Basically it would include this line $dbh->prepare("select 1 from softwares inner join hardware on hardware.id = softwares.hardware_id where hardware.name = :server and softwares.name = :software limit 1"); but I do not know where, I can not have a machine with 2 same softwares, repeated software.

// POST - incluir
$app->post('/softwares', function(Request $request) use ($app, $dbh) {
$data = json_decode($request->getContent(), true);
//print_r($data);
$erros = array();

if(isset($data['softwares']) and sizeof($data['softwares']) > 0){
    try{
    $sth = $dbh->prepare("INSERT INTO softwares(HARDWARE_ID, PUBLISHER, NAME, VERSION, FOLDER, COMMENTS, FILENAME, FILESIZE, SOURCE, GUID, LANGUAGE, INSTALLDATE, BITSWIDTH, EXCEPT) SELECT id, NULL, :software, :version, :path, :daemon, :binary, NULL, NULL, NULL, NULL, NULL, NULL, TRUE  FROM hardware where hardware.name = :server");

        for($i=0; $i < sizeof($data['softwares']); $i++){
            try{
                    $sth->execute($data['softwares'][$i]);
                    $id = $dbh->lastInsertId();
                    if($id == 0){
                            array_push($erros, $data['softwares'][$i]);
                    }
            }catch(PDOException $e){
                    array_push($erros[$i], $data['softwares'][$i]);
            }
        }

    if(count($erros) > 0){
            $json = array("status" => 202, "code" => 202, "message" => "Accepted", "errors" => array("count" => (int )count($erros), "content" => $erros));
            $response = new Response(json_encode($json), 201);
            $response->headers->set('Location', "/softwares");

    }else{
            $json = array("status" => 201, "code" => 201, "message" => "Created");
            $response = new Response(json_encode($json), 201);
            $response->headers->set('Location', "/softwares");
    }

            return $response;

    }catch(PDOException $e){
        $json = array("status" => 400, "code" => 400, "message" => "invalid json format", "errorMessage" => $e->getMessage());
        $response = new Response(json_encode($json), 201);
        return $response;
    }
}else{
    $response = array("status" => 400, "code" => 400, "message" => "invalid json format");
    return new Response(json_encode($response), 400);}});
    
asked by anonymous 16.12.2016 / 18:28

0 answers