How can I change this code to upload multiple files? - php

Here I am uploading single file to the database and I used longblob, how can I change this code to upload multiple files to database with same id and also I can able to download more than one uploaded files for the same id in download option. Can anyone please help me?
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', '12345', 'documentksrsac');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
//$project_name = $_POST["pname"];
//$project_name = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['project_name']));
// $project_name =real_escape_string(['uploaded_file']['project_name']);
$name = $dbLink->real_escape_string($_FILES['uploaded_file']['name']);
$mime = $dbLink->real_escape_string($_FILES['uploaded_file']['type']);
$data = $dbLink->real_escape_string(file_get_contents($_FILES ['uploaded_file']['tmp_name']));
$size = intval($_FILES['uploaded_file']['size']);
// Create the SQL query
$query = "
INSERT INTO `fileupload1` (
`name`, `mime`, `size`, `data`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}'
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// close connection
//mysqli_close($link);
?>

For multiple Image uploading I am using given code:-
<form method="post" enctype="multipart/form-data">
<input type="file" name="img[]" >
<input type="file" name="img[]" >
<input type="file" name="img[]" >
<input type="file" name="img[]" >
<button type="submit" name="save" >Submit</button>
</form>
<?php
if(isset($_POST['save']))
{
$img_name=$_FILES['img']['name'];
$img_type=$_FILES['img']['type'];
$img_temp_name=$_FILES['img']['tmp_name'];
$img_size=$_FILES['img']['size'];
$count=count($img_name);
for($i=0; $i<$count; $i++){
$name=$img_name[$i];
$type=$img_type[$i];
$temp_name=$img_temp_name[$i];
$size=$img_size[$i];
$query = "INSERT INTO `fileupload1` (`name`, `mime`, `size`, `data`)VALUES ('{$name}', '{$type}', {$temp_name}, '{$size}')";
$result = $dbLink->query($query);
}
}

Related

How to INSERT an array of uploaded filenames into a table and later display them?

I am working on a project where each item could have multiple images, I created a form that would accept the images and store them into an array. The problem is whenever I try inserting the images into a table row in the database it displays an error:
"Array to string conversion"
How can I fix this? And also how do I fetch each images on another page from the same database table. Below is my code.
-Form code
<form method="post" enctype="multipart/form-data" >
<input required type="text" name="name">
<input required type="text" name="location">
<input required type="text" name="status">
<select required name="category">
<option>Category</option>
<option value="construct">Construction</option>
<option value="promgt">Project Development</option>
<option value="archdesign">Architectural Designs</option>
</select>
<textarea required class="form-control" name="descrip" rows="5"></textarea>
<input style="text-align:left" type="file" name="imgs[]" multiple>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
-Addaction.php code
<?php
$db=mysqli_connect("localhost","root","dbpassword","dbname");
if(!empty($_FILES['imgs']['name'][0])){
$imgs = $_FILES['imgs'];
$uploaded = array();
$failed = array();
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = explode('.',$img_name);
$img_ext = strtolower(end($img_ext));
if(in_array($img_ext, $allowed)) {
if($img_error === 0){
if($img_size <= 500000) {
$img_name_new = uniqid('', true) . '.' . $img_ext;
$img_destination = 'img/'.$img_name_new;
if(move_uploaded_file($img_tmp, $img_destination)){
$uploaded[$position] = $img_destination;
}else{
$failed[$position] = "[{$img_name}] failed to upload";
}
}else{
$failed[$position] = "[{$img_name}] is too large";
}
}else{
$failed[$position] = "[{$img_name}] error";
}
}else{
$failed[$position] = "[{$img_name}] file extension";
}
}
if(!empty($uploaded)){
print_r($uploaded);
}
if(!empty($failed)){
print_r($failed);
}
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$location = $_POST['location'];
$status = $_POST['status'];
$descrip = $_POST['descrip'];
$category = $_POST['category'];
$img_name_new = $_FILES['imgs']['name'];
if ($db->connect_error){
die ("Connection Failed: " . $db->connect_error);
}
$sql_u = "SELECT * FROM projects WHERE name='$name'";
$sql_e = "SELECT * FROM projects WHERE category='$category'";
$res_u = mysqli_query($db, $sql_u);
$res_e = mysqli_query($db, $sql_e);
if (mysqli_num_rows($res_u) && mysqli_num_rows($res_e) > 0) {
echo "<div style='margin: 0 80px' class='alert alert-danger' role='alert'> Error. Item Already exists </div>";
header("refresh:3 url=add.php");
}else{
$sql_i = "INSERT INTO items (name, location, status, descrip, imgs, category) VALUES ('$name','$location','$status,'$descrip','$img_name_new','$category')";
}
if (mysqli_query($db, $sql_i)){
echo "Project Added Successfully";
}else{
echo mysqli_error($db);
}
$db->close();
}
?>
$img_name_new = $_FILES['imgs']['name'] is an array of one or more image names.
You will need to decide how you wish to store the array data as a string in your database.
Here are a couple of sensible options, but choosing the best one will be determined by how you are going to using this data once it is in the database.
implode() it -- $img_name_new = implode(',', $_FILES['imgs']['name']);
json_encode() it -- $img_name_new = json_encode($_FILES['imgs']['name']);
And here is my good deed for the year...
Form Script:
<?php
if (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} else {
if ($result = $db->query("SELECT name FROM items")) {
for ($rows = []; $row = $result->fetch_row(); $rows[] = $row);
$result->free();
?>
<script>
function checkName() {
var names = '<?php echo json_encode($rows); ?>';
var value = document.forms['project']['name'].value;
if (names.indexOf(value) !== -1) { // might not work on some old browsers
alert(value + ' is not a unique name. Please choose another.');
return false;
}
}
</script>
<?php
}
?>
<form name="project" method="post" enctype="multipart/form-data" onsubmit="return checkName()">
Name: <input required type="text" name="name"><br>
Location: <input required type="text" name="location"><br>
Status: <input required type="text" name="status"><br>
Category: <select required name="category">
<?php
if ($result = $db->query("SELECT category, category_alias FROM categories")) {
while ($row = $result->fetch_assoc()) {
echo "<option value=\"{$row['category']}\">{$row['category_alias']}</option>";
}
}
?>
</select><br>
<textarea required class="form-control" name="descrip" rows="5"></textarea><br>
<input style="text-align:left" type="file" name="imgs[]" multiple><br>
<button type="submit" name="submit" formaction="addaction.php">Add Project</button>
</form>
<?php
}
*notice that I have made a separate category table for validation.
Submission Handling Script: (addaction.php)
<?php
if (isset($_POST['submit'], $_POST['name'], $_POST['location'], $_POST['status'], $_POST['descrip'], $_POST['category'], $_FILES['imgs']['name'][0])) {
$paths = [];
if (!empty($_FILES['imgs']['name'][0])) {
$imgs = $_FILES['imgs'];
$allowed = array('jpg', 'png');
foreach($imgs['name'] as $position => $img_name){
$img_tmp = $imgs['tmp_name'][$position];
$img_size = $imgs['size'][$position];
$img_error = $imgs['error'][$position];
$img_ext = strtolower(pathinfo($img_name)['extension']);
if (!in_array($img_ext, $allowed)) {
$errors[] = "File extension is not in whitelist for $img_name ($position)";
} elseif ($img_error) {
$errors[] = "Image error for $img_name ($position): $image_error";
} elseif ($img_size > 500000) {
$errors[] = "Image $image_name ($position) is too large";
} else {
$img_destination = 'img/' . uniqid('', true) . ".$img_ext";
if (!move_uploaded_file($img_tmp, $img_destination)) {
$errors[] = "Failed to move $img_name ($position) to new directory";
} else {
$paths[] = $img_destination;
}
}
}
}
if (!empty($errors)) {
echo '<ul><li>' , implode('</li><li>', $errors) , '</li></ul>';
} elseif (!$db = new mysqli("localhost", "root", "", "db")) { // declare and check for a falsey value
echo "Connection Failure"; // $db->connect_error <-- never show actual error details to public
} elseif (!$stmt = $db->prepare("SELECT COUNT(*) FROM categories WHERE category = ?")) {
echo "Prepare Syntax Error"; // $db->error; <-- never show actual error details to public
} elseif (!$stmt->bind_param("s", $_POST['category']) || !$stmt->execute() || !$stmt->bind_result($found) || !$stmt->fetch()) {
echo "Category Statement Error"; // $stmt->error; <-- never show actual error details to public
} elseif (!$found) {
echo "Category Not Found - Project Not Saved";
} else {
$stmt->close();
$cs_paths = (string)implode(',', $paths);
// Set the `name` column in `items` to UNIQUE so that you cannot receive duplicate names in database table
if (!$stmt = $db->prepare("INSERT INTO items (name, location, status, category, descrip, imgs) VALUES (?,?,?,?,?,?)")) {
echo "Error # prepare"; // $db->error; // don't show to public
} elseif (!$stmt->bind_param("ssssss", $_POST['name'], $_POST['location'], $_POST['status'], $_POST['category'], $_POST['descrip'], $cs_paths)) {
echo "Error # bind"; // $stmt->error; // don't show to public
} elseif (!$stmt->execute()) {
if ($stmt->errno == 1062) {
echo "Duplicate name submitted, please go back to the form and change the project name to be unique";
} else {
echo "Error # execute" , $stmt->error; // $stmt->error; // don't show to public
}
} else {
echo "Project Added Successfully";
}
}
}

move_uploaded_file not uploading image

I am trying to upload a file to an images folder and also insert the directory path into a mysql db.
Here is my HTML form
<form enctype="multipart/form-data" method="post" action="newfacility.php">
<fieldset>
<legend>New Facility</legend>
...
<label for="photo">Facility Photo:</label>
<input type="file" id="facilityphoto" name="facilityphoto" /><br />
<label for="province">Photo Description:</label>
<input type="text" id="photodesc" name="photodesc" /><br />
....
<input type="submit" value="Create" name="submit" />
</fieldset>
</form>
newfacility.php
require_once('../appvars.php');
require_once('upload_image.php');
//connect to db and test connection.
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (!$dbc) {
die("Connection failed: " . mysqli_connect_error());
}
if (isset($_POST['submit'])) {
// Grab the user data from the POST
$facilityNumber = mysqli_real_escape_string($dbc, trim($_POST['facilitynumber']));
....
....
//This is defined in appvars.php -- define('MM_UPLOADPATH', 'images/');
//facility photo
$facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
$facilityPhotoDesc = mysqli_real_escape_string($dbc, trim($_POST['photodesc']));
// check if the faciliy info already exists.
if (!empty($facilityNumber) && !empty($facilityName) && !empty($facilityAddress) && !empty($facilityCity)) {
$query = "SELECT * FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
. "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";
$data = mysqli_query($dbc, $query);
//if the facility is unique insert the data into the database
if (mysqli_num_rows($data) == 0) {
//insert into facility table
$query = "INSERT INTO facility (facility_id, account_id, facility_number, facility_name, facility_address,"
. " facility_city, facility_province, facility_postal_code, facility_photo, facility_roof_plan,"
. " facility_roof_size, facility_roof_size_inspected, facility_last_inspected_date, facility_inspected_by)"
. " VALUES (NULL, '$selectedAssocAccount', '$facilityNumber', '$facilityName', '$facilityAddress', "
. "'$facilityCity', '$facilityProvince', '$facilityPostalCode', '$facilityRoofSize', "
. "'$facilityRoofSizeInspected', '$facilityDayInspected', '$facilityInspectedBy')";
mysqli_query($dbc, $query);
//query used to get the facility_id of the facility we had just entered -- I haven't tested this yet.
$getFacilityID = "SELECT facility_id FROM facility WHERE facility_number = '$facilityNumber' AND facility_name = '$facilityName' "
. "AND facility_address = '$facilityAddress' AND facility_city = '$facilityCity'";
$facilityID = mysqli_query($dbc, $getFacilityID);
//insert into photo table
$photoQuery = "INSERT INTO photo (photo_id, facility_id, photo, photo_desc)"
. "VALUES (NULL, $facilityID, $facilityPhoto, $facilityPhotoDesc)";
mysqli_query($dbc, $photoQuery);
// Confirm success with the user
echo '<p>You have succesfully created a new facility. '
. 'Please go back to the admin panel.</p>';
//testing to see if I can view the image
echo '<img class="profile" src="' . MM_UPLOADPATH . $facilityPhoto . '"/>';
//close db connection
mysqli_close($dbc);
exit();
}
And finally here is upload_image.php
if(isset($_FILES["facilityphoto"])) {
// Check if file already exists
if (file_exists($facilityPhoto)) {
echo "Sorry, facility photo already exists.";
}
if($_FILES['facilityphoto']['error'] !==0) {
echo "Error uploading facility photo image.";
} else {
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading the facility photo.";
}
}
}
So the error I keep hitting right now is: echo "Sorry, there was an error uploading the facility photo.";
I don't understand what I am doing wrong here that is resulting in the image not being uploaded into my images/ directory.
I am going to provide an answer that addresses only the file upload problem, all the database stuff is striped from the answer as it is not relevant.
// returns true only if the file was written to $to,
// the value of $status_msg will be a user friendly string
// representing the outcome.
function save_facility_photo($from, $to, &$status_msg) {
// Check if file already exists
if (file_exists($to)) {
$status_msg = "Sorry, facility photo already exists.";
return false;
}
if (move_uploaded_file($from, $to)) {
$status_msg = "The file ".basename($to)." has been uploaded.";
return true;
}
$status_msg = "Sorry, there was an error uploading the facility photo.";
return false;
}
if (isset($_POST['submit'])) {
define('MM_UPLOADPATH', 'images/');
$facilityPhoto = MM_UPLOADPATH . basename($_FILES["facilityphoto"]["name"]);
if ($_FILES['facilityphoto']['error'] == UPLOAD_ERR_OK) {
$status_msg = '';
$from = $_FILES["facilityphoto"]["tmp_name"];
$saved = save_facility_photo($from, $facilityPhoto, $status_msg);
}
else {
// handle upload error
}
// continue with code
}
The following is an explanation of what I think is happening in your scripts.
At the top of newfacility.php, require_once('upload_image.php'); is called. Now lets step though upload_image.php noting that $facilityPhoto has not yet been defined
// this is very likely true
if(isset($_FILES["facilityphoto"])) {
// $facilityPhoto is undefined so file_exists(NULL) will return false
if (file_exists($facilityPhoto)) { }
// the image upload was probably successful, so we jump to the else branch
if($_FILES['facilityphoto']['error'] !==0) {
}
else {
// $facilityPhoto is undefined move_uploaded_file('p/a/t/h', NULL)
// will return false, so we jump to the else branch
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)) {
}
else {
// resulting in this error
echo "Sorry, there was an error uploading the facility photo.";
}
}
}
Replace these lines:
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], $facilityPhoto)){
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}
with these:
if (move_uploaded_file($_FILES["facilityphoto"]["tmp_name"], 'images/'. $_FILES["facilityphoto"]["name"])){
echo "The file ".( $_FILES["facilityphoto"]["name"]). " has been uploaded.";
}

How to get Mysqli image in database to show up in div

The div that I want the image to be displayed in (form is sent to send_post.php):
<div style="width:200px ; height: 200px ; border:1px dashed red ; display:inline-block ; margin-top:5px ; margin-left:5px" class="postedBy"></div><!--end image-->
This aforementioned div is located inside this container div:
<div style="height:800px ; width:800px ; border:1px dashed black ; margin-left:200px ; float:left ; margin-top:50px" id= "profilePosts"></div>
Code from send_post.php:
<?php
session_start();
if(!isset($_SESSION['username'])) {
header('location: mustLogin.php');
} else {
$username = $_SESSION['username'];
}
$title = $_POST['title'];
$description = $_POST['description'];
$image = $_POST['image'];
$dateAdded = date('Y-m-d');
$addedBy = $username;
if (!empty('title') && !empty('description') && !empty('image')) {
//establish connection to SQL
$conn = mysqli_connect("localhost", "root", "") or die ("Couldn't connect to SQLI");
//connect to DB
mysqli_select_db($conn, "accounts") or die ("Couldn't find DB");
$sqliCommand = "INSERT INTO `posts` (title, description, image, date_added, added_by) VALUES ('$title', '$description', '$image', '$dateAdded', '$addedBy')" or die ('Info couldnt go to database');
mysqli_query($conn, $sqliCommand) or die ('MySQLI error');
header('location: profile.php?user='.$username);
} else {
header('location: error.php');
}
?>
The info get's sent to the database just fine, but can someone explain to me how I can get the images added by the user (all of them) to display in the first div I listed?
You need to create a separate url just to return the retrieved image from DB by image type in header
So after your selection in a for loop you can have something like
<?php
$sqliCommand = "SELECT * FROM `posts` WHERE `added_by` = '{$this->username}'";
$result = mysqli_query($conn, $sqliCommand);
while ($row = mysqli_fetch_assoc($result)) {
?>
<div style="width:200px ; height: 200px ; border:1px dashed red ; display:inline-block ; margin-top:5px ; margin-left:5px" class="postedBy">
<img src="/imgView.php?imgId=<?php echo $row['id'] ?>"
</div>
<?php
}
?>
Now what you need is to create a page for imgView.php which contains something like
<?php
$imgId = $_GET['imgId'];
if (!empty($imgId)) {
$sqliCommand = "SELECT `image` FROM `posts` WHERE `id` = '$imgId'";
$result = mysqli_query($conn, $sqliCommand);
$row = mysqli_fetch_assoc($result));
header("Content-Type: image/jpeg"); // or whatever the correct content type is.
echo $row['image']; //if your image is encoded you can decode it here, too.
}
?>
I would also recommend to save the MIME type while you are inserting so that you be able to use a proper header Content-Type
Upload form:
<form action="/image_upload.php" method="POST" enctype="multipart/form-data">
<label>Title:</label>
<input type="text" name="title">;
<label>Description:</label>
<textarea name="description"></textarea>
<label>Upload Image:</labe>
<input type="file" name="avatar" accept="image/*">
<button type="submit">Upload</button>
</form>
Upload script (image_upload.php):
session_start();
if(!isset($_SESSION['username']))
{
header('location: mustLogin.php');
exit;
}
else
{
if($_FILES != null) //uploaded files are held in $_FILES array
{
$username = $_SESSION['username'];
$title = $_POST['title'];
$description = $_POST['description'];
$dateAdded = date('Y-m-d');
$addedBy = $username;
if ($title != "" && $description != "" && !empty($_FILES))
{
$new_file_name = uniqid() . "-" . $username . "-upload";
$file_path = 'images/' . $new_file_name; //images haves to be a directory in the same directory that this script runs
$uploaded_file = move_uploaded_file($_FILES['tmp_name'], $file_path );
if($uploaded_file == TRUE)
{
$conn = mysqli_connect("localhost", "root", "") or die ("Couldn't connect to SQLI");
//connect to DB
mysqli_select_db($conn, "accounts") or die ("Couldn't find DB");
/* You should change this while query to a prepared statement for security reasons */
$sqliCommand = "INSERT INTO `posts` (title, description, image, date_added, added_by) VALUES ('$title', '$description', '$file_path', '$dateAdded', '$addedBy')" or die ('Info couldnt go to database');
mysqli_query($conn, $sqliCommand) or die ('MySQLI error');
header('location: profile.php?user='.$username);
}
else
{
echo "Could not upload file.";
}
}
else
{
echo "Missing title or description, or file array is empty.";
}
}
else
{
echo "No file uploaded.";
}
}
Display images in profile:
session_start();
$username = $_SESSION['username'];
$conn = new mysqli("localhoast", "root", "", "accounts") or die('Connect Error (' . $conn->connect_errno . ') ' . $conn->connect_error);
$sql = "SELECT * FROM `posts` WHERE added_by = ?";
$query = $conn->stmt_init();
$query = $query->prepare($sql);
$query->bind_param('s',$username);
$query->execute();
$images = $query->get_result();
if($images->num_rows > 0)
{
while($image = $images->fetch_assoc())
{
?>
<div style="width:200px ; height: 200px ; border:1px dashed red ; display:inline-block ; margin-top:5px ; margin-left:5px" class="postedBy">
<img src="<?php echo $image['image']; ?>">
</div><!--end image-->
<?php
}
}
You should upload the images to a directory, then keep track of where these images are in the database. Then just link to those images from the information you get out of the database. I didnt test this but the algorithm should all be there. I would suggest changing your insert query to a prepared statement, like i used in the profile section, and you might want to look into something like https://github.com/samayo/bulletproof to make sure people don't upload files which are not actually images.

Problems with inserting image into table of blob type

Having problems with inserting image into table of blob type. If I insert it manually by phpmyadmin, and print it, I can get the image, but with this code I can't insert into table. On localhost it works, but on the server doesn't. Can you please help. I've already searched the forums, but couldn't get correct answer.
Here's the code:
<form action="index.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="upload">
</form>
<?php
$file = $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select some image";
else
{
$image_name = mysql_real_escape_string($_FILES['image']['name']);
$image = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE)
{
echo "That's not an image";
}
else
{
if (!$insert = mysql_query("insert into image(id, name, image) values ('','$image_name','$image')"))
{
echo "Problem uploading image";
}
else
{
$res = mysql_query("SELECT * FROM image ");
while ($row = mysql_fetch_assoc($res))
{
echo "<img src=data:image/jpeg;base64," . (base64_encode(($row['Image']))) . " style='width:60px;height:60px;'>";
}
}
}
}
?>
If I echo the $row['Image'] the result is like this: "?PNG IHDR??vlH cHRMz%??????u0?`:?o?" and etc.
You have not even used image_size in your so don't need to define it, and on other hand you are not storing the file path into db. first define file path of the image and then store it, else refer this Reference site
and Update your query
("insert into image(id, name, Image) values (null,'$image_name','$image')")
I think you are not opening a database connection before querying
$con = mysql_connect("localhost","mysql_user","mysql_pwd");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$query = "your query";
mysql_query($query,$con);
and also use
header("Content-type: image/jpeg");
before echoing the image.
Solved in PDO
$pdo = new PDO('mysql:dbname=database_name;host=localhost', 'username', 'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'));
$imageName = mysql_real_escape_string($_FILES["image"]["name"]);
$imageData = file_get_contents($_FILES["image"]["tmp_name"]);
$imageType = mysql_real_escape_string($_FILES["image"]["type"]);
$stmt = $pdo->prepare('INSERT INTO image (name,image) VALUES (:name,:image)');
$stmt->bindParam(':image', $imageData, PDO::PARAM_LOB);
$stmt->bindParam(':name', $imageName);
$stmt->execute(array('name' => $imageName, 'image' => $imageData));
echo "Image Uploaded";
$res = mysql_query("SELECT * FROM image ");
while ($row = mysql_fetch_assoc($res))
{
echo "<img src=data:image/jpeg;base64," . (base64_encode(($row['image']))) . " style='width:60px;height:60px;'>";
}

Import CSV data to fields in MySQL Database

I am trying to upload a CSV file which contains the fields stated in the link below [see CSV example] via a web form. The user can browse their computer by clicking the upload button, select their CSV file and then click upload which then imports the CSV data into the database in their corresponding fields. At the moment when the user uploads their CSV file, the row is empty and doesn't contain any of the data that the CSV file contains. Is there a way i could solve this so that the data inside the CSV file gets imported to the database and placed in its associating fields?
CSV example:
http://i754.photobucket.com/albums/xx182/rache_R/Screenshot2014-04-10at145431_zps80a42938.png
uploads.php
<!DOCTYPE html>
<head>
<title>MySQL file upload example</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
<form action="upload_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
<p>
See all files
</p>
</body>
</html>
upload_file.php
<?php
// Check if a file has been uploaded
if(isset($_FILES['uploaded_file'])) {
// Make sure the file was sent without errors
if($_FILES['uploaded_file']['error'] == 0) {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'vario007', 'spineless');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$filedata= file_get_contents($_FILES ['uploaded_file']['tmp_name']); //this imports the entire file.
// Create the SQL query
$query = "
INSERT INTO `Retail` (
`date`, `order_ref`, `postcode`, `country`, `quantity`, `packing_price`, `dispatch_type`, `created`
)
VALUES (
'{$date}', '{$order_ref}', '{$postcode}', '{$country}', '{$quantity}', '{$packing_price}', '{$dispatch_type}', NOW()
)";
// Execute the query
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
try this
<?php
if(isset($_FILES['uploaded_file'])) {
if($_FILES['uploaded_file']['error'] == 0) {
$dbLink = new mysqli('localhost', 'root', 'vario007', 'spineless');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
$file = $_FILES ['uploaded_file']['tmp_name'];
$handle = fopen($file, "r");
$row = 1;
while (($data = fgetcsv($handle, 0, ",","'")) !== FALSE)
{
if($row == 1)
{
// skip the first row
}
else
{
//csv format data like this
//$data[0] = date
//$data[1] = order_ref
//$data[2] = postcode
//$data[3] = country
//$data[4] = quantity
//$data[5] = packing_price
//$data[6] = dispatch_type
$query = "
INSERT INTO `Retail` (
`date`, `order_ref`, `postcode`, `country`, `quantity`, `packing_price`, `dispatch_type`, `created`
)
VALUES (
'".$data[0]."', '".$data[1]."', '".$data[2]."', '".$data[3]."', '".$data[4]."', '".$data[5]."', '".$data[6]."', NOW()
)";
$result = $dbLink->query($query);
// Check if it was successfull
if($result) {
echo 'Success! Your file was successfully added!';
}
else {
echo 'Error! Failed to insert the file'
. "<pre>{$dbLink->error}</pre>";
}
}
$row++;
}
}
else {
echo 'An error accured while the file was being uploaded. '
. 'Error code: '. intval($_FILES['uploaded_file']['error']);
}
// Close the mysql connection
$dbLink->close();
}
else {
echo 'Error! A file was not sent!';
}
// Echo a link back to the main page
echo '<p>Click here to go back</p>';
?>
fgetcsv() in third argument in separator to you want to save in csv file. Ex: comma,semicolon or etc.
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
$filedata= csv_to_array($_FILES ['uploaded_file']['tmp_name']);
foreach($filedata as $data)
{
$sql = "INSERT into table SET value1='".$data['value1']."'......";
}

Categories