MySQL:获取某一行

时间:2009-06-06 08:33:04

标签: php mysql wordpress

我在MySQL上有这个表。我想查询port 1和2的user_id号码。

umeta_id  user_id  meta_key     meta_value
------------------------------------------
       1        1  nickname     admin
       8        1  userDir      D
       9        1  port         8080
      10        1  paymentopt   bankin
      13        2  port         8081
      20        2  a_renew      1240098300
      21        2  userDir      D
      22        2  paymentopt   paypal

我如何在PHP中完成?

谢谢!

3 个答案:

答案 0 :(得分:3)

一个非常简单的示例代码应基于http://uk.php.net/manual/en/mysqli-result.fetch-row.php

中的示例
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

$query = "SELECT `umeta_id`, `user_id`, `meta_key`, `meta_value` FROM TableName WHERE (`user_id` = 1 OR `user_id` = 2) AND (`meta_key` = 'port')"; //You will need to change TableName to whatever your table is called.

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($row = $result->fetch_row()) {
        echo $row[3];
    }

    /* free result set */
    $result->close();
}

/* close connection */
$mysqli->close();
?>

答案 1 :(得分:1)

SELECT * FROM table  
WHERE user_id = 1
    AND meta_key = 'port'

user_id = 2执行相同操作,或者如果要同时检索两个用户的端口,请在一个查询中执行此操作:

SELECT * FROM table 
WHERE (user_id = 1 OR user_id = 2)
    AND meta_key = 'port'

这个答案仅反映了SQL部分 - 我假设你知道如何使用所需的MySQL库(ext/mysqlext/mysqliext/PDO)向MySQL服务器发送查询。

答案 2 :(得分:-2)

我会使用它而不是上面提出的那些:

SELECT * FROM table WHERE user_id IN (1,2) AND meta_key = 'port'

使用数组等时,这也会使它更容易,更漂亮:

<?php
$users = array(1,2,3,4,5);
$sql = sprintf("SELECT * FROM table WHERE user_id IN (%s) AND meta_key = 'port'", implode(",", $users));
?>

<强> NB! 如果用户阵列不安全,请记得检查输入。例如,如果它是用户输入的结果。在这种情况下,你想做类似的事情:

<?php
$users = array_map($users, 'mysql_real_escape_string');
?>