Mysqli подготовил оператор, не извлекающий правильное значение в каждом посте цикла - PullRequest
0 голосов
/ 28 мая 2019

Я не могу получить правильное значение поля для каждого сообщения, используя идентификатор, полученный при удалении ссылки в RSS-канале.

MyBB RSS-канал не предоставляет значение автора в RSS-канале, поэтому я получаю вручнуюэто с помощью ссылки, найденной в ленте, который содержит идентификатор потока.Я думаю, что я успешно получаю правильный идентификатор потока по ссылке, потому что я могу отобразить правильный идентификатор потока в каждом сообщении.Из-за этого я использую ту же переменную для идентификатора потока при извлечении поля автора (имя пользователя) в моей базе данных.Я выбираю поле имени пользователя, но оно выглядит одинаково для всех сообщений, на самом деле это последнее имя пользователя, которое опубликовало.Я смог заставить это работать должным образом, выбирая правильного автора, но из-за некоторых сумасшедших вещей в жизни, и я действительно новичок в этой области, я не смог сделать резервную копию и забыл, как я это сделал.

Это код, который я использую для создания поста из фида:

            <?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;

Я предполагаю, что получаю правильного автора для каждой темы.Поэтому, если идентификатор потока равен 9, я должен получить jodilljames.esteban в качестве автора, а если идентификатор потока равен 10, я должен получить hermes.vargas в качестве автора и так далее ...

1 Ответ

0 голосов
/ 28 мая 2019

Если вы возьмете часть кода из сценария 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();
?>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...