显示插入的表单时出现问题

时间:2014-12-29 作者:Ehsan

我构建了一个表单,并使用$wpdb.

当我点击提交按钮时,页面会重新加载,一行被添加到数据库中,但网站上没有显示任何内容。

我的插入代码是:

function insert_form() {

    global $wpdb;
    $table_name = $wpdb->prefix . "food_resarved";
    $alibaba = $wpdb->insert( 
        $table_name, 
        array(
            \'id\' => \'\',
            \'user_id\' => wp_get_current_user()->ID,
            \'name\' => wp_get_current_user()->user_firstname,
            \'lastname\' => wp_get_current_user()->user_lastname,
            \'post_title\' => $_POST[\'post_title\'],
            \'food_selected\' => $_POST[\'food\'],
            \'guest_number\' => $_POST[\'guest_food\'],
            \'email\' => wp_get_current_user()->user_email 
        ), 
        array( \'%d\', \'%s\', \'%s\' , \'%s\' , \'%s\' , \'%s\' , \'%s\', \'%s\' ) 
    );

    if ( !$alibaba ) {
        $mylink = $wpdb->get_results( "select * from wp_food_resarved where user_id like \'".$curent_user."\' AND post_title like \'".$abcde."\' ");
        foreach ($mylink as $posta){
            echo \'<div class="ordered-food">\';
            echo \' شما \';
            echo $posta->food_selected;
            echo \' سفارش داده‌اید \';
            echo \'</div>\';
        }
    } 
    else {
        echo "Die";
    }
}

1 个回复
最合适的回答,由SO网友:CodeMascot 整理而成

在您的代码中,我遇到了两个问题。

第一个问题是您尚未定义$current_user$abcde 变量用于使用全局$current_user 您需要在函数顶部将其定义为global $current_user. 否则它将无法获得$current_user 变量而且还可以获取您需要使用的当前用户ID$current_user->ID 声明全局变量后。对于$abcde 变量请先在该变量中声明或存储值if (!$alibaba) 这实际上意味着如果$alibaba 变量为false。显然,如果DB条目成功$alibaba 将返回true。因此不会执行循环现在,您的整个代码如下所示-

function insert_form() {

    global $wpdb, $current_user;
    $table_name = $wpdb->prefix . "food_resarved";
    $abcde = \'\'; // Later some where put a value in it. Otherwise it will not work.
    $alibaba = $wpdb->insert(
        $table_name,
        array(
            \'id\' => \'\',
            \'user_id\' => wp_get_current_user()->ID,
            \'name\' => wp_get_current_user()->user_firstname,
            \'lastname\' => wp_get_current_user()->user_lastname,
            \'post_title\' => $_POST[\'post_title\'],
            \'food_selected\' => $_POST[\'food\'],
            \'guest_number\' => $_POST[\'guest_food\'],
            \'email\' => wp_get_current_user()->user_email
        ),
        array( \'%d\', \'%s\', \'%s\' , \'%s\' , \'%s\' , \'%s\' , \'%s\', \'%s\' )
    );

    if ( $alibaba ) {
        $mylink = $wpdb->get_results( "select * from wp_food_resarved where user_id like \'".$current_user->ID."\' AND post_title like \'".$abcde."\' ");
        foreach ($mylink as $posta){
            echo \'<div class="ordered-food">\';
            echo \' شما \';
            echo $posta->food_selected;
            echo \' سفارش داده‌اید \';
            echo \'</div>\';
        }
    }
    else {
        echo "Die";
    }
}
希望这对你有帮助。

结束