如果变量等于值PHP

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代表狗。
感谢任何能够帮助发现脚本问题的人!

2
你需要学习赋值 =,相等 == 和恒等 === 运算符之间的区别。 - samayo
使用数组代替 if - hakre
4个回答

20

你正在进行比较,而不是赋值:

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

您可以使用=====来比较值。

您可以使用=来赋值。

您也可以使用switch语句或一堆带有if但不带elseif的语句来写更少的代码,从而实现相同的结果。

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']);

3

你使用了 == 而不是 =。它会将变量与新值进行比较。使用 = 来设置值。

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

2

您正在使用 == 来赋值:

$type == bear;

应该是:

$type = bear;


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 />";
?>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接