Error query failed , check manual line 3 - php

My upload.php and view.php are working fine but I am not able to create a download links to download files. db name = dbtuts.
and the link for download option is:
<td><a href='download.php?id=<?php echo $row['file_name']; ?>'>Download</a></td>
Here is the code for download.php
<?php
// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID$id
$file_name= ($_GET['id']);
// Make sure the ID is in fact a valid ID
if($file_name == NULL) {
die('The name is invalid!');
}
else {`enter code here`
// Connect to the database
$dbLink = new mysqli('localhost', 'root', "", 'dbtuts');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ".mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT file, type, size
FROM tbl_uploads
WHERE `file` = {$file_name}";
$result = $dbLink->query($query);
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
header("Content-Type: ".$row['type']);
header("Content-Length: ".$row['size']);
header("Content-Disposition: attachment");
// disopsition = attachment to force download request
// Print data
echo $row['data'];
}
else {
echo 'Error! No file exists with that ID.';
}
// Free the mysqli resources
#mysqli_free_result($result);
}
else {
// if there is an error excuting the query
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
// close database connection
#mysqli_close($dbLink);
}
}
else {
// if no ID passed
echo 'Error! No ID was passed.';
}
?>

Related

Create zip archive out of file from MySQL using PHP

I am trying to put a XML file from MySQL database to a zip archive before downloading. I am able to create zip file but Windows is giving error while opening it.
error msg: window cannot open the foler.
filename.zip is invalid
Here is my code:
<?php
if(isset($_GET['id']))
{
$id = intval($_GET['id']);
if($id <= 0) {
die('The id is invalid!');
}
else
{
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'root', 'db');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
$zip = new ZipArchive();
$filename = "export_".date('Y.m.d H.i').".zip";
if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true)
{
echo "Cannot Open for writing";
}
$zip->addEmptyDir('Section');
$query = "SELECT name,data FROM file_section WHERE id ='$id'";
$result = $dbLink->query($query);
if($result->num_rows == 1)
{
// Get the row
$row = mysqli_fetch_array($result);
}
while($row = mysql_fetch_array($result))
{
$zip->addFile($row['data'], "{$row['name']}.xml");
}
$zip->close();
header("Content-disposition: attachment; filename='.$filename'");
header('Content-type: application/zip');
readfile($fileName);
}
// Free the mysqli resources
mysqli_free_result($result);
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
mysqli_close($dbLink);
?>
P.S.: I have limited PHP knowledge.
Test this : create a temp file before addFile your zip object
see http://php.net/manual/en/ziparchive.addfile.php
addFile method wait first parameter a filename (the path to the file to add)
Here is the working solution that I got later. Its valid for one single file id input.
<?php
// Make sure an id was passed
if (isset($_GET['ids'])) {
// Get the id into string (in case of an array)
$id_pass = implode(",",$_GET['ids']);
// Make sure the name is in fact a valid
if ($id_pass <= 0) {
die ('No ID Selected!');
} else
{
// Connect to the database
$dbLink = new mysqli('localhost', 'root', 'password', 'DB Name');
if (mysqli_connect_errno()) {
die("MySQL connection failed: " . mysqli_connect_error());
}
// Fetch the file information
$query = "select id, name, data from datatable where id = {$id_pass};";
$result = $dbLink->query($query);
if ($result) {
// Make sure the result is valid
if ($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
//zip function
$zip = new ZipArchive();
$filename = "export_" . date('Y.m.d H.i.s') . ".zip";
if ($zip->open($filename, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== true) {
echo "Cannot Open for writing";
}
$ext = $row['name'] . ".xml"; // taking file name from DB and adding extension separately
$zip->addFromString($ext, $row['data']); //adding blob data from DB
$zip->close();
header("Content-disposition: inline; filename='.$filename'");
header('Content-type: application/zip');
readfile($filename);
unlink($filename);
}
}
// Free the mysqli resources
mysqli_free_result($result);
mysqli_close($dbLink);
}
}

How to COUNT the number of times a FILE from my database has been downloaded?

I am new to this and I am having problems trying to get my website to count the number of times a files has been downloaded. The website has download buttons linking to the files which are stored on my database, and I would like to be able to count the amount of downloads per file to display as a statistic, ideally once they click the link to download, the column in the files table should be incremented, but I cannot wrap my head around it. please help?
<?php
error_reporting(E_ALL ^ E_NOTICE);
session_start();
$userid = $_SESSION['userid'];
$username= $_SESSION['username'];
?>
<?php
// Make sure an ID was passed
if(isset($_GET['id'])) {
// Get the ID
$id = ($_GET['id']);
// Make sure the ID is in fact a valid ID
if($id <= 0) {
die('The ID is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('dragon.kent.ac.uk', 'repo', '3tpyril', 'repo');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT `mime`, `name`, `size`, `data`
FROM `files`
WHERE `id` = {$id}";
$result = $dbLink->query($query);
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
// Print headers
header("Content-Type: ". $row['mime']);
header("Content-Length: ". $row['size']);
header("Content-Disposition: attachment; filename=". $row['name']);
// Print data
echo $row['data'];
}
else {
echo 'Error! No files exists with that ID.';
}
}
else {
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
#mysqli_close($dbLink);
}
}
else {
echo 'Error! No ID was passed.';
}
?>
The download link would point to a php file, such as download.php?id=123 -- this file would then take the ID and check the downloads database. If the ID exists, you run a query such as UPDATE files SET downloads = downloads + 1 WHERE id = 123.
Afterwards, you set the headers using header() to set content-type. Then use readfile().
See How to force file download with PHP on how to set headers and force a download.
Cheers!

Unable to show Images stored in mySQL using PHP

I am trying to store images in mySQL database and then displaying on the other page. I have this function to store images in mySQL.
function upload() {
include "databaseConnection.php";
$maxsize = 10000000; //set to approx 10 MB
//check associated error code
if ($_FILES['userfile']['error'] == UPLOAD_ERR_OK) {
//check whether file is uploaded with HTTP POST
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
//checks size of uploaded image on server side
if ($_FILES['userfile']['size'] < $maxsize) {
// prepare the image for insertion
$imgData = addslashes(file_get_contents($_FILES['userfile']['tmp_name']));
// put the image in the db...
// database connection
mysql_connect($host, $user, $pass) OR DIE(mysql_error());
// select the db
mysql_select_db($db) OR DIE("Unable to select db" . mysql_error());
// our sql query
$sql = "INSERT INTO carsinfo
(carName, carPicture)
VALUES
('{$_FILES['userfile']['name']}', '{$imgData}');";
// insert the image
mysql_query($sql) or die("Error in Query: " . mysql_error());
$msg = '<p>Image successfully saved in database with id =' . mysql_insert_id() . ' </p>';
} else {
// if the file is not less than the maximum allowed, print an error
$msg = '<div>File exceeds the Maximum File limit</div>
<div>Maximum File limit is ' . $maxsize . ' bytes</div>
<div>File ' . $_FILES['userfile']['name'] . ' is ' . $_FILES['userfile']['size'] .
' bytes</div><hr />';
}
}
else
$msg = "File not uploaded successfully.";
}
else {
$msg = file_upload_error_message($_FILES['userfile']['error']);
}
return $msg;
}
And this code to show iamges.
<?php
include "databaseConnection.php";
// just so we know it is broken
error_reporting(E_ALL);
// some basic sanity checks
//connect to the db
$link = mysql_connect("$host", "$user", "$pass") or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("$db") or die(mysql_error());
// get the image from the db
$sql = "SELECT carPicture FROM carsinfo;";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
$row = mysql_fetch_assoc($result);
// set the header for the image
echo $row['carPicture'];
header("Content-type: image/jpeg");
// close the db link
mysql_close($link);
?>
When this code is run, nothing is shown on the page, even if I write some HTML inside this code, empty page is shown.
I assume you are saving the image content as blob and if your sql is returning the correct data then you can display as
header("Content-type: image/jpeg");
echo $row['carPicture'];
You need to add the header first before the image.
or
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['carPicture']) . '">';
do not write
include databaseConnection.php
nothing include anything.

file download using mysql and PHP

I am creating PHP page that allows users to download files when they click in this button:
<td><a href='download.php?id={$row['file_name']}'>Download</a></td>
then the page redirect to download.php, code:
<?php
// Make sure an ID was passed
if(isset($_GET['file_name'])) {
// Get the ID$id
$file_name= ($_GET['file_name']);
// Make sure the ID is in fact a valid ID
if($file_name == NULL) {
die('The name is invalid!');
}
else {
// Connect to the database
$dbLink = new mysqli('localhost', 'root', "", 'db_name');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ".mysqli_connect_error());
}
// Fetch the file information
$query = "
SELECT `type`, `file_name`, `size`, `data`
FROM `pdfs`
WHERE `file_name` = {$file_name}";
$result = $dbLink->query($query);
if($result) {
// Make sure the result is valid
if($result->num_rows == 1) {
// Get the row
$row = mysqli_fetch_assoc($result);
header("Content-Type: ".$row['type']);
header("Content-Length: ".$row['size']);
header("Content-Disposition: attachment");
// disopsition = attachment to force download request
// Print data
echo $row['data'];
}
else {
echo 'Error! No file exists with that ID.';
}
// Free the mysqli resources
#mysqli_free_result($result);
}
else {
// if there is an error excuting the query
echo "Error! Query failed: <pre>{$dbLink->error}</pre>";
}
// close database connection
#mysqli_close($dbLink);
}
}
else {
// if no ID passed
echo 'Error! No ID was passed.';
}
?>
however, wehn i click in download i always get the massage of the last else statement "error no id was passed", but i can't find the problem, is the problem that i made the primary key of the file is the name??
If your link looks like this:
<a href='download.php?id={$row['file_name']}'>
Then the GET variable will be 'id' as in $_GET['id'] and not $_GET['file_name']
$_GET['file_name'] should be $_GET['id']
since <a href='download.php?id={$row['file_name']}'> you sending "id" not "file_name"
Typo
<td><a href='download.php?id=<?php echo $row['file_name']; ?>'>Download</a></td>
<a href='download.php?id={$row['file_name']}'>
u should use <a href="download.php?id=<?= $row['file_name'];?>">
then use $_GET['id'] since id is the variable u pass in url not $_GET['file_name']

Upload files from IPhone/IPad to mysql DB?

I've been searching a lot about managing data on IOS and finally i build an app that downloads PDF archives,when the user download a PDF the archive is displayed on a UITableView and the user can see the PDF.Now i need do to the most important thing to my project,upload those archives to my MYSQL DB!I've found an very busy tutorial on a website,but the app just upload images,so if anyone know,how can i upload PDF archives!Any tutorial or idea will be helpful!
Thanks in advanced!
PHP SCRIPT:
<?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', 'root', 'fileUP');
if(mysqli_connect_errno()) {
die("MySQL connection failed: ". mysqli_connect_error());
}
// Gather all required data
$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 `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', 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 using the following library to upload your PDF documents: http://allseeing-i.com/ASIHTTPRequest/How-to-use

Categories