0

我是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');
 ?>
4

3 回答 3

0

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

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

您需要dbname在 DSN 中使用,而不是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 。

于 2013-09-08T06:33:16.603 回答
0

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

$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' )))";

并给出类 aok和 a counts

<?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: ";}
 ?>
于 2013-09-08T05:53:40.750 回答
-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);

如果出现问题,此设置至少会告诉您。

于 2013-09-08T03:29:57.353 回答