简体   繁体   English

MySQL:获取特定行

[英]MySQL: Get a certain row

I have this table on MySQL. 我在MySQL上有此表。 I want to query the port number for user_id s 1 and 2. 我想查询user_id 1和2的port号。

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

How do I do it in PHP? 如何在PHP中做到这一点?

Thank you! 谢谢!

A very simple bit of example code should work based on example from http://uk.php.net/manual/en/mysqli-result.fetch-row.php 一个非常简单的示例代码应该基于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();
?>
SELECT * FROM table  
WHERE user_id = 1
    AND meta_key = 'port'

Do the same for user_id = 2 or if you want to retrieve the ports of both users simultaneously do this in one query: user_id = 2进行相同的操作,或者如果要同时检索两个用户的端口,请在一个查询中执行此操作:

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

This answer reflects just the SQL-part - I assume that you know how to send queries to a MySQL server using the desired MySQL library ( ext/mysql , ext/mysqli or ext/PDO ). 这个答案仅反映了SQL部分-我假设您知道如何使用所需的MySQL库( ext/mysqlext/mysqliext/PDO )将查询发送到MySQL服务器。

I'd use this instead of the ones proposed above: 我将用它代替上面建议的方法:

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

This will also make it easier and prettier when working with arrays etc: 当使用数组等时,这也将使它变得更容易,更漂亮:

<?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! NB! Remember to check the input if the users array is not safe. 如果用户数组不安全,请记住检查输入。 For example if it is the result of a user input. 例如,如果这是用户输入的结果。 In that case you'd like to do something similar to this: 在这种情况下,您想要执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM