I met some trouble. I tried to get user display_name in a custom mysql query foreach, but it failed. I have tried three method. new WP_User
, get_user_by
and get_userdata
. but they only can get back the result $user->display_name
which is ID=1 in table wp_users
(admin). failed get any $user->display_name
which ID=2(3,4…) in table wp_users
. What should I do to solve this question? many thanks.
$results = mysql_query("SELECT * FROM custom_table");// query connect from a custom database, not in database wp.
while($row = mysql_fetch_array($results)) {
global $wpdb;
$user = new WP_User($row['user_id']);
//$user = get_user_by('id',$row['user_id']);
//$user = get_userdata($row['user_id']);
var_dump($user);
}
edit
Here is my full code. same code, If SELECT * FROM test_table where id = 1
I could get the user display name admin
, but if I try SELECT * FROM test_table where id = 3
I could not get the display name, the back value is empty (I have checked the wp_users
table, ID = 3 really has a member.)
header("Content-type: text/html; charset=utf-8");
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "root";
$mysql_database = "test_db";
$db = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die('Error connection to database server: ' . mysql_error());
mysql_select_db($mysql_database, $db)
or die('Error connection to database server: ' . mysql_error());
mysql_query("SET NAMES utf8");
$results = mysql_query("SELECT * FROM test_table where id = 3");
while($row = mysql_fetch_array($results)) {
//echo $row['id']; I can get the $row['id'] value.
$foo_db = new wpdb('root','root','wp','localhost');
$foo_result = $foo_db->get_results("SELECT * FROM `wp_users` WHERE ID = '".addslashes($row['id'])."'",OBJECT);
foreach($foo_result as $user){
var_dump($user);
}
}
BTW: test_table is very simple, just has 1 field, record the user ID. (ID:1 – ID:33)
You should use all of the goodness of the wpdb object.
You can read more here: http://codex.wordpress.org/Class_Reference/wpdb#SELECT_Generic_Results
To note, if you are selecting from the same server that uses the same credentials, try the following instead so as not to nest another identical connection:
Hope this helps you!
try it like this one:
this should do it.
notice the prepare function used on the $wpdb object to ensure the safety of the query.