根据MYSQL数据创建数组以显示为带有准备好的语句的复选框值

问题描述 投票:0回答:1

我有一个包含用户名的MYSQL表。我想将其放入数组中,并以一系列复选框的形式呈现,供用户选择。

下面的代码适用于表中的第一个值,如果我创建一个数组(不从MYSQL表中提取),则它将显示所有值。我想念什么?

功能:

function checkbox2( $name, $id, $label, $array_name = array() ) {?>
  <div class="form-group">
    <p><?php echo $label; ?></p>
    <?php foreach ( $array_name as $value => $title ) : ?>
      <label class="checkbox-inline" for="<?php echo $id; ?>">
        <input type="checkbox" name="<?php echo $name; ?>[]" value="<?php echo $title; ?>" <?php isset($_SESSION[$name]) ? checked($title, $_SESSION[$name]) : ''; ?>>
        <span class="checkbox-title"><?php echo $title; ?></span>
      </label>
    <?php endforeach; ?>
  </div>

function array_name() {
  // Connect to database
  $conn = db_connect();

  // Prepare and bind
  $stmt = $conn->prepare("SELECT user_name FROM usernames");

  // Execute and bind result;
  $stmt->execute();
  $response = $stmt->get_result();
  $array_name = $response->fetch_array(MYSQLI_ASSOC);

  return $array_name;
}

index.php

        <form action="pageprocessresults.php" method="post">
          <?php
          checkbox2( 'user_name', 'user_name', 'Select name', $array_name );
          ?>
          <?php
          submit('Go To Step 2 &raquo;');
          ?>
php mysql arrays prepared-statement
1个回答
0
投票

根据您的评论,仅当您未循环访问数据库结果时,才从数据库中获取返回的第一项。

尝试如下执行pdo

function array_name(){
  $conn = new PDO('mysql:host='.$yourhost.';dbname='.$yourdb.'', $dbuser, $dbpass);
  $stmt = $conn->prepare("SELECT user_name FROM usernames");
  $stmt->execute();
  while($res = $stmt->fetch(PDO::FETCH_ASSOC)){
    $response[] = $res;
  }
  return $response
}
© www.soinside.com 2019 - 2024. All rights reserved.