wpdb-> prepare et mysql UPDATE - comment est-ce fait?
-
-
Utilisez simplement lafonction demise àjourinterne de wpdb.Ilgère la désinfectionpour vous.Just use wpdb's internal update function. It handles sanitization for you.
- 0
- 2014-01-10
- Andrew Bartel
-
3 réponses
- votes
-
- 2011-10-19
J'aien quelque sorte corrigé votre requête.Il abesoin d'unetableet d'une condition WHEREpour éviter de changertoutes les lignes.Même un LIMIT 1 à lafin neferapas demal.
$rows_affected = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET removed = %s, post_id = %d, user_id = %d, status = %d;", $cur_date = date('Y-m-d H:i:s'), $postid, $userid, 0 ) // $wpdb->prepare ); // $wpdb->query
Ajoutez simplement le WHERE ... dans la requête MySQL.Unebonne utilisation deprepareest:
$wpdb->prepare($format, $arg1, $arg2, ...); // just like printf()
I sort of fixed your query. It needs a table and a WHERE condition to prevent changing all rows. Even a LIMIT 1 at the end won't hurt.
$rows_affected = $wpdb->query( $wpdb->prepare( "UPDATE {$table} SET removed = %s, post_id = %d, user_id = %d, status = %d;", $cur_date = date('Y-m-d H:i:s'), $postid, $userid, 0 ) // $wpdb->prepare ); // $wpdb->query
Just add the WHERE... in the MySQL query. Proper use of prepare is:
$wpdb->prepare($format, $arg1, $arg2, ...); // just like printf()
-
Enfait,LIMIT 1esttrès dangereux avec lesinstructions UPDATEet DELETE.Celaestparticulièrement vrai si labase de donnéesest unmaître dans la configuration de réplication MySQL cariln'y a aucunegarantie de l'ordre de UPDATE/DELETE sur l'esclave.Les avertissements à ce sujet serontpubliés dans lejournal deserreurs MySQL du Maître.En dehors de cela,votre réponseestessentiellement correcte unefois que @dkmojo ajoute la clause WHERE.+1 !!!Actually, LIMIT 1 is very dangerous with UPDATE and DELETE statements. This is particularly true if the database is a Master in MySQL Replication setup because there is no guarantee the order of UPDATE/DELETE on the Slave. Warnings about this will be posted in the Master's MySQL error log. Other than that, your answer is essentially correct once @dkmojo adds the WHERE clause. +1 !!!
- 0
- 2011-10-19
- RolandoMySQLDBA
-
Si vous ciblez un ID de cléprimaire ou une combinaison de clés unique ...pourquoi serait-ce dangereux?If you target a primary key ID or a unique key combo... why would it be dangerous?
- 0
- 2011-10-19
- EarnestoDev
-
Ce serait la seuleexception.Les clésnon uniques seraient une autre histoire.MySQLpeuttoujourspublier des avertissements dans lejournal deserreurs detoutefaçon.That's would be the only exception. Nonunique keys would be a different story. MySQL may still post warnings in the error log either way.
- 0
- 2011-10-19
- RolandoMySQLDBA
-
J'aien fait écrit un article à ce sujet dans le DBA StackExchange: http://dba.stackexchange.com/questions/1371/problem-with-mysql-subquery/1384#1384.Cela a à voir avec lafaçon dont MySQL Optimizereffectue lestransformations de requêtes sous le capot.I actually wrote a post about that in the DBA StackExchange : http://dba.stackexchange.com/questions/1371/problem-with-mysql-subquery/1384#1384. It has to do with the way MySQL Optimizer performs query transformations under the hood.
- 1
- 2011-10-19
- RolandoMySQLDBA
-
C'est vrai,mais cela devrait être une décision consciente.Si vous savez que vousprévoyez demettre àjour un seulenregistrement,AFAIK,ilestbon d'imposer la LIMITE 1. Si vous avez unnombre variable d'enregistrements àmettre àjour,n'utilisezjamais la LIMITE car letripar défautest ...nontrié :)True but this should be a conscious decision. If you know you plan to update a single record, AFAIK, it's good practice to impose the LIMIT 1. If you have a variable number of records to update, never use the LIMIT as default sorting is... unsorted :)
- 0
- 2011-10-19
- EarnestoDev
-
Il y a des rapports debogues sur le site webmysqlpour 4.0 (fermé: http://bugs.mysql.com/bug.php?id=1024)et 5.1 (patch appliquéil y a un an: http://bugs.mysql.com/bug.php?id=42415) sur l'utilisation de UPDATE/DELETE avec LIMIT.Même avectoutes les corrections debogues autour de LIMIT,la réplication MySQLpour l'esclavepeuttoujours être victime.J'ai appris cela àpartir de l'ordre des lignes SELECTed: http://dba.stackexchange.com/q/6051/877.There are bugs reports in mysql website for 4.0 (closed : http://bugs.mysql.com/bug.php?id=1024) and 5.1 (patch applied a year ago : http://bugs.mysql.com/bug.php?id=42415) about using UPDATE/DELETE with LIMIT. Even with all bugs fixes around LIMIT, MySQL Replication for the Slave can still be victimized. I learned about this from just the order of SELECTed rows : http://dba.stackexchange.com/q/6051/877.
- 0
- 2011-10-19
- RolandoMySQLDBA
-
L'utilisation de LIMITpeut égalementimpliquer destablestemporaires si la requête lejustifie.Toutes lestablestemporairesgénéréespar les requêtes sont,parnature,nontriées comme vous l'avez commentéprécédemment.LIMITfait valser detellestablestemporairesen rendant son ordre d'exécutionet d'accès différent d'unmaître à unesclave.Using LIMIT may also involve temp tables if the query warrants it. All temp tables generated by queries are, by nature, unsorted as you commented on before. LIMIT waltzes through such temp tables making its order of execution and access different from Master to Slave.
- 0
- 2011-10-19
- RolandoMySQLDBA
-
Mercipour les commentaires détaillés!J'ai ajouté la clause WHEREet ajoutémon codemodifié ci-dessus.Maisje ne saispas à quoi sert latable '{}' autour de $ ou sielles sontnécessaires.J'ai d'autres requêtes quin'utilisentpas le '{}' À quoi servent les '{}'?Merciencore!Thanks for the in depth feedback! I added the WHERE clause and added my edited code above. But am unsure of what the '{}' around $table are for or if they are needed. I have other queries that do not use the '{}' What are the '{}' for? Thanx again!
- 0
- 2011-10-20
- dkmojo
-
@dkmojo {$ variable}est labonnefaçon d'utiliser des variables dans des "chaînes"pourmaintenir un contrôletotalet éviter les caractèresindésirables analysés.(Lireici) [http://php.net/manual/en/language.types.string.php].Lire ** Syntaxe simple ** vs ** Syntaxe complexe (bouclée) ** (recherche dans letexte de lapage liée).(parexemple: $table="{$ wpdb->prefix} ds_entry_swoons";)@dkmojo {$variable} is the proper way to use variables in "strings" to maintain full control and avoid unwanted characters parsed. (Read here)[http://php.net/manual/en/language.types.string.php]. Read **Simple Syntax** vs **Complex (curly) syntax** (search in text of linked page). (e.g.: $table = "{$wpdb->prefix}ds_entry_swoons";)
- 0
- 2011-10-20
- EarnestoDev
-
merci coolpour laperspicacitéet le lien.Je les ai déjà vus dans le code dupluginmaisje n'étaispas sûr de leur objectif.Maintenantje sais,et savoirest lamoitié de labataille (GI JOE - devait lefaire) :)cool thanx for the insight and link. I've seen them before in plugin code but was unsure of their purpose. Now I know, and knowing is half the battle (GI JOE - had to do it) :)
- 1
- 2011-10-20
- dkmojo
-
- 2014-01-10
There is dedicated
$wpdb->update()
method that is both convenient helper to performUPDATE
query and performs sanitization, calling$wpdb->prepare()
internally. -
- 2015-07-21
Vouspouvezinsérer autant de variables que vous le souhaitez (%
d
igit,%s
tring ...)global $wpdb; $zz = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->postmeta SET meta_value = '%s' WHERE post_id = '%d' OR WHERE post_id = '%d' ", $value, $id_1, $id_2 ) ); var_dump($zz); exit;
You can insert as many variables as you want (%
d
igit, %s
tring ...)global $wpdb; $zz = $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->postmeta SET meta_value = '%s' WHERE post_id = '%d' OR WHERE post_id = '%d' ", $value, $id_1, $id_2 ) ); var_dump($zz); exit;
Jetente de définir une heure de "suppression" dans une requête deplug-in,maisje ne saispas comment utiliser UPDATE SET avec $ wpdb->prepare.
Voicima requête:
Puis-je configurer UPDATE de cettemanièreen utilisant $ wpdb? Trèsnouveau dans les requêtes DB auto-conçues.
Sinon,comment dois-je/puis-je accomplir cela?
Merci d'avance!
MODIFIER ---------------------------------------------- -----
Nouveau code: