php - More efficient way of inserting using PDO? -


hi inserting image data database each time image uploaded server. code using looks bit 'chunky' binds. can done differently reduce amount of text , execute more or should not worry it?

here code using:

function($file_name, $cat, $year, $desc, $title, $image_size, $image_width, $image_height){     //test connection     try {         //connect database         $dbh = new pdo("mysql:host=localhost;dbname=mjbox","root", "usbw");         //if there error catch here     } catch( pdoexception $e ) {         //display error         echo $e->getmessage();     }      $stmt = $dbh->prepare("insert 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();     } 

you this, passing array of values , use keys place holders, way can use same function insert different tables:

<?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 connection     try{         //connect database         $dbh = new pdo("mysql:host=localhost;dbname=mjbox","root", "usbw");         //if there error catch here     } catch( pdoexception $e ) {         //display error         echo $e->getmessage();     }      $fieldnames = array_keys($values);      $sql = "insert $table";     $fields = '( ' . implode(' ,', $fieldnames) . ' )';     $bound = '(:' . implode(', :', $fieldnames) . ' )';     $sql .= $fields.' values '.$bound;      $stmt = $dbh->prepare($sql);     $stmt->execute($values);// whoops }  //insert 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 )  ?> 

Comments

Popular posts from this blog

java - Play! framework 2.0: How to display multiple image? -

gmail - Is there any documentation for read-only access to the Google Contacts API? -

php - Controller/JToolBar not working in Joomla 2.5 -