我的div内容有些问题。我创建了一个网站,书籍必须从Mysql数据库加载到html div内容。我使用printf();
来加载数据来分割内容。但我不能在<span>
标签之间粘贴php变量。
<?php
require 'scripts/connect.php';
$sql_select = "SELECT * FROM users";
$result = mysql_query($sql_select);
$row = mysql_fetch_array($result);
do
{
printf(
'<ul>
<li>
<div class="product">
<a href="#" class="info">
<span class="holder">
<img src="css/images/image01.jpg" alt="" />
<span class="book-name">$row['b_name'] </span> //ERROR IN HERE
<span class="author">$row['a_name']</span> //AND HERE
<span class="description">Maecenas vehicula ante eu enim pharetra<br />scelerisque dignissim <br />sollicitudin nisi</span>
</span>
</a>
<a href="#" class="buy-btn">BUY NOW <span class="price"><span class="low">$</span>22<span class="high">00</span></span></a>
</div>
</li>
</ul>'
);
}
while($row = mysql_fetch_array($result));
?>
我怎么能这样做?感谢
答案 0 :(得分:3)
如果你问我,我会这样做,没有mysql_*
函数和分隔PHP和HTML 。您的问题是, '
引号不会扩展变量。
<?php
require 'scripts/connect.php';
$sql_select = "SELECT * FROM users";
$result = mysqli_query($conn, $sql_select);
if (mysqli_num_rows($result) > 0)
while (false != ($row = mysql_fetch_array($result))) { ?>
<ul>
<li>
<div class="product">
<a href="#" class="info">
<span class="holder">
<img src="css/images/image01.jpg" alt="" />
<span class="book-name"><?php echo $row['b_name']; ?></span>
<span class="author"><?php echo $row['a_name']; ?></span>
<span class="description">Maecenas vehicula ante eu enim pharetra<br />scelerisque dignissim <br />sollicitudin nisi</span>
</span>
</a>
<a href="#" class="buy-btn">BUY NOW <span class="price"><span class="low">$</span>22<span class="high">00</span></span></a>
</div>
</li>
</ul>
<?php } ?>
在上面的代码中,我假设$conn
是mysqli_connect
变量。
答案 1 :(得分:0)
问题在于您混合使用双引号和单引号。 PHP变量只能在双引号内输出。将所有现有的双引号更改为单引号,然后将<ul>
封装在双引号中:
"<ul>
<li>
<div class='product'>
<a href='#' class='info'>
<span class='holder'>
<img src='css/images/image01.jpg' alt='' />
<span class='book-name'>$row['b_name']</span>
<span class='author'>$row['a_name']</span>
<span class='description'>Maecenas vehicula ante eu enim pharetra<br />scelerisque dignissim <br />sollicitudin nisi</span>
</span>
</a>
<a href='#' class='buy-btn'>BUY NOW
<span class='price'>
<span class='low'>$</span>22
<span class='high'>00</span>
</span>
</a>
</div>
</li>
</ul>"
当然,您可以随时重构以简单地将内容输出为HTML,然后注入PHP变量:
<span><?php echo $row['b_name']; ?></span>
另请注意,{* 1}}调用在PHP 5.5中已弃用,而在PHP 7.0中已完全已删除,因此请考虑使用MySQLi或PDO:)
希望这有帮助!