如何使用 PHP mysql_fetch_array 检索一个 row/one 字段

How to retrieve one row/one field using PHP mysql_fetch_array

刚开始学习 PHP、Angular 和 mySQL,我正在尝试从一行中仅检索一个字段值。下面的相同代码适用于 returns 多行的查询:

$qry = "SELECT ID FROM SharePoint001 ORDER BY DownloadedTimeStamp DESC LIMIT 1"; //returns a5f415a7-3d4f-11e5-b52f-b82a72d52c35        
$data = array();   
while($rows = mysql_fetch_array($qry))
{
    $data[] = array("ID" => $rows['ID']);
}
print_r(json_encode($data[0])); 

您还没有执行查询,所以您永远不会得到结果。

  1. 首先,您必须准备查询并将其放入一个变量中,比方说 $qry
  2. 然后使用mysql_query()函数执行该查询,并将结果捕获到变量中 让我们说 $result
  3. 现在您可以迭代 $result 循环获取单元格(你称之为字段)。

下面是我更正的代码:

$qry = "SELECT ID FROM SharePoint001 ORDER BY DownloadedTimeStamp DESC LIMIT 1"; 
$result = mysql_query($qry); // You are missing this line

$data = array();   
while($rows = mysql_fetch_array($result)) // You have to pass result into mysql_fetch_array not query string 
{
    $data[] = array("ID" => $rows['ID']);
}
print_r(json_encode($data[0])); 

我强烈建议切换到 mysqli 扩展。这是一种更好的做事方式,您可能会发现它更容易。

Here's a simple mysqli solution for you:

$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
$row = $resource->fetch_assoc();
echo "{$row['field']}";
$resource->free();
$db->close();

If you're grabbing more than one row, I do it like this:

$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
while ( $row = $resource->fetch_assoc() ) {
    echo "{$row['field']}";
}
$resource->free();
$db->close();

With Error Handling: If there is a fatal error the script will terminate with an error message.

// ini_set('display_errors',1); // Uncomment to show errors to the end user.
if ( $db->connect_errno ) die("Database Connection Failed: ".$db->connect_error);
$db = new mysqli('localhost','user','password','database');
$resource = $db->query('SELECT field FROM table WHERE 1');
if ( !$resource ) die('Database Error: '.$db->error);
while ( $row = $resource->fetch_assoc() ) {
    echo "{$row['field']}";
}
$resource->free();
$db->close();

With try/catch exception handling: This lets you deal with any errors all in one place and possibly continue execution when something fails, if that's desired.

try {
    if ( $db->connect_errno ) throw new Exception("Connection Failed: ".$db->connect_error);
    $db = new mysqli('localhost','user','password','database');
    $resource = $db->query('SELECT field FROM table WHERE 1');
    if ( !$resource ) throw new Exception($db->error);
    while ( $row = $resource->fetch_assoc() ) {
        echo "{$row['field']}";
    }
    $resource->free();
    $db->close();
} catch (Exception $e) {
    echo "DB Exception: ",$e->getMessage(),"\n";
}

The MySQL extension is:

Does not support:

  • 非阻塞、异步查询
  • 交易
  • 存储过程
  • 多个语句
  • Prepared statements 或参数化查询
  • "new" 密码验证方法(MySQL 5.6 默认启用;5.7+ 要求)

由于它已被弃用,使用它会使您的代码不那么适合未来。参见 the comparison of SQL extensions