在PHP中以数组形式获取MySQL查询结果的最佳方法是什么? [英] What is the best way to get MySQL query results as an array in PHP?
问题描述
我是PHP的新手.我有一条select语句,它为特定记录返回100个值.我想将这100个值存储在数组中.这是将我从select语句获得的值存储到数组中的正确命令吗?
I'm new to PHP. I have a select statement that returns 100 values for a particular record. I'd like to store these 100 values in an array. Is this the right command to store values that I get from a select statement into an array?
$result = mysql_query("select * from processed1 where record = ('$id') ");
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = $row; //IS THIS CORRECT?
}
有没有一种方法可以避免为表格输入100个属性?例如:$ row [1] ... $ row [100]
Is there a way where I can avoid typing in the 100 attributes for my table? example : $row[1] ... $row[100]
推荐答案
您的代码对我来说很好.但是我建议使用mysql_fetch_assoc()而不是mysql_fetch_array(),以便将键映射到它们的值.另外,使用mysql_real_escape_string()防止SQL注入.
Your code looks fine to me. But I would suggest to use mysql_fetch_assoc() instead of mysql_fetch_array(), so that keys are mapped to their values. Also, use mysql_real_escape_string() to prevent SQL injection.
$query = "Select * from processed1 where record = '".mysql_real_escape_string($id)."'";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_assoc($result))
{
$data[] = $row;
}
这篇关于在PHP中以数组形式获取MySQL查询结果的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!