SugarCRM save database data to file - php

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

Related

php User registration system without mysql database

I want to create a registration system on my site where only limited users will be able to create their account. I want to use a .txt file for storing usernames and passwords.
I have the following code so far :
$uname=$_POST['usr'];
$pass=$_POST['pwd'];
if(empty($_POST["ok"])){echo "Could not insert data!";}
else
{$file=fopen("user.txt","w");
echo fwrite($file,$uname);
fclose($file);}
This receives the user data from a form and puts it in user.txt file.
My problem is that when new data is inserted to txt file the old data get deleted.
I want to keep the data in txt file like
foo:12345~bar:1111
username and password are seprated by : and new user is seprated by ~ ,later I will use regex to get the data from txt file.
How can i correct my code to keep both new and old data?
You need to open file in append mode
http://php.net/manual/en/function.fopen.php
<?php
$uname = $_POST['usr'];
$pass = $_POST['pwd'];
if (empty($_POST["ok"])) {
echo "Could not insert data!";
} else {
$file = fopen("user.txt", "a");
$srt="foo:".$uname."~bar:".$pass;// create your string
echo fwrite($file, $srt);
fclose($file);
}
If we want to add on to a file we need to open it up in append mode.
So you need to change from write only mode to append mode.
$file=fopen("user.txt","a");
To answer your question: you have to explicitly pass $mode argument to fopen() function equals to 'a'.
However, it looks like a bad idea to use plain files for this task. Mainly because of concurent writes troubles.
This is really a bad choice: there are a lot of drawbacks for security, for read/write times, for concurrent requests and a lot more.
Using a database isn't difficult, so my suggestion is to use one.
Anyway, your question is asked yet here: php create or write/append in text file
Simple way to append to a file:
file_put_contents("C:/file.txt", "this is a text line" . PHP_EOL, FILE_APPEND | LOCK_EX);

CodeIgniter - Create multiple databases from master SQL file

What would be the best way to take an .sql file that includes schema and table creation statements and use it to create new databases from within CodeIgniter? What I want to be able to do is use this .sql file as a blueprint for several databases with the same schema, but which may be created at any time.
I imagine I just need to be able to take this file, extract the contents and echo it out into a database query. Is there a better way to do it?
I also need to be able to inject a custom database name into the statements before submitting the query. How would I go about this? Just have a placeholder keyword and do a preg replace with the database name?
Just to ensure all databases are maintained synchronously, I thought perhaps this blueprint schema should be added to CodeIgniter as a module. That way if I need to alter the schema, I can upload a new version of the module with the updated .sql file and perform the necessary migrations across all the databases. Sound reasonable? If so, how would I go about this?
I have done this (run a .sql file) before, and I used this;
$sql = read_file('path/to/file.sql');
$final = '';
foreach(explode("\n", $sql) as $line)
{
if ( isset($line[0]) && $line[0] != '#' )
{
$final .= $line . "\n";
}
}
foreach (explode(";\n", final) as $sql)
{
if ($sql)
{
$this->db->query($sql);
}
}

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.

Edit a file inside database in php

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.

PHP write to included file

I need to include one PHP file and execute function from it.
After execution, on end of PHP script I want to append something to it.
But I'm unable to open file. It's possible to close included file/anything similar so I'll be able to append info to PHP file.
include 'something.php';
echo $somethingFromIncludedFile;
//Few hundred lines later
$fh = fopen('something.php', 'a') or die('Unable to open file');
$log = "\n".'$usr[\''.$key.'\'] = \''.$val.'\';';
fwrite($fh, $log);
fclose($fh);
How to achieve that?
In general you never should modify your PHP code using PHP itself. It's a bad practice, first of all from security standpoint. I am sure you can achieve what you need in other way.
As Alex says, self-modifying code is very, VERY dangerous. And NOT seperating data from code is just dumb. On top of both these warnings, is the fact that PHP arrays are relatively slow and do not scale well (so you could file_put_contents('data.ser',serialize($usr)) / $usr=unserialize(file_get_contents('data.ser')) but it's only going to work for small numbers of users).
Then you've got the problem of using conventional files to store data in a multi-user context - this is possible but you need to build sophisticated locking queue management. This usually entails using a daemon to manage the queue / mutex and is invariably more effort than its worth.
Use a database to store data.
As you already know this attempt is not one of the good ones. If you REALLY want to include your file and then append something to it, then you can do it the following way.
Be aware that using eval(); is risky if you cannot be 100% sure if the content of the file does not contain harmful code.
// This part is a replacement for you include
$fileContent = file_get_contents("something.php");
eval($fileContent);
// your echo goes here
// billion lines of code ;)
// file append mechanics
$fp = fopen("something.php", "a") or die ("Unexpected file open error!");
fputs($fp, "\n".'$usr[\''.$key.'\'] = \''.$val.'\';');
fclose($fp);

Categories