0

こんにちは、画像がサーバーにアップロードされるたびに、画像データをデータベースに挿入しています。私が使用しているコードは、特にバインドが少し「分厚い」ように見えます。テキストの量を減らしてより迅速に実行するために、別の方法で実行できますか?それとも心配する必要はありませんか?

私が使用しているコードは次のとおりです。

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();
    }
4

2 に答える 2

-1

書き換えるコードの量に応じて、純粋な PDO の使用から RedBean のようなものにいつでも切り替えることができます (これは実際には非常に優れており、ゼロ構成の ORM です)。

http://www.redbeanphp.com/

今は使用しない場合でも、一見の価値があります。それは間違いなく素晴らしいツールです。

挿入では、Bean プロパティを変更するだけで済み、使用するコードの全体量が削減されます。

于 2012-06-04T14:50:22.117 に答える
-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 )

?>
于 2012-06-04T14:59:58.853 に答える