如果变量等于值 php
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16377823/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
If variable equals value php
提问by llw
I am trying to do a check before the data inserts into the MySQL query. Here is the code;
我正在尝试在数据插入 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";
}
}
However, this isn't working. Basically, there are different values in the 'table' for each type. 1 means Bear, 2 means Cat, and 3 means Dog.
但是,这不起作用。基本上,每种类型的“表”中有不同的值。1代表熊,2代表猫,3代表狗。
Thanks to whomever can help see a problem in my script!
感谢任何可以帮助查看我的脚本中的问题的人!
回答by Jezen Thomas
You are comparing, not assigning:
您是在比较,而不是分配:
if ($type == 1){
$type = "Bear";
}
You compare values with ==
or ===
.
您将值与==
或进行比较===
。
You assign values with =
.
您使用 分配值=
。
You could write less code to achieve the same result too, with a switch
statement, or just a bunch of if
s without the elseif
s.
您也可以编写更少的代码来实现相同的结果switch
,只需使用一条语句,或者只是一堆if
s 而没有elseif
s。
if ($type == 1) $type = "Bear";
if ($type == 2) $type = "Cat";
if ($type == 3) $type = "Dog";
I would make a function for it, like this:
我会为它做一个函数,像这样:
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']);
回答by PurkkaKoodari
You are using ==
instead of =
. It compares the variable to the new value. Use =
to set the value.
您正在使用==
而不是=
. 它将变量与新值进行比较。使用=
设定值。
if ($type == 1){
$type = "Bear";
} elseif ($type == 2){
$type = "Cat";
} elseif ($type == 3){
$type = "Dog";
}
回答by LeonardChallis
You're using ==
to assign values:
您正在使用==
分配值:
$type == bear;
$type == bear;
Should be:
应该:
$type = bear;
$type = bear;
回答by Porta Shqipe
if ($type == 1) {$displayVar = "Bear";}
Example:
例子:
<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>
Results:
结果:
<?php
$inputVar = $_POST["inputField"];
if ($inputVar == 1) {$answerVar = "correct";}
else $answerVar = "<strong>not correct</strong>";
?>
<?php
echo "Your answer is " . $answerVar . "<br />";
?>