我试着用下面的代码做一个简单的切换函数。
$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> </td>";
echo "</tr>";
?>我的结果是打印出缺省值“该死!”我做错了什么,而不是期望的值“羊群改变”。如果行herd的值= 2,我想打印出单词"Herd Change“。
发布于 2017-12-13 13:34:25
这很可能是一个类型转换问题
试一试
$catch = string($row["herd"]);并确保$catch为2
发布于 2017-12-13 14:04:48
您的代码应按如下方式进行更改。
<?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> </td>";
$html += "</tr>";
}
echo $html;
//It will print multiple rows, If query returns multiple rows.
?>发布于 2017-12-13 13:41:57
如果您的变量$catch包含整数值,则使用以下语法。
switch($catch){
case 2:
// your code
default:
// your code
}如果是字符串值,请执行以下操作,
switch($catch){
case "2":
// your code
default:
// your code
}Switch case manual
手动对变量进行类型转换不是一种好的做法。
我希望它能有所帮助!
https://stackoverflow.com/questions/47786156
复制相似问题