How to upload file to database - php

I am trying to create a upload.php which uploads only PDF, DOC and DOCX to the database (path) and a file on my server. Now my upload to the file is working but I do not really know how to upload the link(path) to my table row.
Also the file I am uploading has to be able to be download by a click on a button on a detail page.
My upload.php
<?php
$servername = "localhost";
$username = "root";
$password = "usbw";
$dbname = "persons";
// CREATE A CONNECTION WITH THE DATABASE
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_FILES["cv"]["error"] > 0)
{
echo "<font size = '5'><font color=\"#e31919\">Error: NO CHOSEN FILE <br />";
echo"<p><font size = '5'><font color=\"#e31919\">INSERT TO DATABASE FAILED";
}
else
{
move_uploaded_file($_FILES["cv"]["tmp_name"],"files/" . $_FILES["cv"]["name"]);
echo"<font size = '5'><font color=\"#0CF44A\">SAVED<br>";
$file="files/".$_FILES["cv"]["name"];
$sql="INSERT INTO person (person_cv, path) VALUES ('','$file')";
if (!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
echo "<font size = '5'><font color=\"#0CF44A\">SAVED TO DATABASE";
}
mysql_close();
?>
The database name is called "persons" which has a table called person. The file link should save to person_cv. I am new to PHP and I am trying to understand PHP however there are so many ways to do it because of that I am getting confused.

You are confused of database structure too, as I see.
I don't know what data you really want to keep in database, but you need following:
table with basic data (called for example people_id), where you will have for example
id
name and surname
cv_file_id
table with file info
file_id (values must be the same as in cv_file_id)
name (may be exact name of file as was before uploading, or rather changed for better manipulation)
type (dfefined mostly by extension, like doc, docx, txt or so)
and probably also some other tables for informations of people, themselves
And in domain folders you will have one, where you will keep all uploaded cv files. And then, you will update db tables as needed - and also upload those files.
That is the most reasonable way how to do it. I would do it in this way. May it be that someone more experienced would do it in else way.

Related

How to update SQL data only if 1 hour is passed

I am working with a coupon code website, it has a products section. Instead of pulling data from API server of shopping sites every time a visitor loads the page, I want to store the data in SQL and use it..
But the data should update every hour or only if an hour is passed.
cron job is not required as I dont want to happen it automatically.
If there is 100 webpage users in an hour, they will get the same data, but when the first user comes after 1 hour time, it should overwrite the products's information in SQL.
I got the following code from w3schools.com and it work fine for saving data in SQL.
I hope some can help me to overwrite data only if it the data older than 1 hour. Otherwise it should act as "data already exists".
<?php
$servername = "localhost";
$username = "nuser";
$password = "pass";
$dbname = "db";
$ProductId = "smartphone";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$check=mysqli_query($conn,"select * from testdb where productid='$ProductId'");
$checkrows=mysqli_num_rows($check);
if($checkrows>0) {
echo "Data Already Exists";
} else {
//insert results from the form input
$sql = "INSERT INTO Flipkart (productid, title, price)
VALUES ('productid','title','price')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();}
?>
The above code saves data in database, it can also detect duplicate data. but I want to add just one more function, which will overwrite data if the current data time is older than 1 hour. database has a TIMESTAMP "reg_date" column, which stores created date and time in YYYY-MM-DD HH:MM:SS format.
I am new to SQL and php, so pardon me if there is any problems with the question...
You can use a cron job.
This is the best explanation with code for PHP I have found so far for cron job:
https://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428

MySQL updating email addresses and assigning them ip's

I am currently working on a project which will sell a product to a user, and on checkout completion, the user will enter an email address. I have been trying (but to no avail so far) to use MySQL to put this data into a database. Only in a certain way. I need the input data to use the UPDATE method to be put into an already existing row. This row should match the following criteria. It should not have already been used, the email should not already exist within the database. I have tried so many different pieces of MySQL, I get all sorts from syntax errors to it updating every record in my table, I have gotten as far as it updating just one, but not checking if it already exists. I was hoping for a little insight as to how I can improve!
Code as follows:
<?php
$servername = "localhost";
$username = "Josh";
$password = "10584066";
$dbname = "customers";
// Get email address from input form
$Email = $_GET['keyword'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE list SET Email='$Email' , In_Use='1' WHERE In_Use='0' LIMIT 1";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
header('Location: /liteservers/logon/wood.php');
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
So, as you can see. The code is working almost as intended, I just want it to also check to see IF the email is already in the database and if it is, perhaps add the time that it attempted to record a new email within the same row as the already found existing email. I hope this actually makes sense if you need any more info that I haven't provided, let me know!
Use INSERT ON DUPLICATE KEY UPDATE syntax and mysql_affected_rows will tell you if its and insert or update.

PHP load csv into sql table only works when all permissions granted #localhost

This question has been asked but no answers yet...
Have a csv upload form to load into an existing MySQL table for use on a Drupal page, hence everything being in one php. This is what I have (thanks coyotelab):
$mysqli = new mysqli($server, $user, $password, $database);
if ($mysqli->connect_error) {
die("Failed to connect: " . $mysqli->connect_error);
}
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h2>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h2>";
}
$handle = fopen($_FILES['filename']['tmp_name'], "r");
if ($handle !== FALSE) {
$import="LOAD DATA LOCAL INFILE '" . $_FILES['filename']['tmp_name'] . "' INTO TABLE Demo2 CHARACTER SET 'utf8' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' IGNORE 1 LINES;";
mysql_query($import) or die('<p style="color:red;">Database import unsuccessful: ' . mysql_error() . '</p>');
}
fclose($handle);
print "<p style='color:blue;'>Import done</p>";
echo "<p style='position: relative; top: 10px;'><strong>Displaying contents:</strong></p>";
readfile($_FILES['filename']['tmp_name']);
unset($_POST);
} else {
print "<p>Import new csv</p>\n";
print "<form enctype='multipart/form-data' action='?q=drupal-relative-path-to/upload.php' method='post'>\n";
print "<input size='50' type='file' name='filename'><br />\n";
print "<input type='submit' name='submit' value='Import'></form>";
At first, the form was test locally and granting all permissions to localhost worked and data imported successfully. But on a Drupal server, there will be no change to localhost permissions. Other forms to insert SQL data have worked fine from Drupal pages. Only happens with the upload file function.
So far the form shows up on Drupal, but when uploading and submitting a CSV, I get the same error as testing on localhost without permissions. Error is "No database selected"
My thought was to change the location where uploaded temp files live, though haven't figured that out or might not be possible on the Drupal server. Tried adding a second db connect line, but that doesn't work. Must have something to do with the temp directory.
This form will be on a private network.
If error is "No database connection" then your code fails on very first code row displayed here. Something is wrong with your database user account information (or account it self). Maybe host isn't "localhost" but something else?
If Drupal is working well check out it's connection. Check file /sites/default/settings.php. There is stored information about database connection so you can copy your account data from there.
BTW, instead of old school fopen on PHP you have easier to use file_get_contents() function.

Add an Image in a table mysql

The main idea is being able to controll, upload and delete a slideshow's images from a database.
So, first I connect to the database like this, and with a while function I echo all the images I have stored in my db.
This is the code to do that:
<?php
$servername = "myservername";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
$sql = "SELECT id, img FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<img src=".$row['img'].">";
}
} else {
echo "0 results";
}
?>
In the table "mytable" I have 2 columns: an ID auto-inc and a column called img.
How can I store an image in the img column so that my function will echo all the images I have in my table?
All I found searching til now was a lot of methods that upload the image with an html form, but I'd prefer to upload my img directly on my database, without building an html+php form to upload all my images to my table.
Is that possible?
Storing entire images in a database is generally a bad idea. It is much simpler to simply store the path of the image inside your database, as has already been mentioned. You may have a bit of extra work deleting the images, as you would need a php system call to delete the image file.
If you really must store images inside a database, you can save them as base64 encoded text. I've seen this be done at a fairly successful company, but no particularly good reason was given for this. Your sql execution time will be substantially larger, because images are large files, and your table size will balloon.

uploading different MIME types to a DataBase with one table

I'm working on a project that the user will be Upload several files with different MIME Types and I want to save the files to a DataBase(Mysql with InnoDB engeen).
Now These are my Questions:
1/ Should I Create several Tables for every MIME type or may be different rows for every type?
2/ I tested BLOB in rows type in mysql for field's type, but it seems there is a problem with DB!!! --either I tried MEDIUM BLOB and LONG BLOB--
3/ If I have to save every MIME type in a different row or table, Which type is OK for this iletypes: a/pdf b/jpeg c/png d/gif e/video/mp4 f/application/word
Here is a small example I just tested
Table: files
id (primary key, auto increment)
filename (varchar 255)
type (varchar 255)
file (largeblob)
encoding: utf8_unicode_ci
<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=test", $username, $password);
echo 'Connected to database';
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $dbh->prepare("INSERT INTO `files` (filename, type, file) VALUES('img.png', 'image/png', :bin)");
$sql->bindParam("bin", file_get_contents("img.png"));
$sql->execute();
$sql = $dbh->prepare("SELECT * FROM `files` WHERE `filename`='img.png'");
$sql->execute();
$result = $sql->fetch();
$file = fopen("new-".$result['filename'], "w+");
$w = fwrite($file, $result['file']);
fclose($file);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
For what you are trying to do:
Instead of fixed file you use the temporary file that was uploaded.
You use the MIME type of that file (you can get it with php)
When you need to read the file you simply read the BLOB field and write it to a file using the filename as the name.
I did not notice any problems with the BLOB fields. If you can't resolve that problem you could use a TEXT field and store base64_encode(file) into that.

Categories