【问题标题】:impossible to display value from DB无法显示来自 DB 的值
【发布时间】:2019-01-18 11:46:53
【问题描述】:

我为我的网站更改了 php 代码,因为我需要使用更多的安全性。我读了很多关于这个的信息,我从例子中做了同样的事情,但不幸的是它不起作用。数据库没有结果,没有错误

之前(工作正常)

连接php

<?php
try { 
$db = new PDO('mysql:host=localhost;dbname=belam647807; charset=utf8','root','root'); }
catch(Exception $e) {die('Erreur : '.$e->getMessage());}
?>

选择代码

<?php $nbPage = ceil($total/$perPage);

if(isset($_GET['page']) && !empty($_GET['page']) &&  ctype_digit($_GET['page']) == 1){
if ($_GET['page'] > $nbPage) {
  $page = $nbPage;
}else{
  $page = $_GET['page'];
}

}else{

 $page = 1;
}

$first = ($page-1)*$perPage;


$reponse = $db->query("SELECT * FROM profils ORDER BY id DESC LIMIT    $first, $perPage" );
while ($donnees = $reponse->fetch())
{
?>

更改 PDO 后

连接php

<?php


$db = new PDO('mysql:host=localhost;dbname=test, charset=utf8', 'root', 'root');

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

?>

选择代码

<?php $nbPage = ceil($total/$perPage);

if(isset($_GET['page']) && !empty($_GET['page']) && ctype_digit($_GET['page']) == 1){
if ($_GET['page'] > $nbPage) {
  $page = $nbPage;
}else{
  $page = $_GET['page'];
}

}else{

$page = 1;
}

$first = ($page-1)*$perPage;

$reponse = $db->prepare("SELECT * FROM profils ORDER BY id DESC LIMIT $first, $perPage" );
$reponse->execute();
while ($donnees = $reponse->fetch(PDO::FETCH_ASSOC)){
?>

【问题讨论】:

  • 这段代码怎么失败了?您的 PHP 日志中是否有任何错误?调试时,具体发生了什么?

标签: sql pdo connection


【解决方案1】:

从准备语句中删除变量并绑定值。

$sql = "SELECT * FROM profils ORDER BY id DESC LIMIT :first, :perPage";
$sth = $db->prepare($sql);
$sth->bindValue(':first', $first);
$sth->bindValue(':perPage', $perPage);

if ($sth->execute()) {
    if ($sth->rowCount() > 0) {
        $data = $sth->fetch(PDO::FETCH_ASSOC);
    }
}
print_r($data);

【讨论】:

  • 感谢您的代码,我试过了,但我有一个空白页
猜你喜欢
  • 1970-01-01
  • 2014-10-28
  • 2016-03-04
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 2011-12-23
  • 1970-01-01
相关资源
最近更新 更多