使用PDO插入数据

时间:2013-09-08 01:05:29

标签: php mysql pdo

我是 PDO 的新手。我听说程序员在项目中使用多个数据库更友好,而且更安全,所以我想学习 PDO 。我想使用 PDO 将数据插入 MySQL ,但我不能,并且没有错误消息。我使用了以下代码:

<?php 

   class ManageUsers02 {             
     private   $db_con;
     public    $db_host  = "localhost";  // I run this code on my localhost
     public    $db_name  = "todo";       // database name
     public    $db_user  = "root";       // username
     public    $db_pass  = "";           // password

     function __construct() {           
        try {
            // connect to database using PDO
           $this->db_con = new PDO("mysql:host=$this->db_host;db_name=$this->db_name", $this->db_user, $this->db_pass);             
        } catch (PDOException $exc) {  // PDO exception handling
           echo $exc->getMessage();    
        }             
     }

     public function reg_user($username, $password, $ip_address, $reg_date, $reg_time ) {
       try {
          // preparing sql query 
          $query = $this->db_con->prepare("INSERT INTO user_reg (username, password, ip_address, reg_date, reg_time) VALUES ( ?, ?, ?, ?, ? )");  
       }
       catch( PDOException $exc )  {  // PDO exception handling
          echo $exc->getMessage();
       }

       try {
           // execute sql query
           $query->execute(array($username, $password, $ip_address, $reg_date, $reg_time)); 
       }
       catch( PDOException $exc )  {
          echo $exc->getMessage();
       }

       $counts = $query->rowCount();  // return value of affected row
       // here it should be return 1       

       echo "<br /> count :: <b> " . $counts . "</b> <br />";  // shows result 0
       // no value inserted 
     }


   }

   $user_reg = new ManageUsers02();         

   $user_reg->reg_user('pdo_name', 'pdo_password', '127.0.0.1', '2013-2-6', '4:20 am');
 ?>

3 个答案:

答案 0 :(得分:0)

由于将字符串插入mysql Time字段,因此失败。

$sql =  "INSERT INTO user_reg ( ... , reg_time) VALUES (..., '4:20 am');

如果您想使用'4:20 am',请使用。

TIME( STR_TO_DATE( ? , '%h:%i %p' ))

$sql =  "INSERT INTO user_reg ( ... , reg_time) VALUES 
                ( ?, ?, ?, ?, TIME( STR_TO_DATE( ? , '%h:%i %p' )))";

并为课程提供okcounts

<?php 

   class ManageUsers02 {             
     ...
     public    $counts   = 0;
     public    $ok       = false;

     function __construct() {           
        try {
          $this->db_con = new PDO("mysql:dbname=$this->db_name;host=$this->db_host", $this->db_user, $this->db_pass);             
        } catch (PDOException $exc) {  // PDO exception handling
           echo $exc->getMessage();
          return;
        } 
        if (!$this->db_con) {
          return;
        }
     $this->ok = true;   
     }

     public function reg_user($username, $password, $ip_address, $reg_date, $reg_time ) {
       $this->counts = 0;
       $this->ok = false;     
       $sql =  "INSERT INTO user_reg (username, password, ip_address,
                reg_date, reg_time) VALUES 
                ( ?, ?, ?, ?, TIME( STR_TO_DATE( ? , '%h:%i %p' )))";
       try {              
        $query = $this->db_con->prepare($sql);  
       }
       catch( PDOException $exc )  {  // PDO exception handling
        echo $exc->getMessage();
        return;
       }
        if (!$query) {
          return;
        }
       try {
       $this->ok = $query->execute(array($username, $password, $ip_address, $reg_date, $reg_time));
       }
       catch( PDOException $exc )  {
          echo $exc->getMessage();
          $this->ok = false;
          return;
       }
       if ($this->ok) {
       $this->counts = $query->rowCount();  // return value of affected row
       }
     }
   }

   $user_reg = new ManageUsers02();
   if ($user_reg->ok) {
       $user_reg->reg_user('pdo_name4', 'pdo_password4',
       '127.0.0.1', '2013-2-6', '04:20 am' );
       if ($user_reg->ok) {
              echo "<br /> count :: <b> " . $user_reg->counts . "</b> <br />";
   } else { echo "Error : Insert failed";}
   } else { echo "Error : Connection failed: ";}
 ?>

答案 1 :(得分:0)

+1来自@ moskito-x的答案,用于发现错误的时间格式。但是您的代码还存在其他一些功能问题。

$this->db_con = new PDO("mysql:host=$this->db_host;db_name=$this->db_name", ...

您需要在DSN中使用dbname,而不是db_name。见http://www.php.net/manual/en/ref.pdo-mysql.connection.php

$this->db_con = new PDO("mysql:host=$this->db_host;dbname=$this->db_name", ...

您还需要启用错误模式,如下所示:

$this->db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

如果不这样做,PDO不会在prepare()或execute()上抛出异常,但如果出现错误,这些函数只返回 false

答案 2 :(得分:-1)

我不知道您的插件有什么特别的问题,但是您的实现非常糟糕。按设计。

首先你必须摆脱类中的PDO连接代码。您必须单独创建一个PDO实例,然后只在构造函数中传递它。

其次,你必须摆脱所有这些try..catch,这会使你的代码膨胀,没有丝毫的好处。

此外,无类方法输出单个字节,但仅返回。

所以,它必须像

<?php 

ini_set('display_errors',1);
error_reporting(E_ALL);

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = array(
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);

class ManageUsers02
{             
    private $db_con;

    function __construct($db_con)
    {
        $this->db_con = $db_con;
    }
    public function reg_user($username, $password, $ip_address, $reg_date, $reg_time )
    {
        $sql "INSERT INTO user_reg (username, password, ip_address, reg_date, reg_time) 
              VALUES ( ?, ?, ?, ?, ? )";
        $query = $this->db_con->prepare($sql);  
        $query->execute(array($username, $password, $ip_address, $reg_date, $reg_time)); 
        return $counts = $query->rowCount();  // return value of affected ro
    }
}
$user_reg = new ManageUsers02($pdo);         
$count = $user_reg->reg_user('pdo_name', 'pdo_password', '127.0.0.1', '2013-2-6', '4:20 am');
var_dump($count);

此设置至少会告诉您是否出现问题。