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.
Related
I would like to save some data from pgsql database to a csv file. The thing you also should know that I'm working at ZF2 Framework. So the code looks like this:
$adapter = $this->serviceMenager->get('db');
$adapter->query("Copy (Select * From data.my_data) To '/test.csv' With CSV;")->execute();
But while I'm trying to execute the code, I'm getting exception:
SQLSTATE[42501]: Insufficient privilege: 7 ERROR: could not open file "/test.csv" for writing: Permission denied
That was the thing that I was expecting, because the only writing path is the public folder with privilages 777. But if I execute:
$adapter->query("Copy (Select * From data.my_data) To '/public/test.csv' With CSV;")->execute();
I'm getting exception:
SQLSTATE[58P01]: Undefined file: 7 ERROR: could not open file "/public/test.csv" for writing: No such file or directory
How to determine where am I (I mean current path)? And how to properly set the path in the query to export my data?
Thanks in advice.
It seems to be executed on PGSQL and not MYSQL as ins0 said.
The problem is almost what he stated though. You are trying to write to /test.csv, which means for PGSQL the root of the Unix server. You need to give the path you really want, and you can actually get the root of your app with getcwd.
Then your code will look like this:
$adapter = $this->serviceMenager->get('db');
$file = getcwd()."/public/test.csv";
$adapter->query("Copy (Select * From data.my_data) To '". $file ."' With CSV;")->execute();
When the submit button is pressed,the isset($_POST['ta'] works,but the file is not updated inside database with '---------'. any suggestion where I am going wrong?
if ( isset( $_POST['ta'] ) ) {
$handle = fopen('saw42.TextGrid', "a");
require('db_connection.php');
fwrite( $handle, "-----------");
fclose( $handle );
}
try this
if(isset($_POST['ta'])){
$handle=fopen('saw42.TextGrid',"a");
require('db_connection.php'); // don't know why this line is here
if ($handle===false){
echo 'Unable to open file';
}else{
fwrite($handle,"-----------");
fclose($handle);
}
}
Try to check your permissions on Unix OS , Is your file is 0644 or 0444
I pressume, the require-line fails and so the file is opened, but the script is aborted before something gets written inside. If errors are turned of (as is on some preconfigured systems), no error message will be shown.
Nevertheless the question is a bit confusing, since if a database (in the sense of a relational database system accessable through a database server) is meant, the code should not use any fopen-calls. If the 'database' is a simple file, the requirement of the db_connection.php seems to be unclear.
To clarify things a bit:
A (relational) database is a collection of tables (relations) that perhaps refer to each other. Such databases are typically filled and asked via SQL-language or some object-oriented interface (MySQL, MS-SQL, SQLITE, ...)
A database in the sense of 'some data' can also reference a simple file. In this case, you have to organize data by yourselves and use file access methods to access it.
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
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
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.