8

我正在尝试在数据插入 MySQL 查询之前进行检查。这是代码;

$userid = ($vbulletin->userinfo['userid']);
$sql3 = mysql_query("SELECT * FROM table WHERE ID='$_POST[hiddenID]'");

while ($row = mysql_fetch_array($sql3)){

$toon = $row['toonname'];
$laff = $row['tlaff'];
$type = $row['ttype'];

if ($type == 1){
$type == "Bear";
} elseif ($type == 2){
$type == "Cat";
} elseif ($type == 3){
$type == "Dog";
}            

}

但是,这是行不通的。基本上,每种类型的“表”中都有不同的值。1 表示熊,2 表示猫,3 表示狗。

感谢任何可以帮助查看我的脚本中的问题的人!

4

4 回答 4

19

您正在比较,而不是分配:

if ($type == 1){
  $type = "Bear"; 
}

您将值与==or进行比较===

您使用 分配值=

您也可以编写更少的代码来获得相同的结果,使用一个switch语句,或者只是一堆if没有 s 的elseifs。

if ($type == 1) $type = "Bear";
if ($type == 2) $type = "Cat";
if ($type == 3) $type = "Dog";

我会为它创建一个函数,如下所示:

function get_species($type) {
    switch ($type):
        case 1: return 'Bear';
        case 2: return 'Cat';
        case 3: return 'Dog';
       default: return 'Jeff Atwood';
    endswitch;
}

$type = get_species($row['ttype']);
于 2013-05-04T18:58:02.900 回答
3

您正在使用==而不是=. 它将变量与新值进行比较。用于=设置值。

if ($type == 1){
$type = "Bear";
} elseif ($type == 2){
$type = "Cat";
} elseif ($type == 3){
$type = "Dog";
}  
于 2013-05-04T18:58:08.890 回答
2

==用于分配值:

$type == bear;

应该:

$type = bear;

于 2013-05-04T18:59:41.990 回答
0
if ($type == 1) {$displayVar = "Bear";}

例子:

<form method="post" action="results.php">
How many horns does a unicorn have? <br />
<input type="text" name="inputField" id="inputField" /> <br />
<input type="submit" value="Submit" /> <br />
</form>

结果:

<?php 
$inputVar = $_POST["inputField"];
if ($inputVar == 1) {$answerVar = "correct";}
else $answerVar = "<strong>not correct</strong>";
?>
<?php 
echo "Your answer is " . $answerVar . "<br />";
?>
于 2014-07-01T12:12:05.247 回答