duan39779 2018-01-01 14:20
浏览 78
已采纳

在Wordpress中,如何使用文件上载选项编写自定义表单并将记录保存在MySql中?

So far I have been able to make a custom form which upon successful entry save the value to a MySql table called "form_entry"

Below is the code for a form:

<form method="post" class="container">
<div class="row">
<div class="col-md-6 mb-3">
<label>Name</label>
<input type="text" name="myname" class="form-control" placeholder="Name" value="John Doe" required>
</div>
<div class="col-md-3 mb-3">
<label>State</label>
<input type="text" name="statename" class="form-control" placeholder="State" required>
</div>
</div>
<button class="btn btn-primary" type="submit" name="BtnSubmit" value="submit">Submit form</button>
</form>

And I insert a few codes in the functions.php under my template folder like this :

if(isset($_POST['BtnSubmit'])) {
    global $wpdb;
    $data_array = array(
                        'myname' => $_POST['myname'],
                        'statename'  => $_POST['statename'],

                        );

    $table_name = 'form_entry';
    $rowResult = $wpdb ->insert($table_name, $data_array, $format=NULL);

    if($rowResult == 1) {
        echo 'Success';
    }
else {
    echo ' Error in my pant';
}   
die;
}

This is working fine. But I want to add a file upload option in the form and save the uploaded file location to MySql. Please help.

  • 写回答

1条回答 默认 最新

  • douyan9398 2018-01-01 14:46
    关注

    You have to add one field into your html form. and add parameter for into form.

    <form method="post" class="container" enctype="multipart/form-data">
    
    <div class="row">
        <div class="col-md-6 mb-3">
            <label>File</label>
            <input type="file" name="myfile" class="form-control" required/>
        </div>
    </div>
    

    then after submit you have to save uploaded file at particular location and save that file into your db.

    if (isset($_POST['BtnSubmit'])) {
        $target = 'uploads/' . basename($_FILES['myfile']['name']);
    
        if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target)) {
            $fp = fopen($target, "r");
        }
        global $wpdb;
        $data_array = array(
                        'myname' => $_POST['myname'],
                        'statename'  => $_POST['statename'],
                        'filename' => $target
                     );
    }
    

    I think it will work for you !! feel free to ask me.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献