使用PDO更有效的插入方式?

时间:2012-06-04 14:46:21

标签: 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 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();
    }

2 个答案:

答案 0 :(得分:-1)

根据您想要重写的代码数量,您可以随时使用纯PDO替换为类似RedBean的东西(实际上非​​常好,是零配置ORM)。

http://www.redbeanphp.com/

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

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

答案 1 :(得分:-2)

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

<?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 )

?>