使用 PHP 从 mysql db 中选择并回显单个字段

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

select and echo a single field from mysql db using PHP

phpmysql

提问by mrpatg

Im trying to select the title column from a particular row

我试图从特定行中选择标题列

$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
echo $result;

all i get is Resource id #19

我得到的只是 Resource id #19

How should i do this? What is best method?

我该怎么做?什么是最好的方法?

采纳答案by dfilkovi

$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$field];

but beware of sql injection cause you are using $_GET directly in a query. The danger of injection is particularly bad because there's no database function to escape identifiers. Instead, you need to pass the field through a whitelist or (better still) use a different name externally than the column name and map the external names to column names. Invalid external names would result in an error.

但要注意 sql 注入,因为您直接在查询中使用 $_GET。注入的危险特别严重,因为没有数据库函数来逃避标识符。相反,您需要通过白名单传递该字段或(更好)在外部使用与列名称不同的名称并将外部名称映射到列名称。无效的外部名称会导致错误。

回答by Franz

Try this:

尝试这个:

echo mysql_result($result, 0);

This is enough because you are only fetching one field of one row.

这足够了,因为您只获取一行的一个字段。

回答by TheGrandWazoo

Read the manual, it covers it very well: http://php.net/manual/en/function.mysql-query.php

阅读手册,它涵盖得很好:http: //php.net/manual/en/function.mysql-query.php

Usually you do something like this:

通常你会做这样的事情:

while ($row = mysql_fetch_assoc($result)) {
  echo $row['firstname'];
  echo $row['lastname'];
  echo $row['address'];
  echo $row['age'];
}

回答by Ben Fransen

And escape your values with mysql_real_escape_string since PHP6 won't do that for you anymore! :)

并使用 mysql_real_escape_string 转义您的值,因为 PHP6 不会再为您这样做了!:)