0

I'm trying to pull data from 1 column of a db and making it into a link where the URL is being pulled from another column. Unfortunately, I have not been able to do this. I've attached the screenshot of the output here's the code I'm using:

$sql = "SELECT DISTINCT item_title, item_url, item_date, item_author FROM nbth";
 $result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<a>" . $row["item_title"]. " url: " . $row["item_url"]. " <br> - By " . $row["item_author"] . " " . $row["item_date"]. "<br><br></a>" ;
    $HTML .= "<a href=".$row['item_url'].">".$row['item_title']."</a>";
    echo $HTML;
}
} else {
echo "0 results";
}

Screenshot of the results: [![enter image description here][1]][1]

The titles do become links but the get looped again and again, the first title in the first line, then next the first title and second, then the first, second and third, so on and so forth. So, how do I fix this looping and still display the titles as links.

2 Answers2

0
$HTML .= "<a href=".$row['item_url'].">".$row['item_title']."</a>";

Remove the period (string concat) operator before the equal sign:

$HTML = "<a href=".$row['item_url'].">".$row['item_title']."</a>";

It causes each iteration of the loop to concat the "<a href=".$row['item_url'].">".$row['item_title']."</a>"; part every time to the $HTML variable.

Also, pls enclose the href attribute's value by quotation marks(").

Shadow
  • 33,525
  • 10
  • 51
  • 64
0

echo $html outside the loop

or

while($row = $result->fetch_assoc()) {
$HTML ='';
echo "<a>" . $row["item_title"]. " url: " . $row["item_url"]. " <br> - By " . $row["item_author"] . " " . $row["item_date"]. "<br><br></a>" ;
$HTML = "<a href=".$row['item_url'].">".$row['item_title']."</a>";
echo $HTML;
}
} else {
echo "0 results";
}
Rogin Thomas
  • 672
  • 8
  • 17