Comment récupérer des données dans WordPress en utilisant MySQLi ou $ wpdb
3 réponses
- votes
-
- 2016-07-25
Pour récupérer les données de latable debase de données
<?php $results = $wpdb->get_results( "SELECT * FROM $table_name"); // Query to fetch data from database table and storing in $results if(!empty($results)) // Checking if $results have some values or not { echo "<table width='100%' border='0'>"; // Adding <table> and <tbody> tag outside foreach loop so that it wont create again and again echo "<tbody>"; foreach($results as $row){ $userip = $row->user_ip; //putting the user_ip field value in variable to use it later in update query echo "<tr>"; // Adding rows of table inside foreach loop echo "<th>ID</th>" . "<td>" . $row->id . "</td>"; echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; echo "<tr>"; echo "<th>User IP</th>" . "<td>" . $row->user_ip . "</td>"; //fetching data from user_ip field echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; echo "<tr>"; echo "<th>Post ID</th>" . "<td>" . $row->post_id . "</td>"; echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; echo "<tr>"; echo "<th>Time</th>" . "<td>" . $row->time . "</td>"; echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; } echo "</tbody>"; echo "</table>"; } ?>
NOTE: Change your data fetching format according to your need (table structure)
Pourmettre àjour le champ d'heure sur la conditionif
<?php if($userip==245.356.134.22){ //Checking if user_ip field have following value $wpdb->update( $table_name, array( 'time' => 'YOUR NEW TIME' // Entring the new value for time field ), array('%d') // Specify the datatype of time field ); } ?>
<❯Mise àjour
Si vous voulez vérifier si l'adresse IP que vous allezinsérer dans labase de donnéesexiste déjà ounon,vérifiez-la comme ceci
<?php global $wpdb,$ip; $results = $wpdb->get_results( "SELECT user_ip FROM $table_name"); //query to fetch record only from user_ip field $new_ip = 245.356.134.22; //New Ip address storing in variable if(!empty($results)) { foreach($results as $row){ $old_ip = $row->user_ip; // putting the value of user_ip field in variable if($new_ip==$old_ip){ // comparing new ip address with old ip addresses $ip = 'Already Exist'; // if ip already exist in database then assigning some string to variable } } } if($ip = 'Already Exist'){ // Checking if variable have some string (It has some string only when if IP already exist in database as checked in if condition by comparing old ips with new ip) //Insert query according to Ip already exist in database }else{ //Insert query according to Ip doesn't exist in database } ?>
To fetch data from database table
<?php $results = $wpdb->get_results( "SELECT * FROM $table_name"); // Query to fetch data from database table and storing in $results if(!empty($results)) // Checking if $results have some values or not { echo "<table width='100%' border='0'>"; // Adding <table> and <tbody> tag outside foreach loop so that it wont create again and again echo "<tbody>"; foreach($results as $row){ $userip = $row->user_ip; //putting the user_ip field value in variable to use it later in update query echo "<tr>"; // Adding rows of table inside foreach loop echo "<th>ID</th>" . "<td>" . $row->id . "</td>"; echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; echo "<tr>"; echo "<th>User IP</th>" . "<td>" . $row->user_ip . "</td>"; //fetching data from user_ip field echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; echo "<tr>"; echo "<th>Post ID</th>" . "<td>" . $row->post_id . "</td>"; echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; echo "<tr>"; echo "<th>Time</th>" . "<td>" . $row->time . "</td>"; echo "</tr>"; echo "<td colspan='2'><hr size='1'></td>"; } echo "</tbody>"; echo "</table>"; } ?>
NOTE: Change your data fetching format according to your need (table structure)
To update time field on if condition
<?php if($userip==245.356.134.22){ //Checking if user_ip field have following value $wpdb->update( $table_name, array( 'time' => 'YOUR NEW TIME' // Entring the new value for time field ), array('%d') // Specify the datatype of time field ); } ?>
Update
If you want to check if the IP you are going to insert in database is already exist or not then check it like this
<?php global $wpdb,$ip; $results = $wpdb->get_results( "SELECT user_ip FROM $table_name"); //query to fetch record only from user_ip field $new_ip = 245.356.134.22; //New Ip address storing in variable if(!empty($results)) { foreach($results as $row){ $old_ip = $row->user_ip; // putting the value of user_ip field in variable if($new_ip==$old_ip){ // comparing new ip address with old ip addresses $ip = 'Already Exist'; // if ip already exist in database then assigning some string to variable } } } if($ip = 'Already Exist'){ // Checking if variable have some string (It has some string only when if IP already exist in database as checked in if condition by comparing old ips with new ip) //Insert query according to Ip already exist in database }else{ //Insert query according to Ip doesn't exist in database } ?>
-
C'est super ...pouvez-vousme dire commentje peux vérifier si l'adresse `ip`est déjà dans labase de données ounon?Si l'adresse IPest déjà dans labase de données,exécutez leprogramme 1et si cen'estpas le cas,exécutez leprogramme 2. Je sais quenous devons utiliser `WHERE` dans la requête,maisje ne saispas comment l'utiliserThat's great... can you tell me how I can check if the `ip` address is already in database or not? If Ip address already in database then run program 1 and if it's not, then run program 2. I know we need to use `WHERE` in query but I dont know hot to use it
- 0
- 2016-07-25
- Ramesh Pardhi
-
Avez-vous vu la réponsemise àjour?Have you seen the updated answer?
- 0
- 2016-07-26
- Rishabh
-
J'aiessayé ceciet celafonctionne.Maispour lemoment,il récupèretoutes les données de labase de donnéesen utilisant `foreach`,puisil compilenotre codepour vérifier si l'adresse IPest lamême ounon.Existe-t-il un autremoyen de vérifier cette adresse IP directement à l'aide d'une requête debase de données?I tried this and its working. But right now its fetching all the data from database using `foreach`, then its compiling our code to check if the ip is same or not. Is there any other way to get that ip get checked directly using database query?
- 0
- 2016-07-26
- Ramesh Pardhi
-
La réponse a étémise àjour!Vérifiez si c'est ce dont vous avezbesoin.Answer has been updated! Check if its what you need.
- 0
- 2016-07-27
- Rishabh
-
Rishabh Merci dem'aider ... Juste une dernière question.Puis-je utiliser une requête comme `SELECT user_ip FROM $table_name WHERE` user_ip`=$ username`.Est-ce que çamarchera?Mercipour votre réponseet aidez Rishabh.Rishabh Thank you to help me... Just one last question. Can I use query like `SELECT user_ip FROM $table_name WHERE `user_ip` = $username`. Will it work? Thank you for your answer and help Rishabh.
- 0
- 2016-07-27
- Ramesh Pardhi
-
Oui,vouspouvez l'utiliser comme ceci` $ results=$ wpdb->get_results ("SELECT user_ip FROM $table_name WHERE user_ip='$ username'"); `Yes you can use it like this` $results = $wpdb->get_results( "SELECT user_ip FROM $table_name WHERE user_ip = '$username' ");`
- 1
- 2016-07-27
- Rishabh
-
- 2016-07-27
//For fetching data use global $wpdb; $results = $wpdb->get_results("SLECT * FROM table_name"); //and for update use below code $wpdb->update( $table_name, array( 'time' => time(), // string ), array( 'user_ip' => '245.356.134.22' ), array('%s'), array( '%d' ) );
//For fetching data use global $wpdb; $results = $wpdb->get_results("SLECT * FROM table_name"); //and for update use below code $wpdb->update( $table_name, array( 'time' => time(), // string ), array( 'user_ip' => '245.356.134.22' ), array('%s'), array( '%d' ) );
-
Veuillez ajouter quelques commentaires devant vos lignes de code afin que le spectateurpuisse comprendre ce que vous codezet comment.Please add some comments in front of you code lines so that viewer can understand what you code does and how.
- 0
- 2016-07-27
- Rishabh
-
@Rishabhpasbesoin deplus de commentaire carj'aiinséré un commentaire approprié avant le code.@Rishabh no need for more comment as i have inserted appropriate comment before the code.
- 0
- 2016-07-27
- Ganesh
-
- 2016-07-25
Vousindiquez MYSQLi dans votre question,mais étiquetezet faites référence à MySQL dans votre question. Si vous utilisez MySQL,ce qui suitfonctionnerapour vous:
C'est assez simple,et étant donné que vous avez déjà construit l'instructioninsert,vouspouvez simplement utiliser update comme ceci:
$wpdb->update($table_name , array('user_ip' => $user_ip, 'post_id' =>$postID, 'time' => $visittime),array('%s','%d', '%d') );
Ensuite,tout ce que vous avez àfaireest de définir les valeurs de votre requêteen fonction des données de labase de données que vous souhaitezmodifier. Vouspouveztrouver desexemplesici: https://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows
Pour récupérertoutes les données,vouspouvez utiliser ce qui suit:
$results = $wpdb->get_results("SLECT * FROM table_name");
Vouspouvez y ajoutern'importe quelparamètre WHERE ou letrier comme uneinstruction de requête SQL standard. Vouspouvez simplementfaire uneboucle avec uneboucleforeachet ensuite vousne feriez quefaire écho aux données que vous avez récupérées.
You indicate MYSQLi in your question, but label and refer to MySQL in your question. If you are using MySQL the following will work for you:
This is fairly simple, and given the fact that you already have the insert statement constructed, you can just use update like so:
$wpdb->update($table_name , array('user_ip' => $user_ip, 'post_id' =>$postID, 'time' => $visittime),array('%s','%d', '%d') );
Then all you would have to do is set the values in your query as to what data in the DB you want to change. You can find examples here: https://codex.wordpress.org/Class_Reference/wpdb#UPDATE_rows
As for fetching all of the data you could use the follow:
$results = $wpdb->get_results("SLECT * FROM table_name");
You can add any WHERE parameters to it or sort it just like and standard SQL query statement. You can just then loop through is with a foreach loop and then you would just echo out your data you retrieved.
-
Mercipour la réponse @hosker.Maisje voulais savoir chaudpour récupérer ces `$ results`Thank you for reply @hosker. But I was wanted to know hot to fetch that `$results`
- 0
- 2016-07-25
- Ramesh Pardhi
-
Je suisprêt à aider,contrairement à @rishabh,qui a été assezgentilpour vous donner une réponse complète avec le codage,je vousexpliquais simplement commentfaire ce que vous demandiez.Une simple recherche sur Googleet un coup d'œil dans le Codex Wordpress auraientpu résoudre votreproblème.Cesforums sontici comme une ressource,et je les utilise,maisje nem'attendraisjamais à ce que quelqu'un le codepourmoi.Vousen aviez déjà lamoitié,mais vous étieztropparesseuxpour le comprendreet écrire le code vous-même.Vousn'apprenezjamais si quelqu'unfaittoutpour vous.I am willing to help, unlike @rishabh, who was nice enough to give you a complete answer with coding, I was just giving you the basics of how to do what you were asking for. A simple google search and a look through the Wordpress Codex could have solved your problem. These forums are here as a resource, and I use them, but I would never expect someone to code it for me. You had half of it already set, but were too lazy to figure it out and write the code yourself. You never learn if someone does it all for you.
- 1
- 2016-07-25
- hosker
-
@ hoskertu as raisonmonpote!L'auto-apprentissageestindispensable ... Maintenant,je me rends compte queje n'auraispas dû donner la réponse complète.@ hosker you are right buddy! Self study is must... Now I realize I shouldn't have given the complete answer.
- 0
- 2016-07-26
- Rishabh
-
Hmm!vous avez raison lesgars.ce quej'ai demandéiciestpourma référence.Ce quej'essaie defaire,c'est quelque chose de différent.Je veux savoir certaines chosespour l'utiliser avecmonplugin.Ce queje veux savoir,c'est comment utiliser ces requêtespour afficher l'adresse IP queje veux sans récupérertoutes les données de labase de données.Je veux une requête qui vérifie l'adresse IP queje veuxet l'afficheensuite.Et sij'ai 30000 adresses IP?Il récupéreratoutes les 30000 adresses IPen utilisant `foreach`.Cen'estpasjuste!C'estpourquoij'aibesoin de votre aide.Hmm! you are right guys. what I asked here is for my reference. What I am trying to do is something different. I want to know some things to use it with my plugin. What I want to know is how to use these queries to show the IP I want without fetching all the data from database. I want a query which checks for the IP I want and then displays it. What if I have 30000 IPs? It will fetch all the 30000 IPs using `foreach`. That's not right! Thats why I need your help.
- 0
- 2016-07-26
- Ramesh Pardhi
J'ai untableaupersonnalisé comme celui-ci:
J'insère des données dans letableauen utilisant
J'aiinséré quatre lignesen utilisant ce code:
Je souhaite apprendre à utiliser les requêtes MySQL dans WordPress. Voici doncmes questions:
time
oùuser_ip = 245.356.134.22
Veuillezme faire savoir s'il y a quelque chose queje dois apprendre.
Merci