You need to enable JavaScript to run this app. 如何复用单个textarea内容同步写入MySQL两个字段
优惠活动
大模型
产品
解决方案
定价
更多

如何复用单个textarea内容同步写入MySQL两个字段

核心调整方案
  • 完全移除原有独立的「文章描述」输入模块,不再单独采集postDesc字段的表单值
  • 删除PHP校验流程中针对postDesc的非空判断规则
  • 数据库写入逻辑中,将postDesc字段的取值直接绑定为用户提交的postCont内容,实现同一份输入数据同步写入两个字段
  • 修复原代码重复id导致CKEditor加载失效、textarea标签未闭合的格式bug
修改后的完整可运行代码
<?php
//if form has been submitted process it
if(isset($_POST['submit'])){

    $_POST = array_map( 'stripslashes', $_POST );

    //collect form data
    extract($_POST);

    //basic validation
    if($postTitle ==''){
        $error[] = 'Please enter the title.';
    }

    if($postCont ==''){
        $error[] = 'Please enter the content.';
    }

    if(!isset($error)){
        try {
            //insert into database: 描述字段直接取内容提交值
            $stmt = $db->prepare('INSERT INTO blog_posts (postTitle,postDesc,postCont,postDate) VALUES (:postTitle, :postDesc, :postCont, :postDate)') ;
            $stmt->execute(array(
                ':postTitle' => $postTitle,
                ':postDesc' => $postCont,
                ':postCont' => $postCont,
                ':postDate' => date('Y-m-d H:i:s')
            ));
            //redirect to index page
            header('Location: index.php?action=added');
            exit;
        } catch(PDOException $e) {
            echo $e->getMessage();
        }
    }
}

//check for any errors
if(isset($error)){
    foreach($error as $err){
        echo '<p class="error">'.$err.'</p>';
    }
}
?>

<form action='' method='post'>
    <p>
        <label>Title</label><br />
        <input type='text' name='postTitle' value='<?php if(isset($error)){ echo $_POST['postTitle'];}?>'>
    </p>

    <p>
        <label>Content</label><br />
        <textarea name="postCont" id="editor1" rows="10" cols="80">
            <?php if(isset($error)){ echo $_POST['postCont'];}?>
        </textarea>
    </p>

    <p><input type='submit' name='submit' value='Submit'></p>
    <script>
        CKEDITOR.replace( 'editor1' );
    </script>
</form>
注意事项
  • 提前核对MySQL表中postDesc字段的长度,确保可以完整存储和postCont一致的内容,避免插入时触发字段长度溢出错误
  • 如果后续需要优化文章描述为自动摘要形式,可在插入数据库时对$postCont做截取处理(比如取前200个字符),不需要重新增加独立输入框
  • 原代码中foreach循环覆盖$error数组变量的问题已修复,提交校验出错时用户输入的内容可正常回填到表单中

内容的提问来源于stack exchange,提问作者Din Din Da Da

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 08:15:04