strava1 strava1 - 4 days ago 5
MySQL Question

Check to see if any of inputs has value

Check to see if any of inputs has value? If input has the value null/empty don't update them to DB?

Here is my code and when I have empty input I lost previusly data in DB.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$mysql_host = "localhost";
$mysql_username = "root";
$mysql_password = "";
$mysql_database = "medvedgrad";

// First we create the connection
$pdo = new PDO("mysql:host=".$mysql_host .";dbname=".$mysql_database .";charset=utf8", $mysql_username, $mysql_password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$data = json_decode(file_get_contents("php://input"));
$zm = $data->zlatni_medvjed;
$ck = $data->crna_kraljica;
$gv = $data->gricka_vjestica;
$dk = $data->dva_klasa;
$fk = $data->fakin;



// Then we prepare, and execute the query
$stmt = $pdo->prepare("UPDATE `stanje_piva`
SET
`zlatni_medvjed`=`zlatni_medvjed`+:zm, `crna_kraljica`=`crna_kraljica`+:ck, `gricka_vjestica`=`gricka_vjestica`+:gv, `dva_klasa`=`dva_klasa`+:dk,`fakin`=`fakin`+:fk WHERE `id`=1");

$stmt->execute(array("zm" => $zm, "ck" => $ck, "gv" => $gv, "dk" => $dk, "fk" => $fk));

?>

Answer
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$mysql_host = "localhost";
$mysql_username = "root";
$mysql_password = "";
$mysql_database = "medvedgrad";

// First we create the connection
$pdo = new PDO("mysql:host=".$mysql_host .";dbname=".$mysql_database .";charset=utf8", $mysql_username, $mysql_password);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);  

$data = json_decode(file_get_contents("php://input"));

$zm = $data->zlatni_medvjed;
$ck = $data->crna_kraljica;
$gv = $data->gricka_vjestica;
$dk = $data->dva_klasa;
$fk = $data->fakin;

//Let's do like Jack the ripper, lets divide  into parts :p

$updateparts = array();

$zm = trim($zm);
if($zm != "")
{
    $zmpart = "`zlatni_medvjed`=`zlatni_medvjed`+:zm";
    $updateparts[] = $zmpart;
}

$ck = trim($ck);
if($ck != "")
{ 
    $ckpart = "`crna_kraljica`=`crna_kraljica`+:ck";
    $updateparts[] = $ckpart;
}

$gv = trim($gv);
if($gv != "") 
{
    $gvpart = "`gricka_vjestica`=`gricka_vjestica`+:gv";
    $updateparts[] = $gvpart;
}

$dk = trim($dk);
if($dk != "") 
{
    $dkpart = "`dva_klasa`=`dva_klasa`+:dk";
    $updateparts[] = $dkpart;
}

$fk = trim($fk);
if($fk != "") 
{
    $fkpart = "`fakin`=`fakin`+:fk";
    $updateparts[] = $fkpart;
}

$updatepartstring = implode(",",$updateparts);

$update_query="UPDATE `stanje_piva`
 SET 
$updatepartstring 
WHERE `id`=1";



// Then we prepare, and execute the query
$stmt = $pdo->prepare($update_query);

 $stmt->execute(array("zm" => $zm, "ck" => $ck, "gv" => $gv, "dk" => $dk, "fk" => $fk));

?>
Comments