1

I have a webpage which uses php to pull through data from a MySQL database. The database stores my writing portfolio organised by columns date, url, category, title, publication, description. It pulls through the title and publication and uses the url to turn it into a hyperlink (see code below). So far, so good.

Where I'm stuck: Sometimes there's no url for something I've published (e.g. for a few of the 'Content & Copywriting' items on my site), but it still turns my title and publication into a link: a link to "_blank". When there is a NULL url, I need it to not turn my title into a link at all.

So, I think I need to insert some sort of logic so that if url=NULL, then it doesn't make the text into a link, instead of creating a link to "_blank". But this is completely beyond my capabilities right now - I don't know where to even start !

I hope that all makes sense. Any guidance/pointers in the right direction welcome! And please let me know if anything's not clear.

        <?php

        $query = mysqli_query($dbconnect, "SELECT * FROM main WHERE category = 'Content & copywriting' ORDER BY date DESC")
            or die (mysqli_error($dbconnect));

        while ($row = mysqli_fetch_array($query)) {
            echo "<a href=$row[url] target='_blank'>$row[publication] - $row[title]</a><br>";
            echo "$row[description]<br><br>";
        }
        ?>
Dharman
  • 30,962
  • 25
  • 85
  • 135
mess1n
  • 53
  • 1
  • 8
  • `SELECT * FROM main WHERE category = 'Content & copywriting' and url <> '' ORDER BY date DESC` – Your Common Sense Dec 25 '20 at 11:23
  • It is a very bad idea to use `die(mysqli_error($$conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Dec 25 '20 at 22:52
  • @YourCommonSense thanks for the alternative solution - I'll try this one out too. – mess1n Dec 26 '20 at 12:11
  • @Dharman That's very helpful to know. I'll read up on it and update my site. Thanks! – mess1n Dec 26 '20 at 12:11

1 Answers1

0

try check for empty values

while ($row = mysqli_fetch_array($query)) {
    if( !empty( $row['url'])){
        echo "<a href=$row[url] target='_blank'>$row[publication] - $row[title]</a><br>";
    }
    echo "$row[description]<br><br>";
}
Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107