简体   繁体   English

根据主键值而不是行号检索PHP中的特定MySQL字段数据

[英]Retrieving Specific MySQL Field Data in PHP Based on Primary Key Value Instead of Row Number

I'm trying to find the correct way of pulling specific field data from a MySQL database and referencing it on a web page, using the primary key (an INT) in the row of data instead of the row number. 我试图找到一种正确的方法,使用数据行中的主键(INT)代替行号,从MySQL数据库中提取特定字段数据并在网页上引用它。 we tried: 我们尝试了:

$sql = "SELECT * FROM ourTable";
$result = mysql_result($sql, $con);
echo mysql_results($sql,$con);
echo mysql_result($result, 2, "pageTitle");
echo "<br />";
echo mysql_result($result, 2, "pageDate");`

But this returns values based on row number. 但这会根据行号返回值。 Instead we would like to make reference to the pageID in our database to populate the pageTitle and pageDate information. 相反,我们想引用数据库中的pageID来填充pageTitle和pageDate信息。

(The $con variable is referenced before this block) ($ con变量在此块之前被引用)

so say in my database I have: 所以说在我的数据库中,我有:

pageID pageTitle pageDate pageID pageTitle pageDate
001 Page1 1885 001第1885章
002 Page2 1976 002第2页1976
003 Page3 1776 第003章1776

As an example, on the web page, the data will be printed like: 例如,在网页上,数据将以如下方式打印:

Title: Page1 标题:第1页
Date: 1885 年代:1885

Thanks in advance for any help. 在此先感谢您的帮助。

Your query is selecting all rows from the table. 您的查询是从表中选择所有行。 You later extract a row by its position in the results array. 稍后,您可以根据行在结果数组中的位置提取行。 However, you should never make any assumptions about the order that your rows are stored or returned, unless you're using the ORDER BY keyword. 但是, 除非您使用ORDER BY关键字, 否则 切勿对行的存储或返回顺序进行任何假设。 Otherwise, you're not guaranteed that your rows will be returned in the order that you inserted them. 否则,您不能保证将按插入顺序返回行。

Like MichaelMior said, you can use the WHERE keyword to select a row based on the value of a column. 就像MichaelMior所说的那样,您可以使用WHERE关键字根据列的值选择一行。

$id = "001";
$sql = "SELECT * FROM ourTable WHERE pageID='$id'";
$result = mysql_result($sql, $con);

// Since you're selecting based on a unique key, you'll get only 0 or 1 rows
if( mysql_num_rows($result) == 1)
{
  // Parse the result
  echo mysql_result($result, 0, "pageTitle");
  echo "<br />";
  echo mysql_result($result, 0, "pageDate");
}

Edit, clarification: A primary key is by definition unique. 编辑,说明:根据定义, 主键是唯一的。

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

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