doufeiqiong3515 2012-12-14 16:54
浏览 76
已采纳

我的IF语句正在改变PHP中的变量

I am fairly new to the whole programming thing, so forgive me if this is a stupid question. It seems odd that I haven't run into it before.

I am trying to make an order form for a cake. You fill out the form, submit it, and it will then display the order in a new window, where you then hit "submit," and upload it to the Database. I have a series of If Statements to check for errors in the form before submitting it. Here is a simplified version of the code. Writing means any writing you want on the cake, Name is your name, and cake is what type of cake you want (the default is "None").

try {
$name = trim($params->name);
$cake = trim($params->cake);
$writing = trim($params->writing);
if (strlen($name) < 3){
    throw new Exception("Please enter Your name.");
    }
if ($cake = "None") {
        throw new Exception("Please select a Cake"
     }
if ($cake = "Caramel Apple Pie" or $cake = "Pumpkin Pie" or $cake = "Eggnog Pie" and strlen($writing) > 1) {
    throw new Exception("We are sorry, but you can't write on any of our specialty pies.");
    }

} catch(Exception $x) {
    $error = $x->getmessage();
    }

So what is happening is that when I go and hit submit the first time, the correct cake type comes up, but when you submit it the second time, the error comes up saying that I have "None" selected. All the other values are there and remain the same. I think the problem is that the first "IF" statement (Where it says "If($cake = "None")) is automatically changing $cake to "None" because I have tried commenting just that statement out, and it will then change the cake to be "Caramel Apple Pie," which is in the top of the next IF statement.

Anyone know why it is doing this? And how to fix it?

  • 写回答

3条回答 默认 最新

  • dpno17028 2012-12-14 16:55
    关注

    You are using a = instead of a ==

    • = is an assignment operator, ie it changes our variable value. Using it inside an if-statement results in setting the variable and checking the result.
    • == is a comparison operation
    • === is also a comparison operator, it additionally checks whether the types are equal.

    See the PHP assignment operator and comparison operator manuals for more information

    Additional notes:

    • the line throw new Exception("Please select a Cake" is missing ); as well.
    • using exceptions to write a message in $error is a bit overkill in your example situation! For example, just use $error = "Please enter Your name.".
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?