-1

I created a table in php but when I try to display it, I got an error.

   if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {

echo "
<table style=\"width:100%\">
<tr>
    <th>Firstname</th> 
    <th>Lastname</th> 
    <th>Salary</th>
  </tr>
  <tr>
    <td>$row[\"Fname\"]</td>//I got error here.
    <td>$row[\"Lname\"]</td> 
    <td>$row[\"Salary\"]</td>
  </tr>
  </table>";

    }

Error is syntax error. Since I am new in PHP, I couldn't find the error. Eclipse just shows me that there is an syntax error and it won't fix it. Anybody have an idea?

berkc
  • 525
  • 3
  • 9
  • 21

4 Answers4

1

Don't escape the strings for the array-access and wrap them in {} If you run php -l path/to/file.php from the command-line it will check the syntax for you and report any errors.

if (mysqli_num_rows($result) > 0) {
// output data of each row


echo "
    <table style=\"width:100%\">
    <tr>
    <th>Firstname</th> //I got error here.
    <th>Lastname</th>•
    <th>Salary</th>
    </tr>";
while($row = mysqli_fetch_assoc($result)) {
    echo "
        <tr>
        <td>{$row["Fname"]}</td>
        <td>{$row["Lname"]}</td>•
        <td>{$row["Salary"]}</td>
        </tr>";
}
echo "
    </table>";

}

kylehyde215
  • 1,216
  • 1
  • 11
  • 18
1

It's more a logical problem, you just have to repeat the table body:

   if (mysqli_num_rows($result) > 0) {
    // output data of each row


          echo "
<table style=\"width:100%\">
<tr>
    <th>Firstname</th> //I got error here.
    <th>Lastname</th> 
    <th>Salary</th>
  </tr>";
    while($row = mysqli_fetch_assoc($result)) {
        echo "
  <tr>
    <td>" . $row["Fname"] . "</td>
    <td>" . $row["Lname"] . "</td> 
    <td>" . $row["Salary"] . "</td>
  </tr>";
  }
echo "
  </table>";
}
skroczek
  • 2,289
  • 2
  • 16
  • 23
1

If you got error there, try to play with syntax, e.g.:

echo "
  <tr>
    <td>".$row["Fname"]."</td>
    <td>".$row["Lname"]."</td> 
    <td>".$row["Salary"]."</td>
  </tr>";

or even make echoes for each line. It will be easier to learn from the error statements.

Piotr Borek
  • 866
  • 1
  • 6
  • 6
1

It is usually a good idea to use syntactic sugar when mixing php and html as you are. Try this:

 <table style="width:100%">
     <tr>
        <th>Firstname</th> 
        <th>Lastname</th> 
        <th>Salary</th>
     </tr>
     <?php while($row = mysqli_fetch_assoc($result)): ?>
     <tr>
        <td><?php echo $row["Fname"]; ?></td>
        <td><?php echo $row["Lname"]; ?></td> 
        <td><?php echo $row["Salary"]; ?></td>
     </tr>
    <?php endwhile ?>
 </table>

It tends to make the code easier to read / understand.

Michael Doye
  • 8,063
  • 5
  • 40
  • 56