douhuiyan2772 2014-04-22 09:32
浏览 42
已采纳

从数据库接收变量的最佳方法

I have a custom Wordpress table with the following contents:

account_info
id   | account_id | wp_title | wp_url
1    | 12345      | website  | website.com

What is the best (or fastest) way to get the results?

Option 1:

global $wpdb;   

$sql = "SELECT id, wp_title. wp_name FROM account_info";
$results = $wpdb->get_results($sql);

if(!empty($results)) { 
    foreach($results as $r) {   
         $id = $r->id;
         $wp_title = $r->wp_title;
         $wp_name = $r->wp_name;

    }
} 

Option 2:

$id = $wpdb->get_var("SELECT id FROM account_info");
$wp_title = $wpdb->get_var("SELECT wp_title FROM account_info");
$wp_name = $wpdb->get_var("SELECT wp_name FROM account_info");
  • 写回答

3条回答 默认 最新

  • duangu1645 2014-04-22 09:38
    关注

    When you are talking about "best" and "fastest" - these aren't the only things you need to take into consideration. Readibility is also key for future developers looking at your code.

    Option one clearly shows that, if the result set isn't empty, you loop around them and set some variables. Option two is framework specific, and this isn't always the best approach.

    So before micro-optimising, make sure readability is at it's utmost - never sacrifice one for the other.

    Speed-wise, just make sure you're indexing your database properly. You're using the fastest loops available to PHP. Also, option two is making multiple database queries. Always try and combine multiple queries into one - you don't need to make a load of extra calls to the db that you don't actually need.

    You want to avoid using the global keyword. It's bad practice and makes your code untestable. Get access to the $wpdb variable another way, either by passing it into a function or including a file elsewhere. See why global variables are bad and search a little on google.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大
  • ¥15 单片机无法进入HAL_TIM_PWM_PulseFinishedCallback回调函数