duanqiang9212 2014-04-18 23:08
浏览 30
已采纳

表单字段,输入数据在发生错误时保留

How to make already typed data not disappeared when error occurs in PHP form.

Example : if I type name and address correctly but I made mistake with email and error occurs I want correct fields stay the same, how I do that?

 <div class="elements">
  <label for="name">Name :</label>
  <input type="text" id="name" name="name" size="50" value="<?php echo $name; ?>" />
</div>
<div class="elements">
  <label for="e-mail">E-mail :</label>
<input type="text" id="e-mail" name="e-mail" size="50"  value="<?php echo $email; ?>"/>
</div>
<div class="elements">
  <label for="Password">Password:</label>
  <input type="password" id="Password" name="Password" size="50" />
</div><input type="text" id="name" name="name" size="50"  " />

I tried echo that but when page is loaded for first time something like that is visible in form field
Notice: Undefined variable: name in C:\xampp\htdocs\MyOnlineStore\members\index.php on line 173

  • 写回答

2条回答 默认 最新

  • douyi7283 2014-04-18 23:33
    关注

    This is called sticky forms.

    You are getting the error string because your variable is empty, that's right. You could simply silence them by adding an at-sign in front of your variable, but that isn't the best practice. What you need to do is check if the value exists, and display if so, or display something else if not.

    I made a helper function that can check to see wether to display what has come in from $_POST or a default value. put in the input

    event name<br />
    <input type="text" 
           style="width:100%" 
           name="title" 
           value="<?=stickyRow($_POST,'title','')?>" />
    
    
    function stickyRow($array,$index,$default = ''){
    
        if(empty($array[$index]) || $array[$index] == ''){
            return $default;
        }else{
            return $array[$index];
        }
    
    }
    

    The $array is usually the returned $_POST, $_GET or $_RESULT array. The $index is the key that belongs in that input. If that is key populated, it shows it in the form, if not, it shows a default value.

    Hope this helps.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于用python写支付宝扫码付异步通知收不到的问题
  • ¥50 vue组件中无法正确接收并处理axios请求
  • ¥15 隐藏系统界面pdf的打印、下载按钮
  • ¥15 MATLAB联合adams仿真卡死如何解决(代码模型无问题)
  • ¥15 基于pso参数优化的LightGBM分类模型
  • ¥15 安装Paddleocr时报错无法解决
  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改