$wpdb->update per aggiornare più righe, come IN nel SQL normale

1 ago 2014, 17:08:52
Visualizzazioni: 15.3K
Voti: 7

Mi chiedevo se fosse possibile utilizzare $wpdb->update per aggiornare i valori di più righe come con IN nel SQL "normale".

Vorrei ottenere qualcosa come questo esempio;

UPDATE [table]
SET [column_1] = [updated_value]
WHERE [column_2] IN ([comma_separated_ids])

Ho cercato in giro come fare questo, ma non ho ancora trovato un'altra domanda che lo chieda o qualsiasi tipo di risposta/post che spieghi se può essere fatto o meno.

Per ora sto usando una query invece, ma sarebbe più bello con una semplice riga di codice.

3
Commenti

Non c'è motivo per cui non funzioni.

Mark Kaplun Mark Kaplun
1 ago 2014 17:18:14

Ma COME? Ho provato ad aggiungere una stringa separata da virgole come valore nell'array where, ma ha aggiornato solo il primo id.

Ludvig Sjöbeck Ludvig Sjöbeck
1 ago 2014 17:54:53

hmm, vedo che persone più esperte di me hanno già risposto ;)

Mark Kaplun Mark Kaplun
1 ago 2014 18:41:20
Tutte le risposte alla domanda 1
5
12

Come puoi vedere nel codice sorgente il segno = è hardcoded nel metodo wpdb::update(), quindi, di default, non è possibile utilizzare IN per il metodo update.

Il modo più semplice per aggirare il problema è utilizzare wpdb::query() con la tua query SQL, assicurandoti di effettuare l'escape corretto di tutti i valori

Esempio:

function wpdb_update_in( $table, $data, $where, $format = NULL, $where_format = NULL ) {

    global $wpdb;

    $table = esc_sql( $table );

    if( ! is_string( $table ) || ! isset( $wpdb->$table ) ) {
        return FALSE;
    }

    $i          = 0;
    $q          = "UPDATE " . $wpdb->$table . " SET ";
    $format     = array_values( (array) $format );
    $escaped    = array();

    foreach( (array) $data as $key => $value ) {
        $f         = isset( $format[$i] ) && in_array( $format[$i], array( '%s', '%d' ), TRUE ) ? $format[$i] : '%s';
        $escaped[] = esc_sql( $key ) . " = " . $wpdb->prepare( $f, $value );
        $i++;
    }

    $q         .= implode( $escaped, ', ' );
    $where      = (array) $where;
    $where_keys = array_keys( $where );
    $where_val  = (array) array_shift( $where );
    $q         .= " WHERE " . esc_sql( array_shift( $where_keys ) ) . ' IN (';

    if( ! in_array( $where_format, array('%s', '%d'), TRUE ) {
        $where_format = '%s';
    }

    $escaped = array();

    foreach( $where_val as $val ) {
        $escaped[] = $wpdb->prepare( $where_format, $val );
    }

    $q .= implode( $escaped, ', ' ) . ')';

    return $wpdb->query( $q );
}

Poi usala in questo modo:

wpdb_update_in(
  'posts', // tabella
  array( 'post_author' => '1', 'post_status' => 'draft' ), // dati
  array( 'post_author' => array( '2', '3', '4', '5' ) ), // where
  array( '%d', '%s' ), // formato
  '%d' // formato where
);

La SQL eseguita sarà

UPDATE wp_posts
SET post_author = 1, post_status = 'draft'
WHERE post_author IN (2, 3, 4, 5)
1 ago 2014 18:29:41
Commenti

Non ho lavorato molto con WP, quindi non ero a conoscenza del codice sorgente. Mi assicurerò di aggiungerlo ai preferiti per riferimenti futuri. Mi piace la tua soluzione e la segnerò come risposta.

Ludvig Sjöbeck Ludvig Sjöbeck
4 ago 2014 10:13:36

Wordpress hardcoded e difficile da usare...

Vishal Kumar Sahu Vishal Kumar Sahu
11 set 2017 01:00:12

L'ho trovato utile, ma sembra che alcune cose siano cambiate da quando è stata data questa risposta. Innanzitutto, la firma di implode() ha invertito l'ordine dei parametri da PHP 7.4. Inoltre, non sono riuscito a capire cosa fosse $wpdb->$table? Alla fine l'ho rimosso.

JDandChips JDandChips
16 giu 2021 17:21:28

c'è anche il formato %f da autorizzare

ZalemCitizen ZalemCitizen
21 apr 2024 00:55:24

Le cose sono cambiate in 10 anni, sì :)

$wpdb->$table è il modo per ottenere il nome completo della tabella. Non dovresti usare, ad esempio, "wp_content" ma $wpdb->content, perché il prefisso potrebbe cambiare, e in multisite cambierà sicuramente.

Questo non è cambiato. Ma oggi abbiamo il segnaposto %i per evitare i nomi delle tabelle.

Per quanto riguarda %f, sì è stato aggiunto relativamente recentemente insieme a %i menzionato sopra.

gmazzap gmazzap
2 mag 2024 21:03:10