2016-11-12 50 views
1

所以有很多人帮助在html中创建一个下拉列表并用它们的数据库填充它。我试图做到这一点,我发现一些PHP代码来做到这一点,但它不工作。我理解php,sql和html,但不是它们如何组合在一起。什么似乎是问题是,第一个回声后,其余的代码只是作为代码输出到页面,它什么都不做。这是代码:创建一个下拉列表,但PHP不会工作

<html> 
    <body> 
     <?php 
     mysql_connect('localhost', 'root', 'password'); 
     mysql_select_db('FoodMatching'); 

     $sql = "SELECT IngID, IngName FROM Ingredient Characteristics"; 
     $result = mysql_query($sql); 

     echo "<select name='Ingredient Name'>"; 
     while ($row = mysql_fetch_array($result)) { 
      echo "<option value='" . $row['IngName'] ."'>" . $row['IngName'] ."</option>"; 
} 
echo "</select>"; 
?> 
    </body> 
</html> 

而我看到的网页是:

"; while ($row = mysql_fetch_array($result)) { echo " 
" . $row['IngName'] ." 
"; } echo ""; ?> 

有没有错误/警告弹出,所以我不知道是什么问题。谢谢,如果你能帮助:)

+1

请勿使用不推荐使用的'mysql_ *'-functions。从PHP 5.5开始它们被弃用,并在PHP 7中完全删除。它们也不安全。改用MySQLi或PDO。 –

+0

我敢肯定,你的sql特别是你的表有什么问题:成分特征...尝试在你的mysql上运行并看到... – barudo

+0

表名,表单项名称和东西没有空格。 –

回答

0

如上所述,你应该看看使用PDO's谈到DB

如果你得到的名单之前,html是输出,那么你可以有更清洁和更容易理解代码

看看下面是有道理的,你可能需要做一些修改它的未经检验的。

对您的mySql有一些评论,请确保在运行查询时返回结果。

<?php 

define("DB_DSN", "mysql:host=localhost;dbname=foo"); 
define("DB_USERNAME", "root"); 
define("DB_PASSWORD", "password"); 

// define the empty array to be filled from db 
$aIngredeintCats = array(); 


// any other php tasks that dont needthe ingcats 


// store sql 
$sSQL = "SELECT IngID, IngName FROM IngredientCharacterisitics"; 

// create an instance of the connection 
$conn = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD); 

// prepare 
$st = $conn->prepare($sSQL); 

// if required securely bind any user input in the query 
// $st->bindValue(":IngID", $sIngName, PDO::PARAM_STR); 

// execute the connection 
$st->execute(); 

/* this will show if a result has been returned from the db. 
echo "<pre>"; 
var_dump($st->fetch()); 
echo "</pre>"; 
*/ 

// while myslq has rows loop over them and store 
while($row = $st->fetch()){ 

    // use the IngID from db as the array key 
    // also strip any tags from the output. other sanatisation should be done 
    $aIngredeintCats[$row['IngID']] = strip_tags($row['IngName']); 
} 


// any other php tasks if they need the list of cats 

?> 


<html> 
    <body> 
     <form method='post' action='/'> 
     <?php 
      // if there are results stored create the select and loop over 
      if(!empty($aIngredeintCats)){ 
       echo "<select name='IngredientName'>"; 
       echo "<option value='' default>default</option>" 
       foreach ($aIngredeintCats as $iIngID => $sIngName) { 
        echo "<option value='".$sIngName."' >".$sIngName."</option>"; 
       } 
       echo "</select>"; 
      }else{ 
       echo "<p>No results avaliable!</p>"; 
      } 
     ?> 

     </form> 
    </body> 
</html> 
+0

它看起来应该可以工作,但同样的事情仍在继续。在//准备行下面的“$ st = $ conn->”之后。其余的代码只是以文本形式打印到页面上。如果这有所作为,我在c9.io中写这个。我检查了元素,并在$ conn->之后的其余代码出现在标记之间。 – pmpman

+0

尝试在文本编辑器中创建文件并将ftp/fssh创建到服务器。可能是ide吗? – atoms

+0

等一下。我觉得我一直很愚蠢。它应该是一个.php文件,而不是.html – pmpman