无法使用php回显从后端检索的选项值

时间:2014-05-23 18:33:35

标签: php mysql echo

我无法回显检索到的数据的价值

这是我的代码:

   <html>
   <?php
        mysql_connect("localhost", "root", "")or die("cannot connect"); 
        mysql_select_db($db_name)or die("cannot select DB");
        echo "<select class=\"chapter\">";
        echo "<option value=\"\">Select Chapter</option>" ?>
    //  $sql="select 'ChapterName' from 'chapter'";
        $sql = "SELECT `ChapterName` FROM `chapter`";
        if (!mysql_query($sql)) {
         die('Error: ' . mysql_error($connection));              
        }  
        $result=mysql_query($sql);     
        while($row=mysql_fetch_assoc($result)){
                $option=$row['ChapterName'];
                echo '<option value=\"\">$row[\'ChapterName\']</option>' ?>     
                echo "<script>alert(".$option.")</script>";
        }

              ?>
              </select><br/><br/><html>

它给出了以下输出::

   $row[\'ChapterName\']

在下拉菜单中.....

3 个答案:

答案 0 :(得分:0)

基本PHP:' - 引用的字符串 NOT 插入变量值:

$foo = 'bar';

echo '$foo'; // output: $, f, o, o
echo "$foo"; // output: b, a, r

所以:

echo '<option value=\"\">$row[\'ChapterName\']</option>' ?>     

应该是

echo "<option value=\"\">$row[ChapterName]</option>" ?>     
     ^---    note the change in quotes      -------^

答案 1 :(得分:0)

我认为这就是你所需要的:

<?php
    mysql_connect('localhost', 'root', '') or die('cannot connect'); 
    mysql_select_db($db_name) or die('cannot select DB');
?>

    <select class="chapter">
    <option value="">Select Chapter</option>
<?php
    $sql = 'SELECT `ChapterName` FROM `chapter`';
    $sql = mysql_query($sql); //added this

    if (!mysql_query($sql)) {
         die('Error: ' . mysql_error($connection));              
    }  

    $result = mysql_query($sql);
    while($row = mysql_fetch_assoc($result)) {

        echo '<option value="">'.$row['ChapterName'].'</option>';
    }
?>
    </select>

如果您有任何错误,请告诉我,以便我可以解决它们

答案 2 :(得分:0)

请试试这个:

<html>
   <?php
        mysql_connect("localhost", "root", "")or die("cannot connect"); 
        mysql_select_db($db_name)or die("cannot select DB");
        echo "<select class=\"chapter\">";
        echo "<option value=\"\">Select Chapter</option>";
        $sql = "SELECT `ChapterName` FROM `chapter`";
        if (!mysql_query($sql)) {
         die('Error: ' . mysql_error($connection));              
        }  
        $result=mysql_query($sql);     
        while($row=mysql_fetch_assoc($result)){
            echo "<option value=''>".$row['ChapterName']."</option>";     
        }

    ?>
        </select><br/><br/>
<html>