Correct way to add PHP variable in MySQL query?
I am very new to PHP and trying to select data from a MySQL field (in a ta开发者_开发知识库ble). I used the following query.
$token = $wpdb->query("SELECT ami_st_token_aut
FROM $wpdb->users
WHERE ID = '".$current_user->ID."' ");
The value in the ami_st_token_aut is a big number but when i echo $token, it is echoing out $current_user->ID
instead of the big token number. What could be going wrong?
Two ways of doing it.
If you're doing it with WordPress, use the wpdb->prepare
function:
$token = $wpdb->get_var(
$wpdb->prepare(
"SELECT ami_st_token_aut FROM $wpdb->users WHERE ID=%d", $current_user->ID
)
);
If you're doing it without Wordpress, use the mysql_real_escape_string
function.
mysql_query(
"SELECT ami_st_token_aut FROM tablename WHERE ID='"
. mysql_real_escape_string($ID) . "'"
);
See the Wordpress Codex.
The $wpdb->query
function returns the number of rows that matched your query (if you do a SELECT, anyway).
$wpdb->get_var
is the function to use to get a single value from the database.
精彩评论