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条)

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图