Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if value exists In MySQL row

I have a php variable: $foo

My MySQL table called data has the following structure:

id    var    header

1     zj3     http://google.com

I would like to check if $foo is all ready in var row.

If it is I would like to echo header ("http://google.com")

How would you approach this?

Thanks in advance, please ask if any clarification is needed!

like image 568
Trufa Avatar asked Jan 27 '11 20:01

Trufa


Video Answer


3 Answers

Your query should be:

SELECT `header` FROM `data` WHERE `var` = '$foo'

This will return all the headers with a var value of $foo.

$db = mysqli_connect('localhost', 'username', 'password', 'database');
if($query = mysqli_query($db, "SELECT `header` FROM `data` WHERE `var` = '$foo'")){
  while($row = mysqli_fetch_assoc($query)){
    echo $row['header'];
  }
  mysqli_free_result($query);
}
like image 178
Rocket Hazmat Avatar answered Oct 22 '22 19:10

Rocket Hazmat


first connect to the db

$query = mysql_query("SELECT var, header FROM data WHERE id='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($query)){
    if($foo == $row['var']){
        echo $row['header'];
    }
}

EDIT: changed equality statement based on your edit

like image 32
heymrcarter Avatar answered Oct 22 '22 18:10

heymrcarter


It's not difficult at all, If I understand correctly then this should help you.

// Query Variable / Contains you database query information
$results = $query;

// Loop through like so if the results are returned as an array
foreach($results as $result)
{
    if(!$result['var'])
        echo $result['header'];
}

// Loop through like so if the results are returned as an object
foreach($results as $result)
{
    if(!$result->var)
        echo $result->header;
}
like image 1
brenjt Avatar answered Oct 22 '22 19:10

brenjt