duandaodao6951 2014-04-26 16:25
浏览 80
已采纳

需要一个文本表单字段

I've been struggling to have a text form field required. So when some one doesn't fill his name he will receive an error like 'No title filled!'

I got this now but it doesn't work that well cause when I submit it insert into the db.

if(isset($_POST['submit'])) {
    $update = "UPDATE post SET `title`='$_POST[title]', `pic`='$_POST[pic]', `youtube`='$_POST[youtube]' WHERE id = $_POST[id]";
    $db->query($update) or die($db->error);

        if($_POST['title'] == "") {
            $error = "Title is required!";
        }
        if ($_POST['pic'] == "") {
            $error = "Picture is required!";
        }
        if(isset($error)){
            echo $error;
        } else {
        echo '<p>Your post has been updated!</p>';
        } 

 }
  • 写回答

2条回答 默认 最新

  • doushuzd3033 2014-04-26 16:31
    关注

    You need to stop your code from being executed if an error is found, not just echo the error. All your other code that submits the data to the database should ONLY be executed if there is no error. Try something like this:

    Edit: Upon seeing the update to your code, this is what you need to do:

    if(isset($_POST['submit'])) {
        if(!isset($_POST['title']) || trim($_POST['title']) == "") {
            $error = "Title is required!";
        }
        if (!isset($_POST['pic']) || trim($_POST['pic']) == "") {
            $error = "Picture is required!";
        }
        if(isset($error)){
            echo $error;
        } else {
            $update = "UPDATE post SET `title`='" . mysql_real_escape_string($_POST['title']) . "', `pic`='" . mysql_real_escape_string($_POST['pic']) ."', `youtube`='" . mysql_real_escape_string($_POST['youtube']) ."' WHERE id = " . mysql_real_escape_string($_POST['id']);
            $db->query($update) or die($db->error);
            echo '<p>Your post has been updated!</p>';
        } 
    }
    

    The problem is, your data was being submitted to the database no matter what happened after with the validation - by the time you checked for errors it was too late, as the SQL had already been executed. If you do it the way shown above, it will only submit if the $error variable is not set, which is what you want.

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

报告相同问题?

悬赏问题

  • ¥15 基于52单片机的酒精浓度检测系统加继电器和sim800
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等