快捷码选择另一个数据库

时间:2020-01-15 作者:Cristofer

我需要连接同一主机中的另一个数据库并返回产品值(Woocomece)。返回值为空


add_shortcode(\'product_project_test\', \'product_project_test\');
function product_project_test() {   
    $mydbTest = new wpdb(\'user\',\'password\',\'dbname\',\'localhost\');

    $result= $mydbTest->get_results("SELECT `meta_value` FROM `wp_postmeta` WHERE \'post_id\' = 5338 AND \'meta_key\' = \'_sale_price\'");
    $price = $result[0];
    $price = number_format($price, 2, \'.\', \',\');

    return \'$ \'.$price;

}

SQL Consult

SELECT `meta_value` FROM `wp_postmeta` WHERE `POST_ID` = 5338 AND `meta_key` = \'_sale_price\'
Returnenter image description here

Update - my Solution works


add_shortcode(\'product_project_test\', \'product_project_test\');
function product_project_test() {   
    $mydbTest = new wpdb($userdb,$mypass,$mydb,\'localhost\');
    $query = "SELECT * FROM wp_postmeta WHERE post_id=608 AND meta_key IN(\'_sale_price\', \'_regular_price\')";

    $results = $mydbTest->get_results($query, ARRAY_A);
        foreach($results as $result){
        if($result[\'meta_key\'] == \'_sale_price\'){
            $price= $result[\'meta_value\'];
            $price= number_format($price, 2, \'.\', \',\');
        } else if($result[\'meta_key\'] == \'_sale_price\'){
            $old_price= $result[\'meta_value\'];
            $old_price= number_format($old_price, 2, \'.\', \',\');
        }
    };

    return \'$ \'.$price;

}

1 个回复
SO网友:TomC

您的代码在我看来是正确的,因此我怀疑连接到第二个数据库时存在某种问题。尝试以下操作将记录最后一个错误:

$wpdb->show_errors(); 
if($wpdb->last_error !== \'\') :
    $wpdb->print_error()
endif;
如果您使用的是multisite,则还需要添加:

define( \'DIEONDBERROR\', true );
查看此处了解更多信息:https://codex.wordpress.org/Class_Reference/wpdb#Show_and_Hide_SQL_Errors