2013-03-08 10 views
6

Sto creando un modulo a più fasi per i miei utenti. Saranno autorizzati ad aggiornare uno o tutti i campi. Quindi, ho bisogno di inviare i valori, controllare se sono impostati e in tal caso, eseguire un UPDATE. Ecco quello che ho finora:AGGIORNA un array usando PDO

public function updateUser($firstName, $lastName, $streetAddress, $city, $state, $zip, $emailAddress, $industry, $password, $public = 1, 
    $phone1, $phone2, $website,){ 

    $updates = array(
     'firstName'    => $firstName, 
     'lastName'    => $lastName, 
     'streetAddress'   => $streetAddress, 
     'city'     => $city, 
     'state'     => $state, 
     'zip'     => $zip, 
     'emailAddress'   => $emailAddress, 
     'industry'    => $industry, 
     'password'    => $password, 
     'public'    => $public, 
     'phone1'    => $phone1, 
     'phone2'    => $phone2, 
     'website'    => $website, 

); 

Ecco il mio DOP (o meglio, il tentativo di iniziare)

$sth = $this->dbh->prepare("UPDATE user SET firstName = "); //<---Stuck here 
    $sth->execute(); 
    $result = $sth->fetchAll(PDO::FETCH_ASSOC); 
    return $result; 

In sostanza, come posso creare l'istruzione UPDATE quindi aggiorna solo le voci del array che non sono NULL?

ho pensato sull'esecuzione di un ciclo foreach come questo:

foreach($updates as $key => $value) { 
     if($value == NULL) { 
      unset($updates[$key]); 
     } 
    } 

ma come faccio a scrivere la dichiarazione prepare se io sono sicuro di valori?

Se sto sbagliando completamente, per favore indicami la giusta direzione. Grazie.

+3

È possibile utilizzare 'SET firstName = IFNULL (?, firstName)', vedere http://stackoverflow.com/question s/2675968/sql-how-can-i-update-a-value-on-a-solo-column-if-that-value-is-null – mario

+0

@mario Grazie, buona idea! – hek2mgl

+0

@mario Grazie per il suggerimento! Non sono sicuro che questo possa aiutare il mio caso, se 'IFNULL (NULL, 10);' restituisce '10', dovrei comunque conoscere il valore di' 10', corretto? Sto semplicemente cercando di fermare l'aggiornamento di "UPDATE" se il valore di un oggetto è 'NULL' –

risposta

4

Prima di tutto, utilizzare array_filter per rimuovere tutti i valori NULL:

$updates = array_filter($updates, function ($value) { 
    return null !== $value; 
}); 

In secondo luogo, i parametri legano, che rende il vostro molto vivo più facile:

$query = 'UPDATE table SET'; 
$values = array(); 

foreach ($updates as $name => $value) { 
    $query .= ' '.$name.' = :'.$name.','; // the :$name part is the placeholder, e.g. :zip 
    $values[':'.$name] = $value; // save the placeholder 
} 

$query = substr($query, 0, -1).';'; // remove last , and add a ; 

$sth = $this->dbh->prepare($query); 

$sth->execute($values); // bind placeholder array to the query and execute everything 

// ... do something nice :) 
+0

Grazie, penso che potrebbe fare il trucco. Ci giocherò e vedrò. –

+1

Ha funzionato alla grande, grazie! Ho appena modificato '$ updates = array_filter ($ updates, function ($ value) { return null! == $ value; });' a '$ updates = array_filter ($ updates, 'strlen');' basato sul commento qui: http://www.php.net/manual/en/function.array-filter.php#111091 –

+1

@relentless ok, bene! E sai anche cosa sta succedendo? Penso che sia più importante che se il codice funzioni o meno. –

1

Il sotto può essere ottimizzata:

$i = 0; $query = array(); 
foreach($updates as $key => $value) { 
    if ($value != NULL) { 
     $query[] = "{$key} = :param_{$i}"; 
     $i++; 
    } 
} 

if (! empty($query)) { 
    $finalQuery = implode(",", $query); 
    $sth = $this->dbh->prepare('UPDATE user SET ' . $finalQuery); 

    $i = 0; 
    foreach($updates as $key => $value) { 
    if ($value != NULL) { 
     $sth->bindParam(':param_'.$i, $value, PDO::PARAM_STR); 
     $i++; 
    } 
    } 
} 
+0

Grazie per la risposta –