Saving Image in mySQL
| From: | Ron Piggott | Date: | Tue, 19 Mar 2013 20:15:44 +0000 |
| Subject: | Saving Image in mySQL | ||
| Groups: | php.db | ||
| Request: | Send a blank email to php-db+get-48702@lists.php.net to get a copy of this message | ||
Hi All
I don’t understand how to save an image to a mySQL table based on the following form. I am trying
to do this using Prepared Statements. All the fields except the image file itself save in the
database. Right now I have $file as the variable when binding the values. What should it be? Ron
===
<form action="add_my_image.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file"><br>
<input type="submit" name="submit" value="submit">
</form>
===
mySQL table structure:
===
reference – INT 10 auto_increment primary
caption – VARCHAR 250
image_type – VARCHAR 100
image_size – INT 10
image_name – VARCHAR 100
image – LONGBLOB
===
Prepared Statement:
===
# mySQL query
$query = "INSERT INTO
my_images ( reference ,
caption , image_type , image_size , image_name ,
image ) VALUES ( NULL , :caption , :image_type , :image_size , :image_name , :image
);";
# apply query to Prepared Statement
if($stmt = $dbh->prepare( $query )) {
# bind variables
$stmt->bindValue(':caption', 'Test Caption', PDO::PARAM_STR);
$stmt->bindValue(':image_type', $_FILES["file"]["type"],
PDO::PARAM_STR);
$stmt->bindValue(':image_size', $_FILES["file"]["size"],
PDO::PARAM_INT);
$stmt->bindValue(':image_name', $_FILES["file"]["name"],
PDO::PARAM_STR);
$stmt->bindValue(':image', $file, PDO::PARAM_STR);
# execute query
if ( $stmt->execute() or die(print_r($stmt->errorInfo(), true)) ) {
# retrieve auto_increment value
$new_record_reference = $dbh->lastInsertId();
}
}
===
Ron Piggott
www.TheVerseOfTheDay.info