Mysqli准备的语句未在每个for循环帖子中获取正确的值

时间:2019-05-28 07:18:15

标签: php for-loop mysqli prepared-statement

我无法使用从剥离RSS提要中的链接获得的ID来获取每个帖子的正确字段值。

MyBB rss提要未在rss提要中提供作者值,因此我使用包含线程ID的提要中的链接手动获取了该值。我认为我可以从链接中成功获取正确的线程ID,因为我可以在每个帖子中回显正确的线程ID。因此,在获取数据库中的作者字段(用户名)时,我对线程ID使用相同的变量。我正在获取用户名字段,但所有帖子都显示相同的内容,它实际上是最后发布的用户名。我能够使它正常工作,并找到合适的作者,但是由于生活中有些疯狂的事情,而且我确实是该领域的新手,所以我无法备份并忘记了我是怎么做到的。

这是我用来从Feed中发布帖子的代码:

            <?php

                //Getting RSS Feed
                $rss = new DOMDocument();
                $rss->load('https://www.cmricths.com/board/syndication.php?fid=2');
                $feed = array();

                foreach ($rss->getElementsByTagName('item') as $node) {
                    $item = array ( 
                        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
                        'desc' => $node->getElementsByTagName('encoded')->item(0)->nodeValue,
                        'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
                        'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
                        );
                    array_push($feed, $item);
                }

                //Setting Feed Limits
                $fid = 2;
                $limit = 5;

                require_once 'queries/threadcount.php';

                if ($tcount > $limit) {
                    $tlimit = $limit;
                } else {
                    $tlimit = $tcount;
                }

                //Posting the feed
                for($x=0;$x<$tlimit;$x++) {

                    $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
                    $link = $feed[$x]['link'];
                    $description = $feed[$x]['desc'];
                    $date = date('l F d, Y', strtotime($feed[$x]['date']));

                    //getting thread id from the link
                    $arr = explode('=', $link);
                    $tid = $arr[1];

                    //fetching the author
                    require_once 'queries/postedby.php';

                    //post summary
                    echo '<h2 class="blog-post-title">'.$title.'</h2>';
                    echo '<p class="blog-post-meta">'.$date.' <em>by: '.$author.' '.$tid.'</em></p>';
                    echo '<p class="mb-0">'.$description.'</p>';
                    echo '<hr />';

                }

            ?>

这是获取作者的代码:

<?php
/*

References: 
*jQuery Remote Validation
*https://websitebeaver.com/prepared-statements-in-php-mysqli-to-prevent-sql-injection

*/

// Get Connection Details
require_once 'config.php';

// Setup the connection
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if($mysqli->connect_error) {

    echo json_encode('Error connecting to database!');
    exit;

} else {

    // Do the validation process
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli->set_charset("utf8mb4");

    //Prepare the statement
    $stmt = $mysqli->prepare("SELECT `username` FROM `mybb_posts` WHERE `tid` = ?");

    //Bind the parameter
    $stmt->bind_param("i", $tid);

    //Execute the statement
    $stmt->execute();

    //Get the result
    $result = $stmt->get_result();

    //Fetch Data
    $row = $result->fetch_array();

    $author = $row['username'];

}


?>

这是我的sql数据文件:

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for mybb_posts
-- ----------------------------
DROP TABLE IF EXISTS `mybb_posts`;
CREATE TABLE `mybb_posts`  (
  `pid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
  `tid` int(10) UNSIGNED NOT NULL DEFAULT 0,
  `replyto` int(10) UNSIGNED NOT NULL DEFAULT 0,
  `fid` smallint(5) UNSIGNED NOT NULL DEFAULT 0,
  `subject` varchar(120) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `icon` smallint(5) UNSIGNED NOT NULL DEFAULT 0,
  `uid` int(10) UNSIGNED NOT NULL DEFAULT 0,
  `username` varchar(80) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `dateline` int(10) UNSIGNED NOT NULL DEFAULT 0,
  `message` text CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `ipaddress` varbinary(16) NOT NULL DEFAULT '',
  `includesig` tinyint(1) NOT NULL DEFAULT 0,
  `smilieoff` tinyint(1) NOT NULL DEFAULT 0,
  `edituid` int(10) UNSIGNED NOT NULL DEFAULT 0,
  `edittime` int(10) UNSIGNED NOT NULL DEFAULT 0,
  `editreason` varchar(150) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '',
  `visible` tinyint(1) NOT NULL DEFAULT 0,
  PRIMARY KEY (`pid`) USING BTREE,
  INDEX `tid`(`tid`, `uid`) USING BTREE,
  INDEX `uid`(`uid`) USING BTREE,
  INDEX `visible`(`visible`) USING BTREE,
  INDEX `dateline`(`dateline`) USING BTREE,
  INDEX `ipaddress`(`ipaddress`) USING BTREE,
  INDEX `tiddate`(`tid`, `dateline`) USING BTREE,
  FULLTEXT INDEX `message`(`message`)
) ENGINE = MyISAM AUTO_INCREMENT = 12 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of mybb_posts
-- ----------------------------
INSERT INTO `mybb_posts` VALUES (7, 6, 0, 2, 'Embed Imgur Album Enabled', 0, 1, 'jodilljames.esteban', 1558864524, 'Imgur Album Embed Test\r\n\r\n[imgur]a/b04h89n[/imgur]\r\n\r\nThe quick brown fox jumps over the lazy dog. :D', 0xA29E76CA, 0, 0, 0, 0, '', 1);
INSERT INTO `mybb_posts` VALUES (10, 9, 0, 2, 'Video Embed Test', 0, 1, 'jodilljames.esteban', 1558960466, '[video=youtube]https://www.youtube.com/watch?v=in-2VHDv44Q[/video]', 0xA29E7612, 0, 0, 0, 0, '', 1);
INSERT INTO `mybb_posts` VALUES (11, 10, 0, 2, 'WELCOME MESSAGE FOR SCHOOL YEAR 2019-2020!', 0, 5, 'hermes.vargas', 1559018673, 'The school year 2019-2020 has just started. New friends, new classmates, new teachers, new challenges and new learnings are bound to happen. The journey to success will never easy, as the saying goes, \"the journey of a thousand miles begins with a single step!\" In order to succeed this school year, bear these three (3) important reminders. First, have an open mind to learning. As a student, you learn  knowledge, acquire skills and develop values. Let your mind accept these positivities to make you better. Second, have a loving heart. Respect emanates from love. Let your love for God, country, environment and fellow men overflow in each day. There is no room for chaos in our school And third, have a disciplined soul. Your intelligence is futile without discipline. A disciplined learner will go beyond the borders of success. As I end let me tell you this quote from Eleanor D. Roosevelt, \"the future belongs to those who believe in the beauty of their dreams!\"\r\n\r\n[b]HERMES PACATANG VARGAS, LPT[/b]\r\nPrincipal II', 0xA29E7711, 0, 0, 0, 0, '', 1);
INSERT INTO `mybb_posts` VALUES (6, 5, 0, 7, 'Hello World', 0, 0, 'TheRandomPoster', 1558861460, 'I just wanted you to know that this post is moderated...\r\n\r\nHello Folks!!! :cool:', 0xA29E7604, 0, 0, 0, 0, '', 1);
INSERT INTO `mybb_posts` VALUES (8, 7, 0, 17, 'Forum Membership', 11, 1, 'jodilljames.esteban', 1558869862, '[b][color=#3333ff]Welcome to Claro M. Recto ICT High School Forum Board![/color][/b]\r\n\r\nThis is board is exclusive only for the Faculty, School Club Officers and selected personnel. \r\n\r\nTo request membership access please seek for CMRICTHS ICT Devs: \r\n\r\n[list]\r\n[*][b]Randy A. Rosales[/b]\r\n[*][b]Jun S. Tibay[/b]\r\n[*][b]Maria Mia Soriano[/b]\r\n[*][b]Jodill James A. Esteban[/b]\r\n[/list]\r\n\r\nNon members can still participate and post message threads in our Public Forum ([url=https://www.cmricths.com/board/forumdisplay.php?fid=7]Click Here[/url]). \r\n\r\nThanks.', 0xA29E761E, 0, 0, 0, 0, '', 1);

SET FOREIGN_KEY_CHECKS = 1;

我想为每个线程获取正确的作者。因此,如果线程ID为9,我应该以jodilljames.esteban作为作者;如果线程ID为10,我应该以hermes.vargas作为作者,依此类推...

1 个答案:

答案 0 :(得分:0)

如果您从queries/postedby.php脚本中提取了一些代码并将其放在代码的开头,请在开始任何循环之前创建prepared statement,然后可能会发现类似以下方法的方法

那让我感到惊讶,PHPBB不允许编辑RSS到您可以选择添加到提要中的程度……也许可以-也许不能-自从我看过已经有好几年了该软件。

祝你好运,希望能有所帮助

<?php
    /*
        Create the db connection and build your prepared statement

    */
    require_once 'config.php';
    $mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    $stmt = $mysqli->prepare( "SELECT `username` FROM `mybb_posts` WHERE `tid` = ?" );


    if( $stmt ){
        /*
            If the statement was constructed OK then bind a variable to
            the placeholder in the sql statement. This variable will be
            deduced later...
        */
        $stmt->bind_param("i", $tid );




        $rss = new DOMDocument();
        $rss->load('https://www.cmricths.com/board/syndication.php?fid=2');
        $feed = array();

        foreach ($rss->getElementsByTagName('item') as $node) {
            $item = array ( 
                'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
                'desc' => $node->getElementsByTagName('encoded')->item(0)->nodeValue,
                'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
                'date' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue,
            );
            array_push($feed, $item);
        }

        //Setting Feed Limits
        $fid = 2;
        $limit = 5;




        /*
            It is unknown what is in this file - if it contains
            a db connection then I'd suggest editing it to 
            remove the db connection as one already exists in
            this page/script....
        */
        require_once 'queries/threadcount.php';

        if ($tcount > $limit) {
            $tlimit = $limit;
        } else {
            $tlimit = $tcount;
        }

        //Posting the feed
        for($x=0;$x<$tlimit;$x++) {

            $title = str_replace(' & ', ' &amp; ', $feed[$x]['title']);
            $link = $feed[$x]['link'];
            $description = $feed[$x]['desc'];
            $date = date('l F d, Y', strtotime($feed[$x]['date']));

            //getting thread id from the link
            $arr = explode('=', $link);
            $tid = $arr[1];



            /*

                query db &
                fetch result

            */
            $stmt->execute();
            $result = $stmt->get_result();
            $row = $result->fetch_array();
            $author = $row['username'];
            $stmt->free_result();



            //post summary
            echo '<h2 class="blog-post-title">'.$title.'</h2>';
            echo '<p class="blog-post-meta">'.$date.' <em>by: '.$author.' '.$tid.'</em></p>';
            echo '<p class="mb-0">'.$description.'</p>';
            echo '<hr />';

        }
    } else {
        exit( 'error' );
    }


    $stmt->close();
    $mysqli->close();
?>