PDO代码没有向mysql输入数据

时间:2015-04-17 03:23:06

标签: php html mysql pdo

我使用php PDO将数据发布到mysql数据库。

我的图片加载并保存到目标文件夹。

当我测试网站时,除了没有数据输入数据库外,一切都正常

代码:

if( isset($_POST['title'], $_POST['description'],$_POST['weblink']) ) {     
           $file = "adimages/" . $_FILES["file"]["name"];
        $conn = new PDO($dsn, $username, $password);
        $date = date('Y-m-d H:i:s');
        $stmt = $conn->prepare("INSERT INTO posted_ad_img (title, file, link, description, NOW()) VALUES (:title, :image_file_path, :link, :description, :date_post)");
        $stmt -> bindParam(':title', $_POST['title']);
        $stmt -> bindParam(':image_file_path', $file);
        $stmt -> bindParam(':description', $_POST['description']);
        $stmt -> bindParam(':link', $_POST['weblink']);
        $stmt -> bindParam(':date_post', $date);
        // Execute the query
    if($stmt->execute()){
        echo "<div class='alert alert-success' role='alert'>Record was added!.</div>";
    }else{
        die("<div class='alert alert-danger' role='alert'>Unable to update record!</div>");
    }
       }
    }

当我进入phpadmin查看表格时,为什么数据没有显示?

2 个答案:

答案 0 :(得分:0)

您需要在$dsn之前将$conn = new PDO($dsn, $username, $password);定义为

$dsn = 'mysql:dbname='.$DATABASE.';host='.$SERVER.'';

您也可以将executeParam替换为execute中的数组。

所以整个代码将如下:

if( isset($_POST['title'], $_POST['description'],$_POST['weblink']) ) {     
           $file = "adimages/" . $_FILES["file"]["name"];
        **$dsn = 'mysql:dbname='.$DATABASE.';host='.$SERVER.'';**
        $conn = new PDO($dsn, $username, $password);
        $date = date('Y-m-d H:i:s');
        $stmt = $conn->prepare("INSERT INTO posted_ad_img (title, file, link, description, NOW()) VALUES (:title, :image_file_path, :link, :description, :date_post)");

        // Execute the query
    if($stmt->execute(array("title"=>$_POST['title'],"image_file_path"=>$file,"description"=>$_POST['description'],"link"=>$_POST['weblink'],"date_post"=>$date))){
        echo "<div class='alert alert-success' role='alert'>Record was added!.</div>";
    }else{
        die("<div class='alert alert-danger' role='alert'>Unable to update record!</div>");
    }
       }
    }

使用以下代码检查服务器中是否已启用wheater PDO:

try {
  $dsn = 'mysql:dbname='.$DATABASE.';host='.$SERVER.'';
  $conn = new PDO($dsn, $USERNAME, $PASSWORD);
} catch (PDOException $e) {
  echo 'Connection failed: ' . $e->getMessage();
}

答案 1 :(得分:0)

我弄清楚了,没注意括号。我正在执行else内部的pdo语句,而不是将代码移到它之外。一旦我执行了代码。