PHP: link to external site inside an if statement

143 Views Asked by At

I'm totally new to PHP, so I apologize if this seems pretty simple. I've gotten so much help on other problems from reading through this site and I've tried so many different examples of trying to solve this, but couldn't work this out yet.

I have a site that some users will include a link to their personal blog (external site) while others will not. I've set up a field in the mySQL table labeled blog. The data inside the field is a full URL to include the http://.

I want to display a message like: Visit my blog here. With the here being a link to the users blog site.

I have the following code

<?php
if (!isset ($blog)) 
{
?>
    Visit my blog <a href="<?=$data['blog'];?>" target="_blank">here</a>
<?php
}
?>

The link works correctly, however, if the data field is empty, it still displays and the link is to the same page the code is on.

I've tried this code:

<?php
if (!isset ($blog)) 
{
    echo "Visit my blog <a href=\" . $blog .\" target=\"_blank\">here</a>." ;
}
?>

This displays the echo whether or not the field is blank AND the link is not pulling the data from the table.

I'm really at a loss as to what I'm doing wrong.

3

There are 3 best solutions below

0
On

isset() checks if the variable exists at all and ignores the value in the variable, e.g.

<?php

var_dump(isset($foo)); // false, $foo was never created
$foo = null;
var_dump(isset($foo)); // true - $foo exists, even though it's been nulled

so if your $blog EVER had a value assigned to it, it'll isset() as true. You probably want

if ($blog != '')

instead.

0
On

Try this

<?php
    if ($blog != "") {
        echo 'Visit my blog <a href="'.$blog.'" target="_blank">here</a>';
    }
?>
1
On

You need to add a condition in your if statement to see if there is anything in $data['blog'], otherwise the link will always load no matter what is in $data['blog']

For instance something like:

if((!isset($blog)) && ($data['blog'] !== ''))

Obviously, testing for '' might not work for you, so you might have to tweak the test to something like ' ', null or some such.