使用PHP在现有div中显示MySQL值

时间:2014-05-20 02:33:10

标签: php mysql

希望显示第一条记录的“post”字段中的值,该字段使用PHP存储在MySQL数据库中。以下div是要插入值的位置:

<div id="insert1"><?php echo($r); ?></div>

PHP(使用MeekroDB注意):

<?php
require_once 'meekrodb.2.2.class.php';
DB::$user = 'username';
DB::$password = 'password';
DB::$dbName = 'database';
DB::$host = 'hostname';
// get all entries from database table Microblog;
$results = DB::query("SELECT post FROM MicroBlog");
foreach ($results as $row) {
  $id = $row['id'];
  // loop through each entry - there's 3
  for($i = 0; $i < 3; $i++) {
    // if it's the 1st entry (id = 1) then get field 'post'
    if ($id == 1) {
      $r = $row['post'];
    }
  }
}
?>

目前#insert1为空。我需要更改什么才能进入div?请注意,我想保持for循环,因为我将在运行后添加其他if。感谢。

1 个答案:

答案 0 :(得分:1)

可能这部分错了:

// get all entries from database table Microblog;
$results = DB::query("SELECT post FROM MicroBlog");

应该是:

// get all entries from database table Microblog;
$results = DB::query("SELECT * FROM MicroBlog");

您认为自己没有从查询中获取ID。

$id = $row['id'];

其他选项:

注释掉$ id。

 //$id = $row['id'];

并在下面的if块中,将$ id更改为$ i:

if ($i == 1) {
      $r = $row['post'];
    }

添加记录数:

 $x = 0;
    foreach ($results as $row) {
      $x++;
      $id = $row['id'];
      // loop through each entry - there's 3
      for($i = 0; $i < 3; $i++) {
        // if it's the 1st entry (id = 1) then get field 'post'
        if ($id == 1) {
          $r = $row['post'];
        }
      }
    }
echo $x;