PHP - 从 MySQL 读取单条记录的简单方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/811153/
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-24 23:55:39  来源:igfitidea点击:

PHP - Simple way to read single record from MySQL

phpmysql

提问by neon

What's the best way with PHP to read a single record from a MySQL database? E.g.:

使用 PHP 从 MySQL 数据库读取单个记录的最佳方法是什么?例如:

SELECT id FROM games

I was trying to find an answer in the old questions, but had no luck.

我试图在旧问题中找到答案,但没有运气。

回答by Dan Grossman

$id = mysql_result(mysql_query("SELECT id FROM games LIMIT 1"),0);

回答by Rytis Luko?evi?ius

$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database_name', $link);
$sql = 'SELECT id FROM games LIMIT 1';
$result = mysql_query($sql, $link) or die(mysql_error());
$row = mysql_fetch_assoc($result);
print_r($row);

There were few things missing in ChrisAD answer. After connecting to mysql it's crucial to select database and also die()statement allows you to see errors if they occur.

ChrisAD 的回答中几乎没有遗漏什么。连接到 mysql 后,选择数据库至关重要,die()如果发生错误,语句还允许您查看错误。

Be carefull it works only if you have 1 record in the database, because otherwise you need to add WHERE id=xxor something similar to get onlyone row and not more. Also you can access your id like $row['id']

要小心,如果你在数据库中记录1它仅适用,因为如果你需要添加WHERE id=xx或类似的东西来获得只有一个排,而不是更多。你也可以访问你的id$row['id']

回答by Tom Haigh

Using PDOyou could do something like this:

使用PDO你可以做这样的事情:

$db = new PDO('mysql:host=hostname;dbname=dbname', 'username', 'password');

$stmt = $db->query('select id from games where ...');
$id = $stmt->fetchColumn(0);
if ($id !== false) {
    echo $id;
}

You obviously should also check whether PDO::query()executes the query OK (either by checking the result or telling PDO to throw exceptions instead)

您显然还应该检查PDO::query()执行查询是否正常(通过检查结果或告诉 PDO 抛出异常)

回答by prl77

Assuming you are using an auto-incrementing primary key, which is the normal way to do things, then you can access the key value of the last row you put into the database with:

假设您使用的是自动递增的主键,这是正常的操作方式,那么您可以使用以下命令访问放入数据库的最后一行的键值:

$userID = mysqli_insert_id($link);

otherwise, you'll have to know more specifics about the row you are trying to find, such as email address. Without knowing your table structure, we can't be more specific.

否则,您必须了解有关您要查找的行的更多细节,例如电子邮件地址。在不知道您的表结构的情况下,我们无法更具体。

Either way, to limit your SELECTquery, use a WHEREstatement like this: (Generic Example)

无论哪种方式,要限制您的SELECT查询,请使用如下WHERE语句:(通用示例)

$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE something = 'unique'"));
$userID = $getID['userID'];

(Specific example) Or a more specific example:

(具体示例)或更具体的示例:

$getID = mysqli_fetch_assoc(mysqli_query($link, "SELECT userID FROM users WHERE userID = 1"));
$userID = $getID['userID'];

回答by Robert K

Warning! Your SQL isn't a good idea, because it will select all rows (no WHERE clause assumes "WHERE 1"!) and clog your application if you have a large number of rows. (What's the point of selecting 1,000 rows when 1 will do?) So instead, when selecting only one row, make sure you specify the LIMIT clause:

警告!您的 SQL 不是一个好主意,因为它会选择所有行(没有 WHERE 子句假定“WHERE 1”!)并在您有大量行时阻塞您的应用程序。(当 1 行时选择 1,000 行有什么意义?)因此,当只选择一行时,请确保指定 LIMIT 子句:

$sql = "SELECT id FROM games LIMIT 1";  // Select ONLY one, instead of all
$result = $db->query($sql);
$row = $result->fetch_assoc();
echo 'Game ID: '.$row['id'];

This difference requires MySQL to select onlythe first matching record, so ordering the table is important or you ought to use a WHERE clause. However, it's a whole lot less memory and time to find that one record, than to get every record and output row number one.

这种差异要求 MySQL选择第一条匹配的记录,因此对表进行排序很重要,否则您应该使用 WHERE 子句。但是,与获取每条记录并输出第一行相比,查找该记录所需的内存和时间要少得多。

回答by danny

Use LIMIT 1. its easy.

使用 LIMIT 1. 很简单。

$rows = $db->query("select id from games LIMIT 1");
$row  =  $rows->fetch_object();
echo $row->id;

回答by MaggusK

One more answer for object oriented style. Found this solution for me:

面向对象风格的另一种答案。为我找到了这个解决方案:

$id = $dbh->query("SELECT id FROM mytable WHERE mycolumn = 'foo'")->fetch_object()->id;

gives back just one id. Verify that your design ensures you got the right one.

只返回一个 id。验证您的设计确保您得到正确的设计。

回答by Powerlord

The easiest way is to use mysql_result. I copied some of the code below from other answers to save time.

最简单的方法是使用mysql_result. 我从其他答案中复制了下面的一些代码以节省时间。

$link = mysql_connect('localhost','root','yourPassword')
mysql_select_db('database',$link);
$sql = 'SELECT id FROM games'
$result = mysql_query($sql,$link);

$num_rows = mysql_num_rows($result);

// i is the row number and will be 0 through $num_rows-1
for ($i = 0; $i < $num_rows; $i++) {
    $value = mysql_result($result, i, 'id');
    echo 'Row ', i, ': ', $value, "\n";
}

回答by gavinandresen

I really like the philosophy of the ezSQL database library, which wraps the native SQL methods in an easier-to-use interface.

我真的很喜欢ezSQL 数据库库的理念,它将本机 SQL 方法包装在一个更易于使用的界面中。

Fetching a single value from the database is trivial:

从数据库中获取单个值是微不足道的:

  $id = $db->get_var("SELECT id FROM games WHERE ...");

It also makes it easy to fetch a single row, column, or set of rows.

它还可以轻松获取单行、单列或一组行。

回答by markus

'Best way' aside some usual ways of retrieving a single record from the database with PHP go like that:

除了使用 PHP 从数据库中检索单个记录的一些常用方法之外,“最佳方法”如下所示:

with mysqli

使用 mysqli

$sql = "SELECT id, name, producer FROM games WHERE user_id = 1";
$result = $db->query($sql);
$row = $result->fetch_row();

with Zend Framework

使用 Zend 框架

//Inside the table class

//表类内部

$select = $this->select()->where('user_id = ?', 1);  
$row = $this->fetchRow($select);