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 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单