切换功能输出默认值而不是期望值

时间:2017-12-13 05:31:40

标签: php mysql switch-statement

我尝试使用以下代码执行简单的切换功能。

$query = "SELECT * FROM entries where Venue='Condamine' and Year='2018' and 
Event='$5,000 Novice'  and herd='2' and scratched IN('n','l')  ORDER BY Draw 
ASC";
// Execute the query
$result = mysqli_query($con ,$query);
if (!$result){
    die ("Could not query the database: <br />". mysqli_error());
}
// Change herds
function getherd($catch) { 
    switch($catch) 
    { 
        case '2': 
            return 'Herd Change'; 
        break; 
        default: 
            return 'Damn!'; 
        break; 
    } 
} 
$catch = $row["herd"];
echo "<tr>";
echo "<td bgcolor=#FFFFFF><strong> ". getherd($catch) ." </strong></td>";
echo "<td bgcolor=#FFFFFF>&nbsp;</td>";
echo "</tr>";
?>

我的结果是打印出默认值&#34;该死的!&#34;而不是期望值&#34;牧群改变&#34;我究竟做错了什么。我想打印出&#34; Herd Change&#34;如果行herd的值= 2。

3 个答案:

答案 0 :(得分:3)

最有可能是一个类型转换问题

尝试

$catch = string($row["herd"]);并确保$ catch为2

答案 1 :(得分:1)

您的代码应更改如下。

<?php 
$query = "SELECT * FROM entries where Venue='Condamine' and Year='2018' and 
Event='$5,000 Novice'  and herd='2' and scratched IN('n','l')  ORDER BY Draw 
ASC";
// Execute the query
$result = mysqli_query($con ,$query);
if (!$result){
    die ("Could not query the database: <br />". mysqli_error());
}
// Change herds
function getherd($catch) { 
    switch($catch) 
    { 
        case '2': 
            return 'Herd Change'; 
        break;
        default: 
            return 'Damn!'; 
           //Break doesn't require in default case
    } 
}

//here you need to get results set from $result.
$html = "";
while ($row = mysqli_fetch_row($result)) {
     $catch = $row["herd"];

     $html += "<tr>";
     $html += "<td bgcolor=#FFFFFF><strong> ". getherd($catch) ." </strong></td>";
     $html += "<td bgcolor=#FFFFFF>&nbsp;</td>";
     $html += "</tr>";  
}
echo $html;
//It will print multiple rows, If query returns multiple rows.
?>

答案 2 :(得分:0)

如果您的变量$ catch包含整数值,请使用以下语法。

switch($catch){
  case 2:
     // your code
  default:
     // your code
}

如果是String值,请执行以下操作,

switch($catch){
  case "2":
     // your code
  default:
     // your code
}

Switch case manual

手动对变量进行类型转换是不好的做法。

我希望它有所帮助!