Php 使用PDO插入的更有效方法?

Php 使用PDO插入的更有效方法?,php,mysql,insert,pdo,bind,Php,Mysql,Insert,Pdo,Bind,嗨,每次图像上传到我的服务器时,我都会将图像数据插入数据库。我使用的代码看起来有点“笨重”,尤其是绑定。是否可以采用不同的方法来减少文本量并更快地执行,或者我不必担心它 以下是我正在使用的代码: function($file_name, $cat, $year, $desc, $title, $image_size, $image_width, $image_height){ //test the connection try { //connect to the

嗨,每次图像上传到我的服务器时,我都会将图像数据插入数据库。我使用的代码看起来有点“笨重”,尤其是绑定。是否可以采用不同的方法来减少文本量并更快地执行,或者我不必担心它

以下是我正在使用的代码:

function($file_name, $cat, $year, $desc, $title, $image_size, $image_width, $image_height){
    //test the connection
    try {
        //connect to the database
        $dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
        //if there is an error catch it here
    } catch( PDOException $e ) {
        //display the error
        echo $e->getMessage();
    }

    $stmt = $dbh->prepare("INSERT INTO mjbox_images(img_file_name,img_cat,
        img_year,img_desc,img_title,img_size,img_width,img_height) 
        VALUES(?,?,?,?,?,?,?,?)");

        $stmt->bindParam(1,$file_name);
        $stmt->bindParam(2,$cat);
        $stmt->bindParam(3,$year);
        $stmt->bindParam(4,$desc);
        $stmt->bindParam(5,$title);
        $stmt->bindParam(6,$image_size);
        $stmt->bindParam(7,$image_width);
        $stmt->bindParam(8,$image_height);
        $stmt->execute();
    }

根据您想要重写的代码量,您可以随时从使用纯PDO切换到类似RedBean的东西(这实际上非常好,是一个零配置的ORM)

值得一看,即使你现在不使用它;这绝对是一个很棒的工具


插入只需要修改bean属性,减少使用的代码总量。

您可以这样做,传递一个值数组并使用键作为占位符,这样您就可以使用相同的函数插入到不同的表中:

<?php 
$insert = array('img_file_name'=>'',
                'img_cat'=>'',
                'img_year'=>'',
                'img_desc'=>'',
                'img_title'=>'',
                'img_size'=>'',
                'img_width'=>'',
                'img_height'=>'');

insert('mjbox_images',$insert);

function insert($table,$values=array()){

    //test the connection
    try{
        //connect to the database
        $dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
        //if there is an error catch it here
    } catch( PDOException $e ) {
        //display the error
        echo $e->getMessage();
    }

    $fieldnames = array_keys($values);

    $sql = "INSERT INTO $table";
    $fields = '( ' . implode(' ,', $fieldnames) . ' )';
    $bound = '(:' . implode(', :', $fieldnames) . ' )';
    $sql .= $fields.' VALUES '.$bound;

    $stmt = $dbh->prepare($sql);
    $stmt->execute($values);// whoops
}

//INSERT INTO mjbox_images( img_file_name ,img_cat ,img_year ,img_desc ,img_title ,img_size ,img_width ,img_height ) VALUES (:img_file_name, :img_cat, :img_year, :img_desc, :img_title, :img_size, :img_width, :img_height )

?>


您只需将所有值添加到一个数组并执行即可。尽管这与你的标题所述的效率无关。你可能还想看看如何操作。你可能应该在catch块中返回,因为你将在PDO的垃圾对象实例上运行查询(PDO异常会告诉你,该实例无法连接)。是否每次用户要插入内容时都要打开新连接?那么更新、删除等呢?为OP写一个完整的CRUD是我的期望吗?对于标题中有效率的问题,我希望答案是有效的。但这不是。在调用
$stmt->execute()
时也不会插入任何内容。我很抱歉,单身汉并不是真的更好。