简体   繁体   English

PHP-PDO尝试/捕获插入动态HTML链接

[英]PHP-PDO try/catch inserting dynamic html link

it seems i have run into a slight problem in my first shot at using PDO and prepared statements. 在使用PDO和准备好的语句的第一枪中,似乎遇到了一个小问题。 Basically I am working on a profile page which includes an Inbox. 基本上,我正在一个包含收件箱的个人资料页面上工作。 I am using try/catch to produce the inbox: 我正在使用try / catch生成收件箱:

<?php
$sqlin = $db->prepare("SELECT * FROM message WHERE recipientID = (SELECT id FROM members WHERE username = '$pageowner')");
try {
    while($row = $sqlin->fetch(PDO::FETCH_ASSOC)){
    ?>
    <br><a href="inbox.php?id=<?php echo $row['idmessage'] ?>"><?php echo $row['title'] ?></a>
    <?php 
    }
}
catch(PDOException $e) {
    die ($e->getMessage()); 
}
?>

So this is supposed to relate the user id to the recipient id, and then create links to the messages. 因此,这应该将用户ID与收件人ID相关联,然后创建指向消息的链接。 When I run in browser no links are listed 当我在浏览器中运行时,未列出任何链接

Is this an issue within my try/catch syntax? 这是我的try / catch语法中的问题吗? maybe stopping the php and inserting the html?--I tried echoing out but ran into problems creating that code. 也许停止php并插入html?-我尝试回显,但是在创建该代码时遇到了问题。

You have to start to try/catch the exception before the prepare() and after it. 您必须在prepare()之前和之后开始尝试/捕获异常。 And please use prepared statement, with prepare() method. 并请使用prepare()语句和prepare()方法。 Otherwise, you are defeating the purpuse of PDO by directly placing your variables inside the query. 否则,您可以通过直接将变量放在查询中来克服PDO的目的。 Which does not make your script safer from mysql injection. 这不会使您的脚本免受mysql注入的影响。

$pageOwner = 'some external data';
try {
   $sqlin = $db->prepare("
        SELECT * FROM message 
        WHERE recipientID = (
             SELECT id
             FROM members 
             WHERE username = ?
             ) 
        ");

    $sqlin->execute(array($pageOwner)); 

     }catch(PDOException $e){
        die ($e->getMessage()); 
     }

     while($row = $sqlin->fetch(PDO::FETCH_ASSOC)){
?>

<br><a href="inbox.php?id=<?= $row['idmessage'] ?>"><?= $row['title'] ?></a>

<?php  } ?>

first, you shouldn't use try..catch here at all. 首先, 您根本不应该在这里使用try..catch。

Instead, you have to call execute() and use prepared statements. 相反,您必须调用execute()并使用准备好的语句。 Also you have to separate your SQL from HTML. 另外,您还必须将SQL与HTML分开。 Here is the proper code. 这是正确的代码。

<?php
$sql = "SELECT m.* FROM message m, members mm WHERE recipientID = mm.id and username = ?";
$stm = $db->prepare($sql);
$stm->execute([$pageowner]);
$data = $stm->fetchAll();
?>
<?php foreach ($data as $row): ?>
    <br><a href="inbox.php?id=<?=$row['idmessage'] ?>"><?=$row['title'] ?></a>
<?php endforeach ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM