I am able to upload a file and echo these. But now I would like to upload these to my database. How would I go onto doing this. I found something like this for C++. but not sure how to convert this to PHP.

this is what I found

// previously setup variables
IBPP::Database db;
IBPP::Transaction tr;
IBPP::Statement st;
std::string file_content; // loaded from file: myfile.pdf

// writing file data to Blob column
st->Prepare("INSERT INTO t1 (file_name, file_data) VALUES (?, ?)");
st->Set(1, "myfile.pdf");
IBPP::Blob b = IBPP::BlobFactory(db, tr);
st->Set(2, b);

This is what I have so far

  if ($_FILES["file"]["error"] > 0)
    echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    if (file_exists("upload/" . $_FILES["file"]["name"]))
     // echo $_FILES["file"]["name"] . " already exists. ";
      "upload/" . $_FILES["file"]["name"]);
      //echo "Stored in: " . "upload/" . $_FILES["file"]["name"];

$filename = "upload/" . $_FILES["file"]["name"];
$fd = fopen ($filename, "r");
$contents = fread ($fd,filesize ($filename));

fclose ($fd);
$delimiter = ".";
$splitcontents = explode($delimiter, $contents);

foreach ( $splitcontents as $color )

      echo "<b>Question </b> $color<br>";


Considering the example provided, I have to ask first, what type of database are you utilizing?

Member Avatar

You sure you want to save the contents or would it be better to upload to a dir and hold a reference to the filepath in the DB?

1st method: grab the file contents (file_get_contents()) and write it to a blob field.
2nd method: grab the filename from $_FILES or whatever name you've given the file field in your form. Post the filename in the DB. Simple. If you want, you can give the filename a unique name based on the upload datetime - sometimes useful if you get duplicate names for uploaded files. However, this can be avoided with prudent use of the file_exists() function

Thanks for the help but I will like to save the content and not the file itself. I just want to read whats inside the file and upload this to the database.

You need to upload the file in a long-blob binary form, and use the mime-type when outputting.

if i have time tomorrow I'll post some code

Thanks. Ill search it up today and try to do this, if not I do need your help :)

The file you are uploading and reading from is a .pdf file, correct?

Well, assuming that the format is like:


Then, the first thing that you would want to do after reading the file contents is split the contents by line breaks. After that, you can split and INSERT the variables into your database. Hope this helps. :)

I am splitting this by

$delimiter = ".";
$splitcontents = explode($delimiter, $contents);

But not sure how to INSERT this to datbase now