cmit
cmit

Reputation: 261

get specific colunm from latest five record in the MySQL DB

I have following code.This code doesn't show any result. Please explain what is the issue?

<?php
require_once("connnection.php"); 

$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();

}

?>
<div style="position:absolute;top:200px;right:65px; padding:10px; background-color:#CCFFFF; width:300px; height:400px;">
<hr>
<p><strong>Latest posts</strong></p>
<hr style="position:relative; top:40px; left:30px; width:80%; ">
<?php
$sql = "SELECT question FROM comment ORDER BY id DESC LIMIT 5";
if ($result = mysqli_query($con, $sql)) {

    /* fetch associative array */
    while ($row = mysqli_fetch_row($result)) {
        printf("%s\n", $row[3]);
    }

    /* free result set */

}
?>

I want to get five latest questions from the db and display it.DB has five records. Table comment has 4 fields. "question" is the last field.

Upvotes: 2

Views: 43

Answers (3)

Aashu Spk
Aashu Spk

Reputation: 111

You can use echo $row['question'] is the column name for questions is "question" else find the column index starting from 0 and asign the value as $row[0] (example 0)

      while ($row = mysqli_fetch_row($result)) {
          echo $row['question']."<br>";
       }

it's recommended that you should use column name because, if in future you change the table structure, your code will not get affected by changes

Upvotes: 1

Ali
Ali

Reputation: 3461

while ($row = mysqli_fetch_row($result)) {
    printf("%s\n", $row[3]);
}

You're selecting only the questions field but somehow enumerating the third field. You have an option to use mysqli_fetch_assoc as the following to avoid any confusion in the future

while ($row = mysqli_fetch_assoc($result)) {
    printf("%s\n", $row['questions']);
}

Or you can use $row[0] instead of $row['3']

Upvotes: 1

hjpotter92
hjpotter92

Reputation: 80639

$row[3] is undefined. You need to use $row[0]

while ($row = mysqli_fetch_row($result)) {
    printf( "%s\n", $row[0] );
}

Alternatively:

while ($row = mysqli_fetch_assoc($result)) { // notice the use of `fetch_assoc`
    echo $row['question'] . "\n";
}

Upvotes: 2

Related Questions