如何在php中创建循环数据库

时间:2015-03-02 05:44:17

标签: php mysql database loops

我已经获得了一个.php文件,我想编写一个for循环来循环数据库条目并为每个条目填充一个div。我是一个完整的PHP菜鸟,我在网上发现的每个循环似乎都不能使用我的代码。任何帮助我开始的帮助将不胜感激。

我连接数据库的php代码如下:

<?php
    require 'mysqliconnection.php';
    require 'top_bottom_functions.php';

    $id = $_GET['id'];
    $stmt_get_details = mysqli_prepare($connect, "SELECT name, nickname, birth_day, birth_place, age, division, fighter_record, stance, height, reach, directory, biography, flag, record FROM fighters_details WHERE id=?");
    if ($stmt_get_details) {
        mysqli_stmt_bind_param($stmt_get_details, "s", $id);
        mysqli_stmt_execute($stmt_get_details);
        mysqli_stmt_bind_result($stmt_get_details, $name, $nickname, $birth_day, $birth_place, $age, $division, $fighter_record, $distance, $height, $reach, $directory, $biography, $flag, $record);
}

    mysqli_stmt_fetch($stmt_get_details);

    $height = html_entity_decode($height);

    $reach = html_entity_decode($reach);

    mysqli_stmt_close($stmt_get_details);
?>

谢谢!

2 个答案:

答案 0 :(得分:2)

考虑这种面向对象(OOP)方法:

$mysqli = mysqli_connect('localhost', 'username', 'password', 'db_name');

$stmt = $mysqli->prepare("SELECT name, nickname, birth_day, birth_place, age, division, fighter_record, stance, height, reach, directory, biography, flag, record FROM fighters_details WHERE id=?");
if ($stmt) {
    $stmt->bind_param("s", $_GET['id']);
    $stmt->execute();
    $stmt->bind_result($name, $nickname, $birth_day, $birth_place, $age, $division, $fighter_record, $stance, $height, $reach, $directory, $biography, $flag, $record);

    while ($stmt->fetch()) {
        echo '<div>Name'.$name.', Nickname'.$nickname.', etc...</div>';
    }

    $stmt->close();
}

$mysqli->close();

答案 1 :(得分:0)

希望这有帮助。

while(mysqli_stmt_fetch($stmt_get_details))
{
  echo "<div> name:"$name."</div>";
  .
  .
  //so on for other columns
}