PHP PDO PDOStatement() 详解

注意事项

一:sql 语句的字符串的长度

二:插入前要关闭游标再插入

Warning: PDOStatement::execute(): MySQL server has gone away  错误发生的时候调整下 j 的最大值即可

关键代码: 

分析,通过循环来添加数据,若出现

$db = mysql::getInstance();

$num = 1;
for($i = 1; $i <= 3 ; $i++) {
  $sql = "insert into table_name (user_id, min, status) VALUES ";
  for($j = 1 ; $j <= 10000; $j++) {
    $user_id = $num + 70022;
    if ($j == 10000) {
      $sql .= "($user_id, 60, 1)";
    } else {
      $sql .= "($user_id, 60, 1),";
    }
    $num ++;
  }
  $db->query($sql);
  $db->close();
}

 

/********************** mysql 类  *************/
class mysql {

    static protected $instance = null;

    //声明数组存放数据
    private $data=array();

    //pdo对象
    private $db=NULL;

    //表名
    protected $table = '';

    protected $rootDir;

    //pdostatement类对象
    protected $stms = null;

    final protected function __construct(){

        try{
            $this->db = new PDO("mysql:host=127.0.0.1;dbname=xxx;port=3306;",'root','xxxx');
            //设置字符集
            $this->db->exec("set names utf8");

        }catch(PDOException $e){
            echo 'Connection Error: '.$e->getMessage();
            exit;
        }
    }

    final protected function __clone(){

    }

    public static function getInstance(){
        if(! self::$instance instanceof self){
            self::$instance=new self();
        }
        return self::$instance;
    }

    /*
    *   预处理执行sql语句
    *   $sql    要执行的sql语句
    *   return  volid
    */
    public function query($sql){

        $this->stms = $this->db->prepare($sql);

        $this->stms->setFetchMode(PDO::FETCH_ASSOC);

        return $this->stms->execute();

    }

    public function close() {
      $this->stms->closeCursor();
    }

    public function execSql($sql){
        $res = $this->query($sql);

        return $res ? $this->stms->fetch() : null;
    }
}

 

你可能感兴趣的:(网站开发)