在 PHP 中以数组形式获取 MySQL 查询结果的最佳方法是什么?

发布于 2024-12-12 22:35:28 字数 376 浏览 0 评论 0原文

我是 PHP 新手。我有一个 select 语句,它为特定记录返回 100 个值。我想将这 100 个值存储在一个数组中。这是将从 select 语句获取的值存储到数组中的正确命令吗?

$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]

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?
}

Is there a way where I can avoid typing in the 100 attributes for my table? example : $row[1] ... $row[100]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

走过海棠暮 2024-12-19 22:35:28

如果你打算在 2011 年学习 PHP,那就好好学吧。

首先,不推荐使用 mysql_query 或 mysql_ Anything 代码。不要再使用它了。

别担心 - 我建议的内容非常适用于 mysql 数据库,但它也适用于任何数据库:

  • PDO 是 PHP 社区不断添加功能的内容,所以我会使用它。
  • PDO 也更强大,并且使以后切换数据库变得更容易。
  • MYSQLi(i 代表改进)取代了已弃用的基于 mysql_ 的查询,但我肯定会直接使用 PDO。
  • 您还可以轻松创建一个数组
    稍后对象的一行更改!

其次,Phil 提到了 fetchAll()。这是最终目标。其他方式只需一次一行地移动即可。这使用推土机而不是铲子。注意:这不是选择大量数据的最佳方法,因为它会耗尽内存。否则的话,也没关系。

为此,请使用准备好的过程来保护您的代码免受 SQL 注入攻击。

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

/* Fetch all of the rows into an array */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);

?>

If you are going to learn PHP in 2011, let's do it right.

First off, mysql_query or mysql_ anything code is deprecated. Don't use it anymore.

Don't worry - what I am suggesting works great with mysql databases, but it will also work great with any database:

  • PDO is what the PHP community continues to add features to, so I would use that.
  • PDO is also way more powerful, and makes it easier to switch databases later.
  • MYSQLi (the i stands for improved) replaces deprecated mysql_ based queries, but I would definitely go straight to using PDO.
  • You could also easily create an array
    of objects later with one line change!

Secondly, Phil mentioned fetchAll(). This is the end goal. The other ways simply move thru it one row at a time. This uses a bulldozer instead of a shovel. Note: not the best way of selecting really large amounts of data, as it will use up memory. Otherwise, it is fine.

To get there, use prepared procedures to protect your code from SQL injection attacks.

<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindParam(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();

/* Fetch all of the rows into an array */
print("Fetch all of the remaining rows in the result set:\n");
$result = $sth->fetchAll();
print_r($result);

?>
镜花水月 2024-12-19 22:35:28

你的代码对我来说看起来不错。但我建议使用 mysql_fetch_assoc() 而不是 mysql_fetch_array(),以便将键映射到它们的值。另外,使用 mysql_real_escape_string() 来防止 SQL 注入。

 $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;               
 }

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;               
 }
吾性傲以野 2024-12-19 22:35:28

如果您尝试将所有数据库行存储到一个数组中,是的,该代码应该可以做到这一点。不过,有一些评论:

  1. 正如 curiou57 所建议的,使用 mysql_fetch_assoc() 能够通过名称引用单个行中的列。 (例如: foreach ($data as $row) { echo $row['columnname']; })
  2. 确保通过 mysql_real_escape_string() 运行 $id 如果您必须继续使用 mysql 扩展。这可以防止 SQL 注入攻击。
  3. 如果您不必继续使用 mysql 扩展,请考虑使用 PDO 或 mysqli。

If you're trying to store all the database rows into an array, yes, that code should do it. A few comments, though:

  1. As curiou57 suggested, use mysql_fetch_assoc() to be able to refer to columns in an individual row by their names. (ex: foreach ($data as $row) { echo $row['columnname']; })
  2. Make sure you run $id through mysql_real_escape_string() if you have to continue using the mysql extension. This prevents SQL injection attacks.
  3. If you don't have to continue using the mysql extension, consider using PDO or mysqli.
哥,最终变帅啦 2024-12-19 22:35:28

切换到 mysql_fetch_row() 如果您想通过数字索引(注意,从零开始)引用每列。否则,这看起来是正确的。

如果您决定切换到 PDO,您可以使用方便的 PDOStatement::fetchAll( ) 方法,使用 PDO::FETCH_NUM 获取样式将所有行作为数值数组获取到数组中。

Switch to mysql_fetch_row() if you want to reference each column by a numeric index (note, zero-based). Otherwise, that looks correct.

If you decide to switch to PDO, you can use the handy PDOStatement::fetchAll() method, using the PDO::FETCH_NUM fetch style to fetch all rows as numeric arrays into an array.

只涨不跌 2024-12-19 22:35:28

这是正确的方法:

while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows);  // pop the last row off, which is an empty row

This is the correct way:

while($rows[] = mysqli_fetch_assoc($result));
array_pop($rows);  // pop the last row off, which is an empty row
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文