我试图将存储在数据库中的日期列表放入数组中。我尝试了以下函数,但我只得到“数组”。我不确定我做错了什么,或者是否有其他方法来检索日期。
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 thearray()
structure.
有关 PDO 中 fetch 语句的一些更清晰的解释。
PDO 有一些非常方便的方法来以不同的格式返回查询结果:
fetch()
- 类似于 mysql_fetch_array() 的通用获取方法。fetchAll()
- 无需 while 循环即可获取所有行。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/