I want to store data (mostly text) and an optional image using PDO. So, text is no problem at all but my problem comes with the "optional" image.
How can i build a query that provides an optional image field.
for text: Something like:
$conn = new PDO(DNS, username, password);
$sql = "INSERT INTO DATABASE (fields) VALUES ( using place holders (? or :holder))";
$stmt = $conn->prepare($sql);
$stmt->bindparam(':holder', '$_GET['value']');
$stmt->execute();
But for an optional image how can I do it?
I have the form built with the file type input:
<input type="file" name="image" />
UPDATE:
Let's imagine the following form:
<form action="index.php" method="post" enctype="multipart/form-data" >
<input type="text" name="sometext" />
<input type="file" name="someimage"/>
<input type="submit" name="sendform" value="send"/>
</form>
The file type input is optional, what I want to know is how to build a query for that purpose using PDO, in order words the user may or not send an image but text will be required.
Thank you.
From PHP: Large Objects (LOBs)
<?php
$db = new PDO('odbc:SAMPLE', 'db2inst1', 'ibmdb2');
$stmt = $db->prepare("insert into images (id, contenttype, imagedata) values (?, ?, ?)");
$id = get_new_id(); // some function to allocate a new ID
// assume that we are running as part of a file upload form
// You can find more information in the PHP documentation
$fp = fopen($_FILES['file']['tmp_name'], 'rb');
$stmt->bindParam(1, $id);
$stmt->bindParam(2, $_FILES['file']['type']);
$stmt->bindParam(3, $fp, PDO::PARAM_LOB);
$db->beginTransaction();
$stmt->execute();
$db->commit();
The gist of it is that you can pass PDOStatement::bindParam
a filehandle, tell PDO is should be saved as a Large Object (exact datatype will depend on your database), and PDO will handle the rest.
As for having the file upload be optional - just check if they uploaded anything. If they didn't, bind null
instead of a filehandle.