当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Querying user_meta table to look up email in the wp_users table

问题描述:

I have created a simple html form to submit a value to a php script I have written. I am using wordpress. I want the script to look up a user in the user_meta table, and select the user ID. I then want the script to look up the email of that user in the wp_users table. Here is the code I have:

<?php

global $wpdb;

$userid = $wpdb->get_var ( $wpdb->prepare (

"

SELECT user_id

FROM $wpdb->user_meta

WHERE user_meta = %s

",

$_POST["submitted_value"] ) );

$useremail = $wpdb->get_var (

"

SELECT user_email

FROM $wpdb->wp_users

WHERE ID = %s

"

, $userid );

echo 'Car Owner Email is' . $useremail . '!';

echo "test" . $_POST["submitted_value"] ."!";

?>

Now, I have run the script and the last line appears to be working -- it is printing the 'submitted_value' from my html form - but it does not seem to be querying the database.

this is the entire php script -- I am placing it in the wordpress plugins directory -- do I need to add anything else to get it to query my wordpress database?

网友答案:
    global $wpdb;
$query1 = "SELECT user_id FROM wp_usermeta WHERE meta_key = 'your_meta_key_name' AND meta_value = '$_POST["submitted_value"]'";
$userid = $wpdb->get_var($query1);

$query = "SELECT user_email FROM wp_users WHERE ID = '$userid'";
$useremail = $wpdb->get_var($query);
  1. Table name is wp_usermeta and not wp_user_meta
  2. In WHERE Clause, you need to give a meta key with which the value has to be mapped. Ex: WHERE meta_key = 'nickname' and meta_value = 'pranita'. Replace 'your_meta_key_name' with proper key with which you are matching your form value.

  3. If you don't understand fields, check wp_usermeta table in phpmyadmin.

Hope this helps. All The Best

网友答案:

You should update your code:

<?php
global $wpdb;
$userInfo = $wpdb->get_row  ( $wpdb->prepare ("
    SELECT user_id, user_email
    FROM $wpdb->usermeta um
    INNER JOIN $wpdb->users u ON (u.ID=um.user_id)
    WHERE meta_key = %s", //OR meta_value !!
    $_POST["submitted_value"]
));


echo 'Car Owner Email is' . $userInfo->user_email. '!';
echo "test" . $_POST["submitted_value"] ."!";

?>

But you can do it easily following the WP codex: http://codex.wordpress.org/Function_Reference/get_users/

$users = get_users(array('meta_key' => $_POST["submitted_value"]));

In this case you will get all possible users and you may need to run a loop.

分享给朋友:
您可能感兴趣的文章:
随机阅读: