PHP - 将数据插入数据库

时间:2016-01-09 01:01:52

标签: php mysql

我想问一下这段代码..我从PHP和MYSQL开始,我无法弄清楚为什么它不会INSERT INTO db即使我连接...

基本上php代码在" SUBMIT" 之后无法正常工作我没有收到消息,没有...感谢您的帮助

add_post.php:

<form>
  <div class="form-group">
    <label for="post_title">title</label>
    <input type="text" class="form-control" id="post_title" name="title"/>
  </div>
  <div class="form-group">
    <label for="post_video">video</label>
    <input type="text" class="form-control" id="post_video" name="video"/>
  </div>
  <div class="form-group">
    <label for="post_content">content</label>
    <textarea rows="10" id="post_content" class="form-control" name="content"></textarea>
  </div>
  <div class="form-group">
    <label for="file_input">file input</label>
    <input type="file" id="file_input" name="image">
    <p class="help-block">Max upload file is 5MB.</p>
  </div>
  <button class="btn btn-default" name="submit">Submit</button>
</form>

<?php  
    include('connect.php');

    if(isset($_POST['submit'])){ 

        $post_title = $_POST['title'];
        $post_date = date('d-m-y');
        $post_video = $_POST['video'];
        $post_content = $_POST['content'];
        $post_image = $FILES['image'];

        if(empty($post_title) || empty($post_content)) {
            echo "<script>alert('title or content is empty')</script>";
        }
        else {
            move_uploaded_file($post_image,"image/uploads/$post_image");

            $insert_query = "INSERT INTO post (title, image, content, video) VALUES (
              '$post_title',
              '$post_image',
              '$post_content',
              '$post_video')";

            if(mysqli_query($db, $insert_query)) {
                echo "<center><h1>post published successfuly</h1></center>";
            }
        }

    }
?>

connect.php(适用于C9.com):

<?php
    // A simple PHP script demonstrating how to connect to MySQL.
    // Press the 'Run' button on the top to start the web server,
    // then click the URL that is emitted to the Output tab of the console.

    $servername = getenv('IP');
    $username = getenv('C9_USER');
    $password = "";
    $database = "portfolio";
    $dbport = 3306;

    // Create connection
    $db = new mysqli($servername, $username, $password, $database, $dbport);

    // Check connection
    if ($db->connect_error) {
        die("Connection failed: " . $db->connect_error);
    }
?>

db screenshots:

enter image description here enter image description here

2 个答案:

答案 0 :(得分:2)

我猜您应该在表单中使用属性“method”,在这种情况下:

<form method="post">

因为默认方法是get,并且正如我所见,您希望收到$ _POST数据。 希望它有所帮助

答案 1 :(得分:2)

表单方法应该是POST,因为您要上传文件,所以应指定enctype。

这是一个例子:

<form method="post" enctype="multipart/form-data">

另外,文件的变量应该是$ _FILES而不是$ FILES

enctype的参考:http://www.w3schools.com/tags/att_form_enctype.asp