Create zip archive out of file from MySQL using PHP - 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);
}
}

Related

Error query failed , check manual line 3

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.';
}
?>

How to get an array of all rows in column A in an Excel file using PHPExel?

I have a list on an Excel file of phone numbers (A row).
How do I get it as an array using PHPExel?
Can I get a whole example including a small explanation of which file from the 'Class' directory I should 'include_once'? How do I know which .php file to include? How do I scan the list?
<?php
/************************ YOUR DATABASE CONNECTION START HERE ****************************/
define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", "root"); // set database user
define ("DB_PASS",""); // set database password
define ("DB_NAME","database Name here"); // set database name
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
$databasetable = ""; // your table name
/************************ YOUR DATABASE CONNECTION END HERE ****************************/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel-develop\Classes\PHPExcel\IOFactory.php';
$targetfolder = "";
$targetfolder = $targetfolder . basename( $_FILES['fileToUpload']['name']) ;
if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $targetfolder))
{
echo "The file ". basename( $_FILES['fileToUpload']['name']). " is uploaded";
}
else
{
echo "Problem uploading file";
print $targetfolder . basename( $_FILES['fileToUpload']['name']) ;
}
$inputFileName = basename( $_FILES['fileToUpload']['name']);
try
{
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
}
catch(Exception $e)
{
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++)
{
$value1 = trim($allDataInSheet[$i]["A"]);
$Value2 = trim($allDataInSheet[$i]["B"]);
$value3 = trim($allDataInSheet[$i]["C"]);
$query = "SELECT * FROM "; // your select query
$sql = mysql_query($query);
$recResult = mysql_fetch_array($sql);
$exist = $recResult["$value1"];
if($exist=="")
{
$insertTable= mysql_query("//your insert query");
$msg = 'Record has been added.</div>';
}
else
{
$msg = 'Record already exist. </div>';
}
}
?>

load default image if database connection fails

I am attempting to build a database driven site whereby images are loaded via a php script like so;
<img src="get_image.php?holderID=2">
I can get images to load from a folder outside the root directory when the database is accessible but I also want to be able to load a default image if there is a failure with making the database connection. The DB connection is initiated form a separate php connection file mysqli_template_connect.php;
DEFINE('DB_USER', 'someusername');
DEFINE('DB_PASSWORD', 'amnesia');
DEFINE('DB_HOST', 'localhost');
DEFINE('DB_NAME', 'template');
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
and then config.inc.php sets some constants, one of which is for all DB connections;
define('MYSQL', '../../../dbconnect/mysqli_template_connect.php');
The get_image.php file then has a database connection conditional;
require('includes/config.inc.php');
REQUIRE(MYSQL);
$holderID = $_GET['holderID'];
if(!$dbc){
$image_name = 'img/unavailable.png';
$info = getimagesize($image_name);
header("Content-Type: {$info['mime']}\n");
readfile($image_name);
}
else {
$query = "SELECT imageID FROM image_holder WHERE image_holderID = $holderID ";
$result = #mysqli_query($dbc, $query);
$number_rows = mysqli_num_rows($result);
if ($number_rows == 1) {
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$imageID = $row[0];
}
else {
$imageID = FALSE;
}
if ($imageID) {
$query = "SELECT file_name FROM image WHERE imageID = $imageID";
$result = mysqli_query($dbc, $query);
$number_rows = mysqli_num_rows($result);
if ($number_rows == 1) {
$row = mysqli_fetch_array($result, MYSQLI_NUM);
$image_name = '../../../uploads/' . $row[0];
}
else {
$image_name = 'img/unavailable.png';
}
}
else {
$image_name = 'img/unavailable.png';
}
$info = getimagesize($image_name);
header("Content-Type: {$info['mime']}\n");
readfile($image_name);
mysqli_close($dbc);
}
If I disable the MYSQL database in XAMP, the default image unavailable.png will not load even though the header and readfile section of code is virtually the same in the section of code that does work. I'm quite a newbie to all this so any ideas on loading the default image would be appreciated.
Depending on the database object you are using (MySQLi/PDO/etc), you can check if they connected. PDO returns a boolean that you can run against.
Since PDO is the most popular, I will provide an example of that. If you use something else, feel free to comment and I can clarify.
$connected = true;
if (!extension_loaded('PDO'))
{
$connected = false;
}
if (!extension_loaded('pdo_mysql'))
{
$connected = false;
}
try
{
$pdo = new PDO("mysql:host={$host};dbname={$db}", $user, $pass);
}
catch(PDOException $e)
{
$connected = false;
}
if(!$connected){ /* Load default image */ }
Note: just make sure you use the correct image headers.
Instead of
$dbc = #mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
Use
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
hopefully it should work..
I have similar code that do the almost the same thing.
I suspect it was the header, since I have a bit more info added to the header. No harm for you to try out.
header('Content-Description: File Transfer');
header('Content-Type: '. $file_content_type);
header('Content-Length: ' . filesize($file_full_path));
header('Content-Disposition: inline; filename=' . $file_name);
readfile($file_full_path);

Writing a CSV File to SQL

Hope someone can help me with what I think will be something minor (I'm still learning...). I'm trying to write the entire contents of a CSV File server based to an SQL database here is the code I presently have. The line // out writes perfectly and generates a new record. The $ar0 values generate no entries into the table named order - even though the csv file is about 100 lines long I just get
Error: INSERT INTO order (Picker,Order_Number,Timestamp,System)values ('','','','')
$file = "Pal.ORD.csv";
$tbl = "order";
$f_pointer=fopen("$file","r"); // file pointer
while(! feof($f_pointer)){
$ar=fgetcsv($f_pointer);
//$sql="INSERT INTO `order` (Picker,Order_Number,Timestamp,System)values ('Me','9999','23-01-2015','ORD')";
$sql="INSERT INTO `order` (Picker,Order_Number,Timestamp,System)values ('$ar[0]','$ar[1]','$ar[2]','$ar[3]')";
echo $sql;
echo "<br>";
}
if ($connect->query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
What I think may be going on is that your file probably has an empty line/carriage return as the last line in the file and is using that to insert the data as blank entries.
I can't be 100% sure about this since you have not provided a sample of your CSV file, however that is what my tests revealed.
Based on the following CSV test model: (Sidenote: blank lines will be ignored)
a1,a2,a3,a4
b1,b2,b3,b4
c1,c2,c3,c4
Use the following and replace with your own credentials.
This will create a new entry/row for each line found in a given file based on the model I have provide above.
<?php
$DB_HOST = 'xxx';
$DB_USER = 'xxx';
$DB_PASS = 'xxx';
$DB_NAME = 'xxx';
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($db->connect_errno > 0) {
die('Connection failed [' . $db->connect_error . ']');
}
$file = "Pal.ORD.csv";
$delimiter = ',';
if (($handle = fopen("$file", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
foreach($data as $i => $content) {
$data[$i] = $db->real_escape_string($content);
}
// echo $data[$i].""; // test only not required
$db->query("INSERT INTO `order`
(Picker, Order_Number, Timestamp, System)
VALUES ('" . implode("','", $data) . "');");
}
fclose($handle);
}
if($db){
echo "Success";
}
else {
echo "Error: " . $db->error;
}
At a quick glance it seems like this:
$f_pointer=fopen("$file","r"); // file pointer
Should be this:
$f_pointer=fopen($file,"r"); // file pointer
You might not be reading anything from the file. You can try outputting the file contents to see if that part is working, since you've confirmed that you can insert into the DB.

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']

Categories