Download file which was upload to mysql to server directory - php

I've searched and searched but have not found a script capable of downloading files which are uploaded to my mysql database down to a directory in my server.
This is only temporary and once the file has been used it'll need to be disposed of.
Got any ideas?

I suppose you meant that the file is saved into mysql database like BLOB (binary data)
$result = mysql_query("select * from tablename where id=XXXX");
if (mysql_num_rows($result)>0){
$r = mysql_fetch_array($result,MYSQL_ASSOC);
file_put_contents($filename,$r['column_blob']);
}
I used file_put_contents function that it is binary safe, but there is also fwrite

Related

Save file from mysql database to file system

I am storing some doc files in a mysql database that need to be saved to the file system and manipulated, however some of the documents are not opening after saving to the file system.
I am pulling the file from the database as follows:
$load_doc = "SELECT doc_id, `doc_ext`, doc_size, `doc_conten`
FROM `li_webs_trans`.`li_docs` WHERE `doc_id` = '$doc_id'";
$doc = mysql_query($load_doc) or die(mysql_error());
$fp = fopen("/var/www/OCR/temp_doc/preview__".$doc_id .".docx", "w+");
while($row = mysql_fetch_array($doc)){
fwrite($fp, $row['doc_conten']);
}
The doc_content filed is a Long BLOB. The files are all docx files.
Any idea why some files open fine but others don't?

php&mysql fopen cannot open the file

I am using PHP & MySQL to generate a dynamic web page. Now I want to make the search result into a file.
Firstly, I use
$query = "select * from database into outfile 'query.txt'";#mysql($query);
BUt it cannot work;
Then, I try to use the "fopen" function.
$fp=fopen("query.txt","w+") or exit("Unable to open file!");
if($result_specific){
while( $row = mysql_fetch_array( $result_specific,MYSQL_ASSOC )){
echo fwrite($fp,$row["p1"]."\t".$row["p2"]."\t".$row["p3"]."\n");
}
}
fclose($fp);
Unfortunately, it tells me "Unable to open file!".
Maybe it is a wrong Url?
But I don't know how to specify the correct URL.
select * from database into outfile 'query.txt'
You haven't specified a path - only a filename. The file will be written to the current working directory of the MySQL instance. It will be written with the uid of the the user running the instance. It's impossible to say from the information you've provided what permissions the resultant file will have - on a Linux/BSD/Posix system the permissions will be based on he the umask inherited by the DBMS instance.
$fp=fopen("query.txt","w+")
Is you PHP looking in the right directory? What are the permissions on the file?
or exit("Unable to open file!");
That 'or' will not do what you think it does - should be '||'
if($result_specific){
...
What has this got to do with the problem?
Go back and use full paths and check the permissions.

PHP: retrieving full path from a selected file to import data to database

I want to allow the user to select a file from which data is exported and saved into a database. I found the following code to import the data:
$fp = fopen("people.csv", "r");
while ($line = fgets($fp)) {
$char = split("\t",$line,4);
list($name, $age,$height,$date) = $char;
//Split the line by the tab delimiter and store it in our list
$sql = "insert into people(name,age,height,date) values('$name','$age','$height','$date')"; // Generate our sql string
mysql_query($sql) or die(mysql_error()); // Execute the sql
//fclose($line);
I'm not sure if it works but i'm yet to get that far. My question is how do I get the full path name of the selected file so I can feed it into the following command rather than hard coding the filename:
$fp = fopen("people.csv", "r");
I have spent alot time researching this but to no avail.
If you want to let users upload this file, you should implement file upload. Please check W3Schools Tutorial for instructions.
The main idea is to get file path from $_FILES["file"]["tmp_name"]:
$fp = fopen($_FILES["file"]["tmp_name"], "r");
If you store your file statically in your web project folder, you can use the path including your DOCUMENT_ROOT:
$path = $_SERVER["DOCUMENT_ROOT"] + 'relative/path/to/your/file/' + 'people.csv';
You can obtain the path of the current file via the __DIR__ magic constant;
Magic constants
In your case;
echo __DIR__ . 'people.csv';
Also, you may consider using the built-in CSV functions that PHP offers;
http://php.net/manual/en/function.fgetcsv.php
If you want to skip processing the file via PHP altogether, MySQL offers ways to directly import data from a CSV file;
https://dev.mysql.com/doc/refman/5.5/en/load-data.html

SugarCRM save database data to file

Is there any way I can save the data of a specific table of the sugarcrm database into a doc file ?
I have a custom module with username,some notes and date. I want to write this into the database and into a file as well.
Its not just a php file. I want to use logic hooks and write the code. I want to use the logic hooks to access database and then write the data into the file.
Thanks in advance
Saving as a DOC file probably isn't the best idea, since it is primarily used for formatting information. A standard .txt file is usually what you would use for such a process.
With that said, there isn't any methods built into sugar that will let you do this. You will need to build the capability into the module.
What exactly are you attempting to accomplish? There is a very powerful auditing tool set, which is good for seeing revisions to a module object. If you are just wanting to monitor changes to the table, you can setup logging for that table/database inside of SQL.
+++Ok, if you are just looking to write to a file after saves, follow the instructions at: http://cheleguanaco.blogspot.com/2009/06/simple-sugarcrm-logic-hook-example.html for a quick how-to on getting the logic hooks working. You are going to want to make a php file that simply uses the data passed to it via the bean class, and either writes to the file directly from the data within bean, or uses the bean->id parameter to do a SQL query and write to the file from that data.
Also, is this a DOC file that is going to be immediately generated and then destroyed at the end of the transaction? Or is it more of a log file that will be persistent?
++++That is simple enough then
Where you have the Query right now, replace it with:
$file = fopen($pathAndNameOfFile, 'a+') or die('Could not open file.');
$query = "SELECT * FROM data_base.table";
$result = $bean->db->query($query,true);
$dbRowData = $bean->db->mysql_fetch_assoc($result);
$printedArray = print_r($dbRowData);
fwrite($file, $printedArray) or die('Could not write to file.');
fclose($file);
*A quick note, you might need to set permissions in order to be able to read/write to the file, but those are specific to the machine type, so if you encounter errors with either do a search for setting permissions for your particular server type.
**Also, 'SELECT * FROM database.table' is going to return ALL of the rows in the entire table. This will generate a very large file, and be a performance hindrance as the table grows. You should use the bean class to update the last saved tuple:
$file = fopen($pathAndNameOfFile, 'a+') or die('Could not open file.');
$query = "SELECT * FROM data_base.table WHERE id = '".$focus->id."';";
$result = $bean->db->query($query,true);
$dbRowData = $bean->db->mysql_fetch_assoc($result);
$printedArray = print_r($dbRowData);
fwrite($file, $printedArray) or die('Could not write to file.');
fclose($file);
You can export/dump mysql databases into SQL files using mysqldump
mysqldump -u userName -p databaseName tableName > fileName.sql

PHP MySQL OUTFILE command

If I use the following in a mysql_query command:
SELECT *
FROM mytable
INTO OUTFILE '/tmp/mytable.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
Where is the tmp file relative to, to the MySQL database somehow or to the PHP file?
If it does not exist will it be created?
If I would like it to appear 1 folder up from the PHP file which does it, how would I do that?
According to The Documentation On Select, it's stored on the server and not on the client:
The SELECT ... INTO OUTFILE 'file_name' form of SELECT writes the selected rows to a file. The file is created on the server host, so you must have the FILE privilege to use this syntax. file_name cannot be an existing file, which among other things prevents files such as /etc/passwd and database tables from being destroyed. As of MySQL 5.0.19, the character_set_filesystem system variable controls the interpretation of the file name.
And, more to the point:
The SELECT ... INTO OUTFILE statement is intended primarily to let you very quickly dump a table to a text file on the server machine. If you want to create the resulting file on some other host than the server host, you normally cannot use SELECT ... INTO OUTFILE since there is no way to write a path to the file relative to the server host's file system.
So, don't use it in production to generate CSV files. Instead, build the CSV in PHP using fputcsv:
$result = $mysqli->query($sql);
if (!$result) {
//SQL Error
}
$f = fopen('mycsv.csv', 'w');
if (!$f) {
// Could not open file!
}
while ($row = $result->fetch_assoc()) {
fputcsv($f, $row);
}
fclose($f);
Where is the tmp file relative to?
A: The file will have the result of the select * from mytable
If it does not exist will it be created?
A: yes
If I would like it to appear 1 folder up from the php file which does it, how would I do that?
A: if you want one folder up from the fileYouAreRunning.php then make path like that: "../mytable.csv"
Your current query has an absolute path. So the outfile will not be relative to anything, but saved to /tmp/mytable.csv.
I'd say, the safest bet would be to keep useing absolute paths, so check in your php what your absolute path to the parent is, and then add this to your query using a variable.

Categories