I am exporting a SQL Server table to a CSV using php (see code below). What I am needing help with is including the headers of the columns in the export. I can do this when I export from MySQL, but cannot figure it out with SQL Server. If anyone can point me in the right direction I would appreciate it.
<?php
// SQL Server connection string details.
$myServer = "server";
$myUser = "user";
$myPass = "password";
$myDB = "dbname";
// connection to the SQL Server
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT col01, col02, col03, col04, col05, col06, col07 ";
$query .= "FROM table ";
$result = mssql_query($query, $dbhandle);
//Generate CSV file - Set as MSSQL_ASSOC as you don't need the numeric values.
while ($l = mssql_fetch_array($result, MSSQL_ASSOC)) {
foreach($l AS $key => $value){
//If the character " exists, then escape it, otherwise the csv file will be invalid.
$pos = strpos($value, '"');
if ($pos !== false) {
$value = str_replace('"', '\"', $value);
}
$out .= '"'.$value.'",';
}
$out .= "\n";
}
//free result set memory
mssql_free_result($result);
//close the connection
mssql_close($dbhandle);
// Output to browser with the CSV mime type
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=export.csv");
echo $out;
?>
Use http://php.net/manual/en/function.mssql-fetch-field.php , like this:
http://www.razorsql.com/articles/sqlserver_column_names_values.html
Adding col01, col02, col03, col04, col05, col06, col07 to the first line of your $out variable before iterating through you request results will solve your problem
out .="col01, col02, col03, col04, col05, col06, col07\n"
Related
I have adapted the info from this site but instead of creating a csv file, it is only displaying the info in the command screen it is being executed in. I have tried entering $fileName = 'C:\Users\dmcgettigan\Desktop\mysql-export.csv'; and just the filename but I do not have a file being generated. Thank you in advance for your help, I am trying to teach myself php, and mysql!
Updated: added code
My Code:
<?php
//Our MySQL connection details.
$host = 'mysql_server';
$user = 'user';
$password = 'password';
$database = 'database';
//Connect to MySQL using PDO.
$pdo = new PDO("mysql:host=$host;dbname=$database", $user, $password);
//Create our SQL query.
$sql = "SELECT
a.InvoiceNumber, a.partnumber, a.Quantity, b.Discount, date
FROM
data a,
mars b
WHERE
a.PartNumber = b.partnumber
AND date >= '2018-09-28'
AND mfg = 'gk'
AND discount <> '0.00'
AND CustomerNumber IN ('Z5447520' , 'Z3715177', 'Z1234444', 'Z5425966')
AND Quantity > '0'";
//Prepare our SQL query.
$statement = $pdo->prepare($sql);
//Executre our SQL query.
$statement->execute();
//Fetch all of the rows from our MySQL table.
$rows = $statement->fetchAll(PDO::FETCH_ASSOC);
//Get the column names.
$columnNames = array();
if(!empty($rows)){
//We only need to loop through the first row of our result
//in order to collate the column names.
$firstRow = $rows[0];
foreach($firstRow as $colName => $val){
$columnNames[] = $colName;
}
}
//Setup the filename that our CSV will have when it is downloaded.
$fileName = 'mysql-export.csv';
//Set the Content-Type and Content-Disposition headers to force the download.
header('Content-Type: application/excel');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
//Open up a file pointer
$fp = fopen('php://output', 'w');
//Start off by writing the column names to the file.
fputcsv($fp, $columnNames);
//Then, loop through the rows and write them to the CSV file.
foreach ($rows as $row) {
fputcsv($fp, $row);
}
//Close the file pointer.
fclose($fp);
$fp = fopen('php://output', 'w'); this specific line should be changed to $fp = fopen($filename, 'w'); because as is you are using the output as the file
I have a PHP script in which I am doing two steps,
1) Deleting all tables from database
2) Restoring default database in that empty database
This code is working properly when I manually run the script by putting the URL but whenever I am running this script with cron job then 1st step is working properly but database is not getting restored.
here is my cron job command ,
[php_path] -q /home/[username]/[php_file_path]
here is my php script,
// Name of the file
$filename = 'sample.sql';
// MySQL host
$mysql_host = 'localhost';
// MySQL username
$mysql_username = 'my_username';
// MySQL password
$mysql_password = 'my_password';
// Database name
$mysql_database = 'my_db_name';
/*---------- Drop All tables From Database ----------*/
$mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database);
$mysqli->query('SET foreign_key_checks = 0');
if ($result = $mysqli->query("SHOW TABLES"))
{
while($row = $result->fetch_array(MYSQLI_NUM))
{
$mysqli->query('DROP TABLE IF EXISTS '.$row[0]);
}
}
$mysqli->query('SET foreign_key_checks = 1');
$mysqli->close();
/*---------- Restore Database From SQL File ----------*/
$con=mysqli_connect($mysql_host, $mysql_username, $mysql_password, $mysql_database);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// ...some PHP code for database "my_db"...
// Change database to "test"
mysqli_select_db($con, $mysql_database);
// ...some PHP code for database "test"...
// Temporary variable, used to store current query
$templine = '';
// Read in entire file
$lines = file($filename);
// Loop through each line
foreach ($lines as $line)
{
// Skip it if it's a comment
if (substr($line, 0, 2) == '--' || $line == '')
continue;
// Add this line to the current segment
$templine .= $line;
// If it has a semicolon at the end, it's the end of the query
if (substr(trim($line), -1, 1) == ';')
{
// Perform the query
mysqli_query($con, $templine) or print('Error performing query \'<strong>' . $templine . '\': ' . mysql_error() . '<br /><br />');
// Reset temp variable to empty
$templine = '';
}
}
I need to get some data from a Microsoft SQL Server database at work. When I have the data I need, I need to make an Excel spreadsheet that can be saved locally on my computer.
I found PHPExcel which seems to do the job on the Excel part, but what about getting the data from the Database?
I can't seem to find anything that's recent. Only old tutorials.
Use this way to Fetch the Records :
<?php
$hostname = "192.168.3.50";
$username = "sa";
$password = "123456";
$dbName = "yourdb";
MSSQL_CONNECT($hostname,$username,$password) or DIE("DATABASE FAILED TO RESPOND.");
mssql_select_db($dbName) or DIE("Database unavailable");
$query = "SELECT * FROM dbo.table";
$result = mssql_query( $query );
for ($i = 0; $i < mssql_num_rows( $result ); ++$i)
{
$line = mssql_fetch_row($result);
print( "$line[0] - $line[1]\n");
}
?>
This will fetch each rows from the Data Retrieve and Print on the Page. Use your Required format into that. I mean, Use html Table to show the data in well format.
Use this code to get an data from Database.
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = '192.168.3.50';
// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'sa');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
else{
echo "connected ";
mssql_select_db('Matrix') or die("Wrong DATAbase");
//mssql_query("SELECT Seq_no from dbo.Trans_R WHERE Seq_no = 000001",$link) or die("cannot execute the query");
$query = mssql_query("SELECT Tr_Date,Tr_Time,Tr_Data from Matrix.dbo.Trans_R");
$f = mssql_fetch_array($query);
echo $f['Tr_Date'];
}
?>
Can i know why Negative Vote??
He asked me to :
" but what about getting the data from the Database?"
When I run php script to export MSSQL server table data I got this error message:
Warning: mssql_query() [function.mssql-query]: message:
Unicode data in a Unicode-only collation or ntext data cannot be sent
to clients using DB-Library (such as ISQL) or ODBC version 3.7 or
earlier. (severity 16) in C:\Program Files\Apache Software
Foundation\Apache2.2\htdocs\Newitemtest\csv3.php on line 22
Can anyone point me in correct way? Thank you so much in advance.
Below is my php script
<?php
$myServer = "****";
$myUser = "**";
$myPass = "****";
$myDB = "***";
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
$query = "SELECT * ";
$query .= "FROM Item ";
$result = mssql_query($query, $dbhandle);
while ($l = mssql_fetch_array($result, MSSQL_ASSOC)) {
foreach($l AS $key => $value){
$pos = strpos($value, '"');
if ($pos !== false) {
$value = str_replace('"', '\"', $value);
}
$out .= '"'.$value.'",';
}
$out .= "\n";
}
mssql_free_result($result);
mssql_close($dbhandle);
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=export.csv");
echo $out;
?>
I am using a CSV file to export a mysql table. How can I view it as a download file now that it is stored on Drive C: directly without any notification
<?php
$host = 'localhost'; // <-- db address
$user = 'root'; // <-- db user name
$pass = 'root'; // <-- password
$db = 'urs'; // db's name
$table = 'veiwresult'; // table you want to export
$file = 'alaa'; // csv name.
$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(" SELECT ApplicantNum,name, averg,choice FROM veiwresult");
fputcsv($f, array('ApplicantNum','name','averg', 'choice'));
$timestamp = date('Ymd-His');
$f = fopen("C:/mycsv-{$timestamp}.csv", 'w');
// Headers
while($row = mysql_fetch_row($result))
{
fputcsv($f, $row);
}
fputcsv($f, $items_array);
fclose($f);
?>
If you want to store csv-file and then open it without any clicking, it`s impossible.
If you just wish to have it opened, open it in browser window via
header('Content-disposition: inline;filename=foobar.csv');
header('Content-Type: text/csv;charset=UTF-8');
echo $csv_content;
where $csv_content is a string with contents of csv-file. You cat get it this way
$csv_content = file_get_contents('c:/mycsv.csv');
To download it...
<?php
$host = 'localhost'; // <-- db address
$user = 'root'; // <-- db user name
$pass = 'root'; // <-- password
$db = 'urs'; // db's name
$table = 'veiwresult'; // table you want to export
$file = 'alaa'; // csv name.
$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(" SELECT ApplicantNum,name, averg,choice FROM veiwresult");
fputcsv($f, array('ApplicantNum','name','averg', 'choice'));
$timestamp = date('Ymd-His');
$f = fopen("C:/mycsv-{$timestamp}.csv", 'w');
// Headers
while($row = mysql_fetch_row($result))
{
fputcsv($f, $row);
}
fputcsv($f, $items_array);
fclose($f);
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename="mycsv-{$timestamp}"');
readfile('C:/mycsv-{$timestamp}.csv');
?>
This will still notify the user of the download, and depending on their settings they may need to accept the download. This functionality cannot be overridden of course.