Michael
Michael

Reputation: 183

How to exclude data if value is set to 0?

I am trying to parse some data from MySQL database, i have a column calls is_approved and the value is either 0 or 1 (0 for no, 1 for yes)

I only want everything that is approved to be echoed

How i can i do this?

<?php
// Connect to MySQL
$link = mysql_connect( 'localhost', 'username', 'password' );
if ( !$link ) {
  die( 'Could not connect: ' . mysql_error() );
}

// Select the data base
$db = mysql_select_db( 'DATABASE', $link );
if ( !$db ) {
  die ( 'Error selecting database \'DATABASE\' : ' . mysql_error() );
}

// Fetch the data
$query = "
  SELECT *
  FROM prayer
  ORDER BY created_at DESC";
$result = mysql_query( $query );

// All good?
if ( !$result ) {
  // Nope
  $message  = 'Invalid query: ' . mysql_error() . "\n";
  $message .= 'Whole query: ' . $query;
  die( $message );
}

// Print out rows
while ( $row = mysql_fetch_assoc( $result ) ) {
  //echo json_encode($row);
  echo 'Name: '.$row['first_name'] . ' ' . $row['last_name'] . ' <br>Gypsy Name: ' .$row['gypsy_name'].'<br>Veetsa: ' .$row['veetsa'].'<br> Location: ' .$row['location'].'<br>' .$row['created_at'].'<br>' .$row['content'] . "<hr>";
}

// Close the connection
mysql_close($link);
?>

The plan is to spit out the JSON so i can use it on another server

Upvotes: 0

Views: 67

Answers (2)

Giacomo1968
Giacomo1968

Reputation: 26066

You could do this in the MySQL query, but you could also filter the data via the PHP logic using if ($row['is_approved'] == 1) { like this:

// Print out rows
while ( $row = mysql_fetch_assoc( $result ) ) {
  if ($row['is_approved'] == 1) {
    echo 'Name: '.$row['first_name'] . ' ' . $row['last_name'] . ' <br>Gypsy Name: ' .$row['gypsy_name'].'<br>Veetsa: ' .$row['veetsa'].'<br> Location: ' .$row['location'].'<br>' .$row['created_at'].'<br>' .$row['content'] . "<hr>";
  }
}

It’s not clear what the larger goal of your code is, but the benefit of doing it this way is perhaps you can toggle quickly between is_approved states or set some kind of sorting logic to deal with is_approved.

Otherwise, the MySQL query is really more efficient & clean.

Upvotes: 1

John Conde
John Conde

Reputation: 219804

Just add a WHERE clause to your query:

SELECT *
  FROM prayer
  WHERE is_approved = 1
  ORDER BY created_at DESC

Upvotes: 2

Related Questions