0

I am having a problem with a little php showing script i wrote. I cant get the code to show in the Table. What am i doing wrong? Cant find the answer somewhere either...

Error code: Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

$con=mysqli_connect("localhost","database_connected","password");
// Check connection 
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM links");

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";

while($row = mysqli_fetch_array($result)) {
  echo "<tr>";
  echo "<td>" . $row['links'] . "</td>";
  echo "<td>" . $row['url'] . "</td>";
  echo "</tr>";
}

echo "</table>";

mysqli_close($con);
Stígandr
  • 2,793
  • 20
  • 36

1 Answers1

0

I would recommend moving away from mysqli and use PDO instead; in addition to having a more sensible model, it is quite a bit easier to use safely. Here's a quick example of how your code above might be rewritten as PDO code:

<?php
$db = new PDO('mysql:host=localhost;dbname=SOME_DB_NAME_HERE;charset=utf8', 'database_connected', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
try {
    $rows = $db->query('SELECT * FROM links');
} catch(PDOException $ex) {
    echo "An Error occured: ", $ex->getMessage(); //user friendly message
    exit();
}

foreach($rows as $row) {
    echo '<tr>';
    foreach($row as $column=>$value) { echo '<td>', $value, '</td>'; }
    echo '</tr>';
}

There's a fairly decent tutorial to help you learn to map mysql(i) constructs to their PDO equivalent at the HashPHP wiki.

TML
  • 12,394
  • 3
  • 36
  • 43