php - Best way to receive variables from database -
i have custom wordpress table following contents:
account_info id | account_id | wp_title | wp_url 1 | 12345 | website | website.com
what best (or fastest) way results?
option 1:
global $wpdb; $sql = "select id, wp_title. wp_name account_info"; $results = $wpdb->get_results($sql); if(!empty($results)) { foreach($results $r) { $id = $r->id; $wp_title = $r->wp_title; $wp_name = $r->wp_name; } }
option 2:
$id = $wpdb->get_var("select id account_info"); $wp_title = $wpdb->get_var("select wp_title account_info"); $wp_name = $wpdb->get_var("select wp_name account_info");
when talking "best" , "fastest" - these aren't things need take consideration. readibility key future developers looking @ code.
option 1 shows that, if result set isn't empty, loop around them , set variables. option 2 framework specific, , isn't best approach.
so before micro-optimising, make sure readability @ it's utmost - never sacrifice 1 other.
speed-wise, make sure you're indexing database properly. you're using fastest loops available php. also, option 2 making multiple database queries. try , combine multiple queries 1 - don't need make load of calls db don't need.
you want avoid using global
keyword. it's bad practice , makes code untestable. access $wpdb
variable way, either passing function or including file elsewhere. see why global variables bad , search little on google.
Comments
Post a Comment