php - 将数据库中的日期存储在数组中

标签 php mysql pdo

我试图将存储在数据库中的日期列表放入数组中。我尝试了以下函数,但我只得到“数组”。我不确定我做错了什么,或者是否有其他方法来检索日期。

function getdate($id) {

   $select = $this->db->query("select * from dates where user_id= '$id' ");
   $result_array = array();

   while($row = $select->fetch( PDO::FETCH_ASSOC )){
        $result_array[] = $row['date'];
   }

   return $result_array;

}

最佳答案

While using the PDO statements you could follow up the procedure where PDO is strong enough to avoid SQL Injections. But you have not followed up the process in your code. Usage of bind parameters is advised.

注意:除了 fetch 语句之外,您的代码将运行良好。您必须fetchAll();,以便它能够捕获结果查询中的所有数据并可以打印它。

如果是这种情况,您必须使用 fetchAll(); 从数据库检索多行输出,或者检索单行输出,您的代码看起来不错。

解决方案一:

You can use bind parameters in the function so that it avoids SQL Injections.

functions.php

function getdate($id)
{
$select = $conn->prepare("SELECT `date` FROM `dates` WHERE user_id= :id ");
$select->bindValue(':id', $id, PDO::PARAM_INT);
$select->execute();
$result = $select->fetchAll(PDO::FETCH_ASSOC);
return $result;
}

其他文件你可以像这样获得函数调用。

$result = getdate(3);

And you have to print_r() the $result. So that it will be resulting in the array() structure.

有关 PDO 中 fetch 语句的一些更清晰的解释。

PDO 有一些非常方便的方法来以不同的格式返回查询结果:

  1. fetch() - 类似于 mysql_fetch_array() 的通用获取方法。
  2. fetchAll() - 无需 while 循环即可获取所有行。
  3. fetchColumn() - 获取单个标量值而不先获取数组。

示例:

$stmt = $pdo->prepare("SELECT id,name FROM songs WHERE dt=curdate()");
$stmt->execute();
$data = $stmt->fetchAll();

现在我们在 $data 数组中拥有所有歌曲,我们可以根据需要设计页面。

<table>
<?php foreach ($data as $row): ?>
  <tr>
    <td>
      <a href="songs.php?<?=$row['id']?>">
        <?=htmlspecialchars($row['name'])?>
      </a>
    </td>
  </tr>
<?php endforeach ?>
</table>

关于php - 将数据库中的日期存储在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39759488/

相关文章:

php - 对齐字符串算法

mysql - 将图片存入数据库

mysql - 如何检查查询是否返回 true 或 false 以替换 PDO 中的 mysql_error()

php - $_POST 变量在 php 中为空

javascript - 使用单个 jQuery 脚本更新多个 DIV - 标签

php - 以周格式显示记录

MySQL 是否可以在 LIMIT 语法之后进行子查询?如果不是,为什么?

MySQL:根据另一个表中的数据和 NO JOIN 的条件删除行

php - 如何将 fetch(PDO::FETCH_ASSOC) 中的单个值或整个数组存储在变量中?

php - Oracle 是否阻止 PHP 使用 PDO 访问 MYSQL?