【发布时间】:2012-06-04 14:46:21
【问题描述】:
您好,每次将图像上传到我的服务器时,我都会将图像数据插入数据库。我使用的代码看起来有点“笨拙”,尤其是绑定。是否可以采取不同的方式来减少文本量并更快地执行,还是我不应该担心?
这是我正在使用的代码:
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();
}
【问题讨论】:
-
您可以简单地将所有值添加到数组中并执行它。尽管根据您的标题,这与效率无关。
-
您可能应该在您的 catch 块中返回,因为您将在 PDO 的垃圾对象实例上运行查询(连接失败,因为 PDOException 会告诉您)。