首页 > 解决方案 > Wordpress:从特定用户的数据库 $wpdb 中获取数据

问题描述

你好我今天正在做一个项目。我想在每次登录时在前端打印特定用户的数据。当他们登录时,将获取他们的用户 ID,并仅从该特定用户那里获取数据。

我有这个数据库。我想要 vendor_id 3 当此供应商登录将仅显示特定供应商的值时,如果没有值将返回“此用户无佣金数据”

现在这是我的 wordpress wpdb 代码

<table border="1">
        <tr>
        <th>Vendor ID</th>
        <th>Total Due</th>
        <th>Time</th>
        </tr>
        <?php
        global $wpdb;
        $result = $wpdb->get_results ( "SELECT * FROM wp_pv_commission" );
        $vendor = get_current_user_id();
        foreach ( $result as $userdata) {
        ?>
        <tr>
        <td><?php echo $userdata->vendor_id;?></td>
        <td><?php echo $userdata->total_due;?></td>
        <td><?php echo $userdata->time;?></td>
        </tr>
        <?php
        }
        ?>
        </table>

并返回 this 的数据。但我想要的只是像现在这样的用户,我以供应商 ID 3 登录。它显示了所有内容。我需要使用的正确的 wordpress php 调节代码是什么

谢谢您的回答。

标签: phpmysqlwordpress

解决方案


您的代码是正确的,但您从数据库中选择数据的条件是错误的

当您不应用 where 子句时,MYSQL 将始终返回所有记录。因此,您需要在查询中提供 where 子句

<table border="1">
    <tr>
        <th>Vendor ID</th>
        <th>Total Due</th>
        <th>Time</th>
    </tr>
    <?php
    global $wpdb;
    $vendor = get_current_user_id();
    $result = $wpdb->get_results ( "SELECT * FROM wp_pv_commission where vendor_id=".$vendor );
    foreach ( $result as $userdata) {
    ?>
        <tr>
            <td><?php echo $userdata->vendor_id;?></td>
            <td><?php echo $userdata->total_due;?></td>
            <td><?php echo $userdata->time;?></td>
        </tr>
    <?php
    }
    ?>
</table>

如何在 MySQL 中使用 where 子句


推荐阅读