php 从 MySQL 返回一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11302379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 00:13:18  来源:igfitidea点击:

Return One Row from MySQL

phpmysqlrowuniquefetch

提问by user1114864

Amateur question, but something I've been wondering about. What is the PHP for selecting one row from a MySQL query? AKA you're picking something by unique ID (you know there's only one row that matches your request) and want to get only that value. Do you still have to use a while loop and mysql_fetch_row?

业余问题,但我一直想知道的问题。从 MySQL 查询中选择一行的 PHP 是什么?也就是您通过唯一 ID 选择某些东西(您知道只有一行符合您的请求)并且只想获得该值。你还需要使用while循环和mysql_fetch_row吗?

$query = "SELECT name,age FROM people WHERE uid = '2'";
$result = mysql_query($query);

// what php is used to return the name and age?  preferably without a loop?

回答by mgraph

add limit 0,1:

添加limit 0,1

$query = "SELECT name,age FROM people WHERE uid = '2' LIMIT 0,1";
$result = mysql_query($query);
$res = mysql_fetch_assoc($result);

echo $res["age"]; 

回答by gcochard

If uidis your primary key, or it has a uniqueconstraint, you can simply call mysql_fetch_row($res)once.

如果uid是你的主键,或者它有一个unique约束,你可以简单地调用mysql_fetch_row($res)一次。

If you want to verify that you actually got a result, you can check if mysql_num_rows($res) == 1.

如果你想验证你是否真的得到了结果,你可以检查是否mysql_num_rows($res) == 1.

回答by Daniel Aranda

There is not any loop required, just call the function to extract one row from a Query Resultset:

不需要任何循环,只需调用函数从查询结果集中提取一行:

$query = "SELECT name,age FROM people WHERE uid = '2'";
$result = mysql_query($query);
$row = mysql_fetch_assoc( $result );
var_dump( $row );

回答by John Woo

Add LIMITin your query. For instance,

添加LIMIT您的查询。例如,

SELECT name,age FROM people WHERE uid = '2' LIMIT 1

回答by Porta Shqipe

Here is another example:

这是另一个例子:

<?php
    mysql_connect("server","user","password")
    or die ('Connection failed: ' . mysql_error() ); 
    //
    mysql_select_db ("database")
    or die ('Selection failed: ' . mysql_error());
    //
    $portaQuery = "SELECT user_name FROM table_users";
    //
    $portaResult = mysql_query($portaQuery) 
    or die ('Query failed: ' . mysql_error());
    //
    $displayUserName = mysql_result ($portaResult, 0, "user_name" );
    //
    echo $displayUserName;
?>