How to stipulate details with a SELECT

Asked

Viewed 41 times

2

Well, I gave a SELECT, to pull my data, only I wanted to do the following: If $category is 1, it would be called World, and if $category equals 2, it would be called Moon, how can I do that?

Code:

    <?php
$conect = mysql_query("SELECT * FROM news ORDER BY ID DESC") or die(mysql_error());
?>

Pulling on the SELECT:

<?php echo $conect['categoria']; ?>

2 answers

2


Using the command if:

<?php 

if ($conect['categoria'] == 1){
  echo "Mundo";
}else if($conect['categoria'] == 2){
  echo "Lua";
}else{
  echo "Outros";
}; 

?>

Using the command case:

<?php 

switch ($conect['categoria']) {
  case 1:
    echo "Mundo"; break;
  case 2: 
    echo "Lua"; break;
  default:
    echo "Outros";
}

?>
  • That’s what I wanted, thank you, it worked perfectly.

1

First you make the consultation:

$connection = mysql_connect("localhost", "user", "pass");
$selectbase = mysql_select_db("base", $connection );
$slectdados = mysql_query("SELECT * FROM news ORDER BY ID DESC") or die(mysql_error());

while ($linha = mysql_fetch_array($slectdados){
     if( $linha['categoria'] == "Mundo" ){
          echo "Mundo<br>";
     } elseif ( $linha['categoria'] == "Lua" ){
          echo "Lua<br>";
     } else {
          echo "Outros<br>";
}

It may be that within a loop where selects all the results you can thus go printing line by line according to the value of each record but the question is very vague.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.