无法获取Select2从我的mysql数据库中获取数据

时间:2019-02-18 15:24:09

标签: javascript php mysql jquery-select2

我一直在尝试几种不同的方法来让Select2使用MySQL数据库中的信息。当前,翻译似乎已经丢失了一些东西,它只是显示array(".$title")的字面名称。数据库称为vettigevrijdag,表名为article

要包含在导航栏中的我的PHP代码段:

<head>
    <link href="select2.css" rel="stylesheet"/>
    <script src="select2.js"></script>
    <script>
      $(document).ready(function() {
      $('.js-example-basic-single').select2();
      });
    </script>
    <select class="js-example-basic-single">
    <?php
      include('db.php');
      $stmt=$db_con->prepare("SELECT * FROM article");
      $stmt->execute();
      if($stmt->rowCount() > 0){
        while($row=$stmt->fetch(PDO::FETCH_ASSOC))
        {
          extract($row);
          $id = $row['if'];
          $title = $row['title'];
        echo '<option value="'.$id.'">'.$title.'</option>';
        }
      }
    ?>
    </select>
</head>

我的db.php文件:

<?php

$dbhost = "localhost"; /* Host name */
$dbname = "vettigevrijdag"; /* Database name */
$dbuser = "localhost"; /* User */
$dbpassword = "123456"; /* Password */


try {
    $db_con = new PDO("mysql:host={$dbhost};dbname={$dbname}",$dbuser,$dbpassword);
    $db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

} catch (PDOException $ex) {
    die($ex->getMessage());
    //throw $th;
}
?>

1 个答案:

答案 0 :(得分:0)

<select class="js-example-basic-single">
<?php
  include('db.php');
  $stmt=$db_con->query("SELECT * FROM article")->fetchall(PDO::FETCH_ASSOC));
  foreach($stmt as $key=>$row){

    echo "<option value=\"".$row['if']."\">".$row['title']."</option>";
  }

?>
</select>