无法将数据加载到php中select标签的值

时间:2015-12-13 17:58:53

标签: php

我正在尝试从数组中的select标记中获取值。foreach数据来自数组,但它不起作用。如何正常工作。

index.php

<?php require 'app/config.php';?> <!-- connect database -->
<?php require 'app/result.php'; ?>
<?php require 'app/function.php'; ?>
<!DOCTYPE html>

<html>
    <head>
        <meta charset="UTF-8">
    <head>
<body>
     <form action="" method="post">

                Khối thi:               
                    <?php $values = &OptionValues(); ?>       
                        <select class="select">
                           <?php foreach($values as $value):?>                 
                               <option value="<?php $value['khoi_thi']; ?>"></option>

                          <?php endforeach;?>
                        </select> 
                   <br/>     

    </form>
</body>
</html>

function.php

<?php
require 'config.php'; <!-- connect database -->


function &OptionValues() {
    $fn = array();
    $sql=mysql_query("SELECT khoi_thi FROM `2014_khoathi` ");
    $i = 0;
    while ($data = mysql_fetch_array($sql)) {
        $fn[$i++] = array($data);

    }
    return $fn; <!-- return an array -->
}

?>

得到我想要的东西:

<select>
   <option value="A1"></option>
   <option value="A2"></option>
   <option value="A3"></option>
   <!-- 3 results if database has 3 rows -->
</select>

1 个答案:

答案 0 :(得分:0)

您应该知道您正在使用的驱动程序已被弃用:

http://php.net/manual/en/function.mysql-db-query.php

我将使用mysqli驱动程序(实际驱动程序)以这种简单的方式完成它:

<?php
    // inside config.php
    $mysqli=new mysqli("localhost", "root","password_here","whatever_db");
    if (mysqli_connect_errno()) {
        echo 'Database Conection Failed: ', mysqli_connect_error();
        exit;
    }
    // end config.php
    $sql = "SELECT khoi_thi FROM 2014_khoathi";
    $query = $mysqli->query($sql);
?>

<select class = "select">
   <?php 
      while($row = $query->fetch_assoc()) {
         echo "<option value = '{$row['khoi_thi']}'> {$row['khoi_thi']} </option>";
      }
   ?>
</select>

以下是不推荐使用的mysql驱动程序:

<?php
    // inside config.php
    $mysql=mysql_connect('localhost', 'user_mysql', 'password_mysql');
    if (!$mysql) {
        echo 'Database Conection Failed: ';
        exit;
    }
    // end config.php
    $sql = "SELECT khoi_thi FROM 2014_khoathi";
    $query = mysql_query($sql, $mysql);
?>
<select class = "select">
  <?php 

        while($row = mysql_fetch_assoc($query)) {
             echo "<option value = '{$row['khoi_thi']}'> {$row['khoi_thi']} </option>";
        }
  ?>
</select>