0

Looking to display a value from the 1st record's 'post' field which is stored in a MySQL database using PHP.  The following div is where the value is to be inserted:

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

The PHP (Note using 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'];
    }
  }
}
?>

Currently #insert1 is blank.  What do I need to change to get it into the div? Please note, I want to keep the for loop, as I'll be adding other if's once I get it running. Thanks.

1
  • at least add the most basic of error checking Commented May 20, 2014 at 2:37

1 Answer 1

1

Probably this part is wrong:

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

should be:

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

You're getting id which i think you're not getting from your query.

$id = $row['id'];

Other option:

Comment out $id.

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

and in the if block below, change $id to $i:

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

To add number of records:

 $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;
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, that worked. If you don't mind me asking I have a couple of questions on limiting $results: How could I get the number of records in results? How to limit records to just those starting w/ number,A & B? How to limit to to 15 records w/ most recent date? (listed from most recent) Thanks
Use mysql_num_rows() function so $number_of_records = mysql_num_rows($result);
Can you help w/ my other questions?
Post a new one and let's see. If you are willing to study, study first and if you're lost, we are here.
Ok, for this post, lets just look at your suggestion: $number_of_records = mysql_num_rows($results); I put that after $results & substituted '3' in for line for $number_of_records, but now nothing in div.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.