无法使用while循环将mysql字段插入div

时间:2015-09-23 17:29:16

标签: php mysql

我正在一个网站上工作,我正在尝试连接到SQL数据库并在<div>内发布一个SQL字段。 <div>位于while循环内。 我想我已成功连接到数据库。但是,我无法在标头中显示 id 字段。我是PHP&amp;的新手SQL并不能解决它。以下是我的代码:

<?php

    $db_host = "localhost";
    $db_username = "user192";
    $db_pass = "xxxx";
    $db_name = "sound-library";

    @mysql_connect("$db_host","$db_username","$db_pass") or die ("couldnt connect to sql");
    @mysql_select_db ("$db_name") or die ("cant find database");

    $query = "select * from sound-library";
    $queryResult=mysql_query($query);
    $numrows=mysql_num_rows($queryResult);

?>

    while($row = mysql_fetch_assoc($queryResult)) {
        <div class="audio-module-parent">
            <div class="audio-module-header">
<?php
                <h1> <?php echo $row['id']?> </h1>
            </div>
            <div class="audio-module-preview"></div>
            <div class="audio-module-download">Download</div>
            <div class="audio-module-tutorial">Watch Tutorial</div>
        </div>
?>

2 个答案:

答案 0 :(得分:1)

您将代码置于<?php ?>之外,例如

?>
while($row = mysql_fetch_assoc($queryResult)) {

然后将HTML放在<?php ?>里面,例如

<?php
<h1> <?php echo $row['id']?> </h1>
</div>

应该是

<?php
error_reporting(E_ALL); //Enable Error Reporting
ini_set('display_errors',1); //change value to 0 to disable the error views
$db_host = "localhost";
$db_username = "user192";
$db_pass = "xxxx";
$db_name = "sound-library";
@mysql_connect("$db_host","$db_username","$db_pass") or die ("couldnt connect to sql");
@mysql_select_db ("$db_name") or die ("cant find database");
$query = "select * from sound-library";
$queryResult=mysql_query($query) or die(mysql_error());
$numrows=mysql_num_rows($queryResult);
while($row = mysql_fetch_assoc($queryResult)) {
?>
<div class="audio-module-parent">
    <div class="audio-module-header">
        <h1> <?php echo $row['id']?> </h1>
    </div>
    <div class="audio-module-preview"></div>
    <div class="audio-module-download">Download</div>
    <div class="audio-module-tutorial">Watch Tutorial</div>
</div>
<?php } ?>

答案 1 :(得分:1)

- <h1> <?echo $row['id'];?> </h1> missing semi colon  (;) here in this line.
- Missing } end of while loop

使用此连接。在“xxxx”部分写一个密码&amp;核实。评论你的mysql_connect&amp; mysql_select_db

$ con = mysql_connect(“localhost”,“user192”,“xxxx”)或死亡(“无法连接到sql”); $ db = mysql_select_db(“sound-library”,$ con)或die(“无法找到数据库”);

 <? 
    while($row = mysql_fetch_assoc($queryResult))
    {?>
    <div class="audio-module-parent">
        <div class="audio-module-header">
            <h1> <?echo $row['id'];?> </h1>
        </div>
        <div class="audio-module-preview">

        </div>
        <div class="audio-module-download">Download</div>
        <div class="audio-module-tutorial">Watch Tutorial</div>
    </div>
    <?}?>