PHP CSV export from stored MySQL Procedure - php

Trying to use the below code to call a stored procedure on MySQL and export to CSV. It generates a csv file however it is blank. The stored procedure is called DATAEXPORT1
Any ideas would be grateful!
<?php
$host = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$file = 'export';
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));
/*
* execute sql query
*/
$sql = "Call DATAEXPORT1()";
$result = mysqli_query($connection,$sql) or die("Selection Error " . mysqli_error($connection));
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$csv_output .= $row['Field'].", ";
$i++;
}
}
$csv_output .= "\n";
$values = mysqli_query($connection,$sql);
while ($rowr = mysqli_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}
$filename = $file."_".date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
mysqli_close($connection);
exit;
?>

Used the following code which works nicely:
<?php
$host = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));
// fetch mysql table rows
$sql = "CALL DATAEXPORT1()";
$result = mysqli_query($connection, $sql) or die("Selection Error " . mysqli_error($connection));
header('Content-type: text/csv');
header('Content-Disposition: attachment; filename="output1.csv"');
$file = fopen('php://output', 'w');
while($row = mysqli_fetch_assoc($result))
{
fputcsv($file, $row);
}
fclose($file);
//close the db connection
mysqli_close($connection);
exit();

I only modify little your script
<?php
$host = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$file = 'export';
$connection = mysqli_connect($host, $username, $password, $dbname) or die("Connection Error " . mysqli_error($connection));
/*
* execute sql query
*/
$sql = "Call DATAEXPORT1()";
$result = mysqli_query($connection,$sql) or die("Selection Error " . mysqli_error($connection));
$num_rows = count($result);
$csv_output = '';
if( $num_rows > 0) {
foreach($result as $item => $value){
$csv_output .= $item . ", " . $value . "\n";
$i++;
}
}
$filename = $file . "_" . date("Y-m-d_H-i",time());
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
print $csv_output;
mysqli_close($connection);
exit;
?>

Related

How to Populate this HTML Table using PHP and MySQL

Mysql File:
<?php
function query($sql, $array) {
$servername = "localhost";
$username = "verifyUser";
$password = "test";
$dbname = "verify";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
$stack = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($stack, $row);
if(!$array) {
return $row;
}
}
return $stack;
}
$conn->close();
}
?>
My php file:
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Serial</th>
</tr>
<?php
include_once("mysql.php");
$result = query("SELECT ProductId, Name, SerialId FROM product", true);
while ($row = mysqli_query($result)) {
echo "<tr><td>" . $row['ProductId'] . "</td><td>" . $row['Name'] . "</td><td>" . $row['SerialId'] . "</td></tr>";
}
?>
</table>
Output:
Id Name Serial
This is my first day trying to do anything with php. So go easy on me :)
I've been following different tutorials and looking at the php documentation, but I have not be able to get my table to print anything besides the table headers.
I don't think my query is wrong, because I return results in workbench
https://gyazo.com/ab588fa7b7498444a5e8dcd1b172f315
<?php
$table='<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Serial</th>
</tr>';
$servername = "localhost";
$username = "";
$password = "";
$dbname = "verify";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
$stack = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($stack, $row);
if(!$array) {
return $row;
}
}
}
$conn->close();
$table_content='';
foreach($stack as $item)
{
$table_content.= "<tr>
<td>" . $row['ProductId'] . "</td>
<td>" . $row['Name'] . " </td>.
<td>" . $row['SerialId'] . "</td>
</tr>";
}
echo $table.$table_content.'</table>';
?>
<table>
<tr>
<th>Id</th>
<th>Name</th>
<th>Serial</th>
</tr>
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "verify";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sql);
$stack = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($stack, $row);
if(!$array) {
return $row;
}
}
}
$conn->close();
foreach($stack as $item)
{
echo "<tr><td>" . $row['ProductId'] . "</td><td>" . $row['Name'] . "</td>. <td>" . $row['SerialId'] . "</td></tr>";
}
?>

how to take backup of mysql database using php

I need to export backup of the database using php when I click on the link. I searched so many references and created code. But when I execute this it displays error. Can anyone help me to get the solution? This is my code
BACKUP
Back.php
<?php
include('../database.php');
$dbhost = $_SERVER['SERVER_NAME'];
$dbuser = 'root';
$dbpass = '';
$dbname='marketing';
$backup_file = $dbname . date("Y-m-d-H-i-s") . '.gz';
$command = "mysqldump --opt -h $dbhost -u $dbuser -p $dbpass ". "$dbname | gzip > $backup_file";
$sys=system($command);
if($sys)
{
echo "succc";
}
else{
echo "failed";
}
?>
You may use the following code pattern directly with your task
<?php
$dbhost = $_SERVER['SERVER_NAME'];
$dbuser = 'root';
$dbpass = '';
$dbname = 'marketing';
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
$backupAlert = '';
$tables = array();
$result = mysqli_query($connection, "SHOW TABLES");
if (!$result) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
$return = '';
foreach ($tables as $table) {
$result = mysqli_query($connection, "SELECT * FROM " . $table);
if (!$result) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$num_fields = mysqli_num_fields($result);
if (!$num_fields) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$return .= 'DROP TABLE ' . $table . ';';
$row2 = mysqli_fetch_row(mysqli_query($connection, 'SHOW CREATE TABLE ' . $table));
if (!$row2) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$return .= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
if (isset($row[$j])) {
$return .= '"' . $row[$j] . '"';
} else {
$return .= '""';
}
if ($j < $num_fields - 1) {
$return .= ',';
}
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
$backup_file = $dbname . date("Y-m-d-H-i-s") . '.sql';
$handle = fopen("{$backup_file}", 'w+');
fwrite($handle, $return);
fclose($handle);
$backupAlert = 'Succesfully got the backup!';
}
}
}
}
echo $backupAlert;
?>
I use this Script as sheduled CRON task.
// Edit this section
$dbhost = "SERVER IP OR LOCALHOST";
$dbuser = "DB USER";
$dbpass = "DB PASSWORD";
$dbname = "DB NAME ";
$message = "E-MAIL MESSAGE TEXT";
// Don't need to edit below this section
function compress($filepath) {
$zip = new ZipArchive();
$file=$filepath.".zip";
if($zip->open($file,1?ZIPARCHIVE::OVERWRITE:ZIPARCHIVE::CREATE)===TRUE) {
// Add the files to the .zip file
$zip->addFile($filepath);
// Closing the zip file
$zip->close();
}
}
ini_set('date.timezone', 'Europe/Budapest');
$backupfile = $dbname.'_'.date("Y-m-d_H-i", time()).'.sql';
system("mysqldump -h $dbhost -u $dbuser -p$dbpass $dbname > $backupfile");
compress($backupfile);
// Send E-mail notification
$sendto = "NAME <E-MAIL ADDRESS>";
$sendfrom = "NAME <E-MAIL ADDRESS>";
$sendsubject = "SUBJECT";
// $message="This attachment contains the backup of your database.";
$separator = md5(time());
// attachment name
$filename = $backupfile.".zip";
// Open db file
$file = fopen( $backupfile, "r" );
// Read the file into a variable
$size = filesize($backupfile);
$content = fread( $file, $size);
//$pdfdoc is PDF generated by FPDF
$attachment = chunk_split(base64_encode(file_get_contents($filename)));
// Define the main headers.
$header = "From:$sendfrom\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; ";
$header .= "boundary=$separator\r\n";
$header .= "--$num\r\n";
// Define the message section
$header .= "Content-Type: text/plain\r\n";
$header .= "Content-Transfer-Encoding:8bit\r\n\n";
$header .= "$message\r\n";
$header .= "--$separator\r\n";
// Define the attachment section
$header .= "Content-Type: application/octet-stream; ";
$header .= "name=\"$filename\"\r\n";
$header .= "Content-Transfer-Encoding:base64\r\n";
$header .= "Content-Disposition:attachment; ";
$header .= "filename=\"$filename\"\r\n\n";
$header .= "$attachment\r\n";
$header .= "--$separator--";
// Send email now
mail( $sendto, $sendsubject, "", $header );
// Delete the SQL and ZIP file from your server
unlink($backupfile);
unlink($filename);
?>
If you add --verbose 2> output.txt to your command, it will spell out what is happening, line by line as below for example. Obviously you need to look at the contents of output.txt after the command.
-- Connecting to localhost...
-- Retrieving table structure for table users...
-- Sending SELECT query...
-- Retrieving rows...
-- Disconnecting from localhost...
Your full command would then be:
"mysqldump --opt -h $dbhost -u $dbuser -p $dbpass --verbose 2> output.txt". "$dbname | gzip > $backup_file"
Also it may not be correct to test $sys like you have done as an indicator of success, Instead use this form..
system ( string $command, &$return_var);
and then $return will contain the return status of the executed command (mysqldump) which is better for testing actual success of the backup.
Your code might then look like:
int $return_var;
system ($command, &$return_var);
if ($return_var ==0){
echo "success";
}
else{
echo "failed";
}
i changed a bit to support utf8
<title><?php echo "backup MySQL data - " . $_SERVER['SERVER_NAME'] ; ?></title>
<?php
// ref. to https://stackoverflow.com/questions/52530833/how-to-take-backup-of-mysql-database-using-php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'jackycms2019';
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
mysqli_set_charset($connection,"utf8");
$backupAlert = '';
$tables = array();
$result = mysqli_query($connection, "SHOW TABLES");
if (!$result) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
while ($row = mysqli_fetch_row($result)) {
$tables[] = $row[0];
}
mysqli_free_result($result);
$return = '';
foreach ($tables as $table) {
$result = mysqli_query($connection, "SELECT * FROM " . $table);
if (!$result) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$num_fields = mysqli_num_fields($result);
if (!$num_fields) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$return .= 'DROP TABLE ' . $table . ';';
$row2 = mysqli_fetch_row(mysqli_query($connection, 'SHOW CREATE TABLE ' . $table));
if (!$row2) {
$backupAlert = 'Error found.<br/>ERROR : ' . mysqli_error($connection) . 'ERROR NO :' . mysqli_errno($connection);
} else {
$return .= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $num_fields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$return .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
if (isset($row[$j])) {
$return .= '"' . $row[$j] . '"';
} else {
$return .= '""';
}
if ($j < $num_fields - 1) {
$return .= ',';
}
}
$return .= ");\n";
}
}
$return .= "\n\n\n";
}
$backup_file = $dbname . '.sql';
$handle = fopen("{$backup_file}", 'w+');
fwrite($handle, $return);
fclose($handle);
$backupAlert = 'backup MySQL data completed !';
}
}
}
}
echo $backupAlert;
?>

php can't respond json

Why a php file does not respond as json, but it responds to the connected file.
file respond
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include '../connect.php';
mysqli_set_charset($conn, "utf8");
$sql="SELECT confer_name, confer_begin_time, confer_end_time, confer_value, con_img FROM conference";
$outp = "";
$result = mysqli_query($conn,$sql);
if(mysqli_num_rows($result)>0){
while($rs = $result->fetch_array(MYSQLI_ASSOC)){
if($outp != ""){$outp .=",";}
$outp .='{"cname":"' .$rs["confer_name"]. '",';
$outp .='"cbt":"' .$rs["confer_begin_time"] . '",';
$outp .='"cet":"' .$rs["confer_end_time"] . '",';
$outp .='"cvalue":"' .$rs["confer_value"] . '",';
$outp .='"cimg":"' .$rs["con_img"] . '"}';
}
$outp = '{"records":['.$outp.']}';
echo $outp;
}
?>//***
file connect This file is used to connect.
<?php
$servername = "localhost";
$username = "----";
$password = "----";
$database = "----";
$conn = new mysqli($servername,$username,$password,$database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
This result
modify your code as below
$outp = json_encode($outp);

Phone Number Automatically Add When Export To Excel File

I have +82-2-573-3585 in my database but when I export .xls file using the following codes below the number add automatically so it result to -4078. How can I make the phone number in my excel file the same with my database phone number?
<?php
$conn = new mysqli('localhost', 'root', '');
mysqli_select_db($conn, 'databasename');
$setSql = "SELECT contact_number FROM supplier";
$setRec = mysqli_query($conn, $setSql);
$columnHeader = 'SUPPLIERS';
$columnHeader = "Mobile Number" . "\t";
$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= $value;
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Machine_Supplier.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>
Please try this following code.
<?php
$conn = new mysqli('localhost', 'root', '');
mysqli_select_db($conn, 'databasename');
$setSql = "SELECT contact_number FROM supplier";
$setRec = mysqli_query($conn, $setSql);
$columnHeader = 'SUPPLIERS';
$columnHeader = "Mobile Number" . "\t";
$setData = '';
while ($rec = mysqli_fetch_row($setRec)) {
$rowData = '';
foreach ($rec as $value) {
$value = '"' . $value . '"' . "\t";
$rowData .= strval($value);
}
$setData .= trim($rowData) . "\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=Machine_Supplier.xls");
header("Pragma: no-cache");
header("Expires: 0");
echo ucwords($columnHeader) . "\n" . $setData . "\n";
?>
Hope it works

Get all rows from MySQL Query

The PHP Code:
<?php
//Server Information
$servername = "localhost";
$dbusername = "USERNAME";
$password = "TOTALLYSECUREPASSWORD";
$dbname = "DEFINITELYADATABASE";
//Query Information
$guid = $_POST['GUID'];
$username = $_POST['USERNAME'];
$admin_username = $_POST['ADMIN_USERNAME'];
$ban_reason = $_POST['BAN_REASON'];
$ip = $_POST['IP'];
//Create Connection
$connection = mysqli_connect($servername, $dbusername, $password, $dbname);
//Check the Connection
if ($connection->connect_error){
die("Connection failed: " . $connection->connect_error);
}
//$sql = "SELECT DATE, DBUSERNAME, GUID, IP, USERNAME, BAN_REASON FROM bans";
//$result = $connection->query($sql);
$sql = "SELECT * FROM bans WHERE";
$types = json_decode($_POST['QUERY_TYPE'], true);
if (in_array("query_admin_username", $types)) {
$sql = $sql . " DBUSERNAME = " . "\"" . $admin_username . "\"" . " &&";
}
if (in_array("query_guid", $types)) {
$sql = $sql . " GUID = " . "\"". $guid . "\"" . " &&";
}
if (in_array("query_ip", $types)) {
$sql = $sql . " IP = " . "\"" . $ip . "\"" . " &&";
}
if (in_array("query_username", $types)) {
$sql = $sql . " USERNAME = " . "\"" . $username . "\"" . " &&";
}
if (in_array("query_ban_reason", $types)) {
$sql = $sql . " BAN_REASON = " . "\"" . $ban_reason . "\"" . " &&";
}
$sql_query = substr($sql, 0, -3);
echo ($sql_query);
$result = $connection->query($sql_query);
while ($connection->query($sql_query)) {
}
if (!$result) {
die("Invalid Query: " . mysqli_error());
}
$row = $result->fetch_array(MYSQLI_NUM);
while ($row = mysqli_fetch_assoc($result)) {
echo ($row);
}
mysqli_close($connection);
?>
As weird as all that looks, it works just how I want it to (I think).
My issue:
I want to be able to get the data from each row and export it as one large String, something along the lines of:
[DATE] DBUSERNAME banned USERNAME (GUID / IP) for BAN_REASON.
I just have absolutely no idea how to go about this. I've tested the Query and it's returning everything it should, however I was using "echo ($row[0])" etc to display them, which is pretty impractical if it's going to return a large amount of rows.
Sorry if something doesn't make sense, my brain is fried at the moment. Please let me know if I forgot anything.
You could concatenate the columns like this if the rest of your script works:
SELECT CONCAT('[',DATE,'] ',DBUSERNAME,' banned ',USERNAME,'(',COALESCE(GUID, IP),),') for ', BAN_REASON) AS your_columns_in_one_line FROM your_table WHERE .....;
See this link for reference to CONCAT

Categories