刚开始学习PHP,Angular和mySQL,我试图从一行中只检索一个字段值。下面的代码适用于返回多行的查询:
$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]));
答案 0 :(得分:1)
我强烈建议您切换到mysqli
扩展程序。这是一种更好的做事方式,你可能会发现它更容易。
以下是一个简单的mysqli解决方案:
$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();
如果您抓住多行,我会这样做:
$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();
使用错误处理:如果发生致命错误,脚本将以错误消息终止。
// 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();
使用try / catch异常处理:这使您可以在一个地方处理任何错误,并在可能出现故障时继续执行,如果需要的话。
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";
}
MySQL扩展名是:
mysqli
不支持:
由于它已被弃用,因此使用它会使您的代码不再适用于未来。请参阅the comparison of SQL extensions。
答案 1 :(得分:0)
您尚未执行查询,因此您永远无法获得结果。
nfc-mfclassic
。$qry
$result
循环获取行和单元格(您称之为字段)。以下是我更正过的代码:
$result