Remove occurances of ",,," from MySQL Database Output PHP - php

I am outputting the contents of my MySQL Database into a text file using the below code:
<?php
$host = 'localhost';
$user = 'myusername';
$pass = 'mypassword';
$db = 'mydbname';
$table = 'mytablename';
$file = 'outputfilename';
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");
$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
//$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
$values = mysql_query("SELECT * FROM ".$table."");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].",";
}
$csv_output .= "\n";
}
//echo $csv_output;
$myFile = "output.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $csv_output;
fwrite($fh, $stringData);
fclose($fh);
exit;
?>
However I would like to know how I could replace the occurances of the string ",,," with this: "," before it goes into the text file.

No need for preg_replace().
A simple str_replace will suffice.
$stringData = str_replace(',,,', ',', $csv_output);

problem is in:
$values = mysql_query("SELECT * FROM ".$table."");
if you got ,,,, it means that some columns has no value. Detect those columns, do not include them in SELECT statement.
if you will automatically (preg_replace, str_replace) change multiple commas to one comma, you are on good way to corrupt CSV file.

Use preg_replace(). Something like this (untested):
$pattern = '/\,\,\,/';
$replacement = ',';
echo preg_replace($pattern, $replacement, $stringData);

add this code:
while ($csv_output=str_replace(',,', ',', $csv_output)) echo '.';
OR change the for code:
for ( $j=0; $j<$i; $j++) {
$csv_output .= (isset($rowr[$j])) ? $rowr[$j]."," : '';
}

str_replace()
$stringData = str_replace(',,,', ',', $stringData);
http://php.net/str-replace

Related

Read only first ten words from a text file using php

<?php
include 'db_connection.php';
if (isset($_POST['submit'])) {
$file = fopen("quiz3.txt","r") or die("Unable to open file!");
$line = fgets($file);
$sql = "INSERT INTO quiz3 (FromFile) VALUES ('".$line."')";
$result = mysqli_query($conn,$sql);
if (!$result) {
echo mysqli_error($conn);
}
else
{
echo "Your File Has Been Read & Stored In Database Successfully<br>Line Stored = ";
echo $line;
}
fclose($file);
}
?>
I want to store only first ten words from the line. How Can i do that?
currently it is saving the first line.
function get_words($sentence, $count = 10) {
preg_match("/(?:\w+(?:\W+|$)){0,$count}/", $sentence, $matches);
return $matches[0];
}
$file = fopen("quiz3.txt","r") or die("Unable to open file!");
$line = fgets($file);
$convertedLine = get_words($line );
$sql = "INSERT INTO quiz3 (FromFile) VALUES ('".$convertedLine ."')";
$result = mysqli_query($conn,$sql);
Not sure if your data contains comma, or other symbols.
This might be quick solution, and it also works with CJK words.
<?php
function cut_words($source, $number_take){
$result = "";
$wc = 0;
$source = str_replace(" ", " ", $source); // Simple sanity
$string = explode(" ", $source);
while ($wc < $number_take){
if(isset($string[$wc])){ // Prevent index out of bound.
$result .= $string[$wc];
if($wc < $number_take) {
$result .= " ";
}
$wc++;
} else {
break;
}
}
$result = trim($result);
return $result;
}
$line = cut_words($line, 10);
?>

Exporting to CSV from MySQL via PHP

I am trying to bug fix a PHP script that should export values from a MySQL database to a CSV file.
The PHP file is returning a blank CSV file & I can't figure out why & I've been stuck on this for quite a while, so any help would be much apprwciated.
Code below:
<?
include('../../../inc/config.php');
$period = $_GET['pid'];
$psql = "SELECT month, year FROM survey_period WHERE sid = " . $period;
$pres = mysql_query($psql, $dcon);
$prow = mysql_fetch_array($pres);
$pmonth = $prow['month'];
$pyear = $prow['year'];
$query="SELECT
sid,
date,
stove_id,
name,
gender,
marital_status,
occupation_of_household,
cz_stove AS km_stove,
happy_with_cz_stove AS happy_with_km_stove,
cz_stove_in_use AS km_stove_in_use,
know_how_to_use,
FROM survey_usage WHERE period = " . $_GET['pid'];
$result = mysql_query($query, $dcon);
//header('Content-Disposition: attachment;filename=export.csv');
$filename = 'usage-'.$pid.'-'.$pmonth.'-'.$pyear;
header('Content-Type: text/csv');
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");
$row = mysql_fetch_assoc($result);
if ($row) {
echocsv(array($title));
echo "\r\n";
echocsv(array_keys($row));
}
while ($row) {
echocsv($row);
$row = mysql_fetch_assoc($result);
}
function echocsv($fields)
{
$separator = '';
foreach ($fields as $field) {
if (preg_match('/\\r|\\n|,|"/', $field)) {
$field = '"' . str_replace('"', '""', $field) . '"';
}
echo $separator . $field;
$separator = ',';
}
echo "\r\n";
}
?>
hey i have a code you can use it like this
<?PHP
// Define database connection variable dynamically
$DB_Server = "localhost"; //MySQL Server
$DB_Username = "root"; //MySQL Username
$DB_Password = ""; //MySQL Password
$DB_DBName = "test1"; //MySQL Database Name
$DB_TBLName = "tabletest"; //MySQL Table Name
$filename = "excelfilename"; //File Name
//create MySQL connection
$sql = "Select * from csvtable";
$Connect = #mysqli_connect($DB_Server, $DB_Username, $DB_Password) or die("Couldn't connect to MySQL:<br>" . mysqli_error() );
//select database
$Db = #mysqli_select_db( $Connect,$DB_DBName) or die("Couldn't select database:<br>" . mysqli_error() );
//execute query
$result = #mysqli_query( $Connect,$sql) or die("Couldn't execute query:<br>" . mysqli_error() );
function cleanData(&$str)
{
if ($str == 't')
$str = 'TRUE';
if ($str == 'f')
$str = 'FALSE';
if (preg_match("/^0/", $str) || preg_match("/^\+?\d{8,}$/", $str) || preg_match("/^\d{4}.\d{1,2}.\d{1,2}/", $str)) {
$str = "'$str";
}
if (strstr($str, '"'))
$str = '"' . str_replace('"', '""', $str) . '"';
}
// filename for download
$filename = "file_" . date('Ymd') . ".csv";
header("Content-Disposition: attachment; filename=\"$filename\"");
header("Content-Type: text/csv;");
$out = fopen("php://output", 'w');
$flag = false;
while ($row = mysqli_fetch_assoc($result))
{
if (!$flag)
{
// display field/column names as first row
fputcsv($out, array_keys($row), ',', '"'); $flag = true;
}
array_walk($row, 'cleanData');
// insert data into database from here
fputcsv($out, array_values($row), ',', '"');
}
fclose($out);
exit;
//end
?>
The issue is that you are not writing anything to the csv file before opening it.
Use this code
$fp = fopen($filename, 'w');
$result = mysql_query($query);
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++) {
$headers[] = mysql_field_name($result , $i);
}
fputcsv($fp, $headers);
while($row = mysql_fetch_assoc($result)) {
fputcsv($fp, $row);
}
fclose($fp);
header('Content-Type: text/csv');
header( "Content-disposition: filename=".$filename);
readfile($filename);
Thanks to everyone for your suggestions, problem now solved, turned out to be a simple comma in the wrong place - "know_how_to_use," changed to " know_how_to_use" solved the problem. Thanks #Tintu C Raju for pointing me in the right direction

excel automatically open file after downloading in php

below is my codes for my excel. its functioning except for one thing. i don't see if my file is already save to excel.. can you help me how to automatically open my file after i download it.. i think something is missing or wrong in my codes.. so please. help . thanks.
{
$conn = mysql_connect("localhost","root","") or die (mysql_error());
mysql_select_db("copylandia",$conn);
//$fp = fopen($filename,"w+");
$filename = 'attachment'. date('Y-m-d') .'.csv';
$fp = fopen($filename,"w+");
$sql = mysql_query("select * from user") or die (mysql_error());
$num_rows = mysql_num_rows($sql);
if($num_rows >= 1)
{
$row = mysql_fetch_assoc($sql);
$fp = fopen($filename,"w+");
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma .'' . str_replace('','""',$name);
$comma = ",";
}
$seperator .= "\n";
//echo $seperator;
fputs($fp,$seperator);
mysql_data_seek($sql, 0);
while($row = mysql_fetch_assoc($sql))
{
$seperator = "";
$comma = "";
foreach($row as $name => $value)
{
$seperator .= $comma .'' . str_replace('','""',$value);
$comma = ",";
}
$seperator .= "\n";
fputs($fp,$seperator);
}
fclose($fp);
}
else
{
echo 'No records in the database!';
}
}
You can't force the browser/computer to open a file after download. The user must make that decision.
Although, since you are trying to make a CSV file, I will at least make a suggestion to help you out instead of crushing your dreams by telling you you can't do this:
Try fputcsv() instead of trying to make the string yourself:
I'm really cool! Click me!

Export more than one DB Table as SQL Data

I'm looking to export 11 Database tables' data as XML. I've easily managed to export one table, without issue. But I am looking to export more than one really.
I'm sure theres a way and obviously output the data as seperate table entitys. Any help is much appreciated on this one, As I'm finding it a little tricky.
My code is as follows
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "root";
$pass = "";
$database = "db_etch";
$table = "keywords";
$SQL_query = "SELECT * FROM $table";
$DB_link = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $DB_link) or die ("Could not find or access the database.");
$result = mysql_query ($SQL_query, $DB_link) or die ("Data not found. Your SQL query didn't work... ");
// produce XML
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
// root node
$XML .= "<result>\n";
// rows
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$XML .= "\t<$table>\n";
$i = 0;
// cells
foreach ($row as $cell) {
$cell = str_replace("&", "&", $cell);
$cell = str_replace("<", "<", $cell);
$cell = str_replace(">", ">", $cell);
$cell = str_replace("\"", """, $cell);
$col_name = mysql_field_name($result,$i);
$XML .= "\t\t<" . $col_name . ">" . $cell . "</" . $col_name . ">\n";
$i++;
}
$XML .= "\t</$table>\n";
}
$XML .= "</result>\n";
// output the whole XML string
echo $XML;
// Write $sql to file
$File = "keywords.xml";
$fh = fopen($File, 'w') or die("can't open file");
$stringData = $XML;
fwrite($fh, $stringData);
fclose($fh);
?>
I changed some of your code, assuming some little extra what you wanted:
Changed str_replace() to htmlspecialchars()
Moved xml start to the beginning.
Added a new root node.
That's about it. If you want to output all tables from a certain db, you should use "show tables;" -query to find out the tables that the db consist of.
<?php
error_reporting(E_ALL);
$host = "localhost";
$user = "root";
$pass = "";
$database = "db_etch";
$table = "keywords";
$tables_to_output_array = array('keywords', 'othertable1', 'othertable2');
$DB_link = mysql_connect($host, $user, $pass) or die("Could not connect to host.");
mysql_select_db($database, $DB_link) or die ("Could not find or access the database.");
// produce XML
header("Content-type: text/xml");
$XML = "<?xml version=\"1.0\"?>\n";
// root node
$XML .= "<tables>\n";
while (list(, $table) = each($tables_to_output_array)) {
$SQL_query = "SELECT * FROM $table";
$result = mysql_query ($SQL_query, $DB_link) or die ("Data not found. Your SQL query didn't work... ");
// tables
$XML .= "\t<$table>\n";
// rows
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$XML .= "\t\t<row>\n";
$i = 0;
// cells
foreach ($row as $cell) {
$col_name = mysql_field_name($result,$i);
$XML .= "\t\t\t<" . $col_name . ">" . htmlspecialchars($cell) . "</" . $col_name . ">\n";
$i++;
}
$XML .= "\t\t</row>\n";
}
$XML .= "\t</$table>\n";
}
$XML .= "</tables>\n";
// output the whole XML string
echo $XML;
// Write $sql to file
$File = "keywords.xml";
$fh = fopen($File, 'w') or die("can't open file");
$stringData = $XML;
fwrite($fh, $stringData);
fclose($fh);
?>

how to create a text file using php where the records should be from mysql

Could any one explain me how to create a text file using php where the records should be from mysql
1) open a file in write mode:
$myFile = "testFile.txt";
$fo = fopen($myFile, 'w') or die("can't open file");
2) Write mysql query and fetch its data
$data_query=mysql_query("SELECT name,age from table");
while($data=mysql_fetch_array($data_query))
$stringData.="Name: ".$data['name']." Age:".$data['age']."\n";
3) Write data into the file
fwrite($fo, $stringData);
4) Close file
fclose($fo);
$fh = fopen('games_set_88.php',"w");//php path
$extend_q = mysql_query('SELECT * from mod_games_set');
$row_count = mysql_num_rows($extend_q);
$col_count = mysql_num_rows(mysql_query('describe mod_games_set'));
$data_str = "<?php \n"." $"."mod_extend_type = array(\n";
$startout = 1;
while($row=mysql_fetch_assoc($extend_q)){
$startin = 1;
foreach($row as $key =>$value){
if( $startin<$col_count){
if($startin == 1){
$data_str .= " '".$value."'=>array('".$key."'=>'".$value."',";
}else{
if($startin < $col_count-1)
$data_str .= "'".$key."'=>'".$value."',";
else
$data_str .= "'".$key."'=>'".$value."')";
}
$startin++;
}
}
if($startout < $row_count) $data_str .= ",";
$data_str .= "\n";
$startout++;
}
$data_str .=" );\n?>";
fwrite($fh,$data_str);
fclose($fh);

Categories