doupi4649 2014-03-18 01:54
浏览 16

尝试用准备好的声明回应

I am trying to go from mySQL (about time?) to PDO - but I am having trouble in making sense of how things are supposed to be written. I want to be protected from injection, but I just can't figure out how to do it properly. It just seems so confusing. It might be because I'm doing it COMPLETELY wrong?

Been looking around for help on various sides doing tutorials, but :(

Any chance someone could assist me? Explain/show like I'm five?

<?php
$col_playername = "playername";
$tbl_playerdata = "player_data";
$post_search = "$_POST[search]";

$sth = $dbh->prepare("SELECT :col_playername FROM :tbl_playerdata
                WHERE :col_playername LIKE %:post_search%
                LIMIT 5");

$sth->bindParam(":col_playername", $col_playername);
$sth->bindParam(":tbl_playerdata", $tbl_playerdata);
$sth->bindParam(":post_search", $post_search);  

$sth->execute();

foreach ($sth as $row)
{
    ?>
    <div id="search_show">
        <a href="?target=<?php echo $row["playername"]; ?>"><?php echo $row["playername"]; ?></a> 
    </div>
    <?php
}
?>

As of right now - nothing is coming out. I wouldn't be surprised if this is absolutely wrong.

  • 写回答

1条回答 默认 最新

  • down2323 2014-03-18 01:57
    关注

    $statement->execute() will execute, but not fetch your rows.

    You need to add either $statement->fetch() to get one result set, or $statement->fetchAll to get an array:

    $sth->execute();
    
    $rows = $sth->fetchAll();
    
    foreach ($rows as $row)
    {
        //do stuff
    }
    

    Note: Since you are handling your results as associative arrays, you should this before preparing anything. It will save you from specifying the fetch mode with every single fetch().

    $dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式
  • ¥50 potsgresql15备份问题
  • ¥15 Mac系统vs code使用phpstudy如何配置debug来调试php
  • ¥15 目前主流的音乐软件,像网易云音乐,QQ音乐他们的前端和后台部分是用的什么技术实现的?求解!
  • ¥60 pb数据库修改与连接
  • ¥15 spss统计中二分类变量和有序变量的相关性分析可以用kendall相关分析吗?
  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错