Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

PHP PHP PDO upload image to DB

JasonL

New Coder
Hi,

I am using PHP with PDO to connect DB.
$pdo = pdo_connect_mysql();

How to edit below code to connect DB?
if(ISSET($_POST['upload'])){
$file_name = $_FILES['file']['name'];
$file_temp = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$date_uploaded=date("Y-m-d");
$location="upload/".$file_name;
if($file_size < 5242880){
if(move_uploaded_file($file_temp, $location)){
try{
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `file`(file_name, file_type, date_uploaded, location) VALUES ('$file_name', '$file_type', '$date_uploaded', '$location')";
$conn->exec($sql);

}catch(PDOException $e){
echo $e->getMessage();
}

$conn = null;
header('location: index.php');
}
</center>";
}
}
 
Hi JasonL,
Welcome here!

If you use MySQL, you connect to it like such:
PHP:
$conn = new PDO("mysql:host=$serverAddress;dbname=$dataBaseName;charset=utf8", $username, $password);
If it is PostgreSQL, like that:
PHP:
$conn = new PDO("pgsql:host=$serverAddress;dbname=$dataBaseName;charset=utf8", $username, $password);
 
I want to reply in full shortly, but for starters...
SANITIZE your data!! You need to make sure you check what type of file it is too - by extension or raw meta data for file type.

I highly recommend using some prepared queries... You can learn how to write a PHP prepared statement / query with my tool I made to help construct the code for beginners:

You should also be checking if the size is over 0 because an empty file upload will fail.

Also you need to make sure you check if file_exists() or not so you don't fail to save a file or overwrite it, etc.

I recommend doing like:
while($filename = md5(rand(0,10000)) && !file_exists($location . $filename . $fileextension){ code to save file here }

... or something similar. This of course would only support 10,000 total uploads, so using a different algorithm for filenames is advised if you have a big project in mind!


-------
Is there a specific error you are trying to fix?
 
Last edited:
Back
Top Bottom