简体   繁体   English

如何在HTML块内的转义PHP代码中回显MySQLi行

[英]How to echo a MySQLi row in escaped PHP code, inside an HTML block

I'm wondering what is the appropriate syntax is to echo a row from MySQLi code in a block of HTML text. 我想知道什么是合适的语法,以便在HTML文本块中从MySQLi代码回显一行。 I'm working on a page that uses PHP code at the start to determine if a session is started and to post comments that user has posted, after pulling said comments from a MySQLi database. 我正在研究一个页面,该页面从一开始就使用PHP代码来确定会话是否已启动,并在从MySQLi数据库中提取用户评论后发布用户已发布的评论。 The interesting and confusing part is, I've accomplished what I'm trying to do in one HTML div, but I can't seem to get it to work in the next. 有趣且令人困惑的部分是,我已经完成了我试图在一个HTML div中进行的操作,但是我似乎无法使其在下一个HTML中工作。

    <?php
    $page_title = "store";
    require_once('connectvars.php');
    require_once('startsession.php');
    require_once('header.php');

    // Connect to the DB
    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

    // Grab location data from the DB
    // Grab post data
    $query2 = "SELECT sp.post_id, sp.admin_id, sp.post, sp.date, sa.admin_id, s.store_name, s.store_city, s.store_state, s.store_zip,s.store_phone, s.store_email, s.store_address FROM store_posts sp, store_admin sa, stores s WHERE sp.admin_id='$admin_id' and sa.admin_id='$admin_id' and s.admin_id='$admin_id'ORDER BY date DESC";
    $data = mysqli_query($dbc, $query2);
    if (mysqli_num_rows($data) == 0) {
        $blankwall = "Empty feed? '<a href=manage.php><u>Click here</u></a> to manage posts and communicate with your customers!";
    }
?>
<body>
<div id="content">
<!-- BANNER & CONTENT-->
    <h2>Recent Posts</h2>
  <div id="store_wrap">
        <div id="left_col">
        <br />
        <?php
            **// Loop through posts and show them
            if (mysqli_num_rows($data) == 0) {
                echo $blankwall;
            }
                else {
            while ($row = mysqli_fetch_array($data)) {
                // Show the posts
                echo '' . $row['post'] . ' | ';
                echo date('M j, Y g:i A', strtotime($row['date']));
                echo '<br /><hr />';
            }**
            }
        ?>
        </div><!-- closes left_col -->

So all the above code is there to query the DB to grab the correct array and then show $row['posts'] in the HTML div below the PHP code, titled left_col. 因此,以上所有代码都可以查询数据库以获取正确的数组,然后在PHP代码下方名为left_col的HTML div中显示$ row ['posts']。 I am trying to do the exact same thing in the next div but instead of echoing $row['posts'], I want to echo rows such as $row['store_city'] to have the page display the store's location after pulling it out of the previously selected array. 我正在尝试在下一个div中执行完全相同的操作,但我不想回显$ row ['posts'],而是回显了诸如$ row ['store_city']之类的行,以使页面在拉出后显示商店的位置从先前选择的数组中删除。 Here's my non-functioning code for that part: 这是我那部分无效的代码:

<div id="right_col">
            <div id="store_picture">
          <img src="images/store.jpg" style="width:325px;"/>
            </div><!-- closes picture --><br />
            <div id="store_address">
                <br /><br /><h2>Location Info</h2>
                <?php
                if (mysqli_num_rows($data) == 1) {
                    while ($row = mysqli_fetch_array($data)) {
                    echo '<p>' . $row['store_city']. '</p>';
                    }
            }
                mysqli_close($dbc);
                ?>

            </div><!-- closes store_address -->
            <div id="store_info">
                <p></p>
            </div><!-- closes store_info -->
        </div><!-- closes right_col -->
        <div class="clear"></div>
    </div><!-- closes store_wrap -->
</div><!-- closes content -->

For whatever reason, the second time, when I try to echo data from that array, I just have empty space within that div. 无论出于何种原因,当我第二次尝试从该数组中回显数据时,该div中都只有空白。 I don't get any errors. 我没有任何错误。 I just don't get...anything. 我什么都没得到。 Therefore, I think this is a syntax issue. 因此,我认为这是一个语法问题。 I've tried exactly the same thing I did with the section where I echo $row['post'] and it isn't working. 我已经尝试过在与我回显$ row ['post']的部分进行相同的操作,但是它不起作用。

The chief issue you're facing is that you make a second attempt at fetching rows from the $data MySQLi result resource object after already having fetched them once. 您面临的主要问题是您已经尝试了一次从$data MySQLi结果资源对象中获取行,然后再进行尝试。 This won't work as intended, as MySQL keeps an internal recordset pointer which advances every time mysqli_fetch_array() is called. 这将无法按预期工作,因为MySQL会保留一个内部记录集指针,该指针在每次调用mysqli_fetch_array()mysqli_fetch_array()前进。 So when the end of the first loop is reached, the pointer is at the end of the recordset and a subsequent call will return FALSE . 因此,当到达第一个循环的末尾时,指针位于记录集的末尾,随后的调用将返回FALSE

Therefore, your second loop gets nowhere because its first call to mysqli_fetch_array() returns FALSE , exiting the loop. 因此,您的第二个循环mysqli_fetch_array()因为它对mysqli_fetch_array()第一次调用返回FALSE ,退出循环。 You have two options. 您有两个选择。

The quickest fix is to just rewind the record pointer using mysqli_data_seek() . 最快的解决方法是使用mysqli_data_seek()倒回记录指针。 Called right before the second loop, it will set the pointer back to the first record, allowing you to fetch them all again. 第二个循环之前调用,它将把指针设置回第一条记录,使您可以再次获取它们。

if (mysqli_num_rows($data) == 1) {
  // Rewind the record pointer back to the first record
  mysqli_data_seek($data, 0);

  while ($row = mysqli_fetch_array($data)) {
    // note addition of htmlspecialchars() to escape the string for HTML!
    echo '<p>' .htmlspecialchars($row['store_city']). '</p>';
  }
}

Perhaps a better option if your recordset is small is to fetch all rows into an array once, then use that array with a foreach loop for both your subsequent output loops: 如果您的记录集很小,那么更好的选择是将所有行一次提取到一个数组中,然后将该数组与foreach循环一起用于随后的两个输出循环:

// To hold all rows
$rows = array();
// Do the query
$data = mysqli_query($dbc, $query2);
// (don't forget to check for errors)
if ($data) {
  while ($row = mysqli_fetch_array($data)) {
    // Append the row onto the $rows array
    $rows[] = $row;
  }
}
else{
  // handle the error somehow...
}

Later, instead of using $data again, you will loop over $rows with a foreach loop. 稍后,您将不再使用$data ,而是通过foreach循环foreach $rows

// use count($rows)
if (count($rows) == 0) {
  echo $blankwall;
}
else {
  foreach ($rows as $row) {
    // Show the posts
    echo '' . $row['post'] . ' | ';
    echo date('M j, Y g:i A', strtotime($row['date']));
    echo '<br /><hr />';
  }
}

...And do the same thing again for your second loop later in the code. ...然后在代码的第二个循环中再次执行相同的操作。 It's recommended to use htmlspecialchars() on the string fields output from the query where appropriate. 建议在适当的地方对查询输出的字符串字段使用htmlspecialchars()

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

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