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;
?>
Related
I'm trying to connect my PHP webpage with my MS SQL database. I've got this code from the internet, but have tried others. All seems to come back with a problem with "mssql_connect".
I have tried (I think) everything and can not find out why it won't work.
My code is:
<?php
$myServer = 'SQL5008.Smarterasp.net,1433';
$myUser = '*****';
$myPass = '*****';
$myDB = '*****';
//connection to the database
$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 id ";
$query .= "FROM tblEmployees ";
$query .= "WHERE CompanyID=3";
//execute the SQL query and return records
$result = mssql_query($query);
$numRows = mssql_num_rows($result);
echo "<h1>" . $numRows . " Row" . ($numRows == 1 ? "" : "s") . " Returned </h1>";
//display the results
while($row = mssql_fetch_array($result))
{
echo "<li>" . $row["id"] . $row["name"] . $row["year"] . "</li>";
}
//close the connection
mssql_close($dbhandle);
?>
Why dont you try using PDO. I use it with SQL SERVER daily. You will need the php sqlsrv extenstion though.
// instantiate the pdo object
try {
$Server = "localhost";
$User = "username";
$Pass = "password";
$Database = "mydb";
$this->conn = new PDO("sqlsrv:Server=$Server;Database=$Database", $User, $Pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);//allow for SQL query errors
}
catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
Check using phpinfo() if mssql extension is loaded. According to PHP Manual:
This extension is not available anymore on Windows with PHP 5.3 or later.
If you find out mssql is unloaded, try to connect using sqlsrv extension. Here you can find a few examples http://php.net/manual/ru/function.sqlsrv-connect.php
Anyway it's a good idea to post here an error message you get from PHP.
I am trying to fetch a set of fields from a Database on MSSQL Database on SQL Server 2012. This is a remote server and I am trying the following piece of code.
//MSSQL Server for retrieving the Member name from Member ID:
//mssql.secure_connection = On
// Need to upload ntwdblib.dll from net
$myServer = "IPAddress/SQLExpress "; // host/instance_name
$myUser = "ID"; // username
$myPass = "pass"; // paasword
$myDB = "dbname"; // database name
// connection to the database
$dbhandle = mssql_connect($myServer, $myUser,$myPass)
or die("Couldn’t connect to SQL Server on $myServer"). mssql_get_last_message();
// select a database to work with
$selected = mssql_select_db("sportsclub", $dbhandle)
or die("Couldn’t open database $myDB");
echo "You are connected to the " . $myDB . " database on the " . $myServer . ".";
$query = "SELECT first_name, last_name";
$query .= "FROM members ";
$query .= "WHERE member_id='".$row['member_id']."'";
// your database query
$result = mssql_query($query);
while($row = mssql_fetch_assoc($result))
{
echo "<td>" . $rows["first_name"] . $rows["last_name"] . "</td>";
}
// close the connection
mssql_close($dbhandle);
//Ended MSSQL Connection
It simply does not connect to the sql server. It gives the error: Couldn’t connect to SQL Server on IPAddress/SQLExpress
I tried checking all configurations like TCP/IP through SQL Server Config management.
Can someone please help?
Ensure remote connections over named pipes are enabled and make sure you're using a backslash before the instance name:
$myServer = "IPAddress\SQLExpress ";
If you'd like to enable connection over the default port (1433) this answer will help.
I am trying to export a MySQL query result to a remote ftp server.
I have the below code but I am currently getting an error:
Warning: ftp_put() [function.ftp-put]: Opening ASCII mode data connection. in /home/hulamyxr/public_html/kisv2/xmltest/export.php on line 50
I would think that my $file = $csv_filename; might be the issue as this is fetching the csv file that has just been created on my local server?
any ideas?
My syntax is:
<?php
$host = 'localhost';
$user = 'un';
$pass = 'pwd';
$db = 'dbname';
$table = 'v2ReportingTable';
$file = 'export';
$datetime=date("Y-m-d H:i:s");
$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
//Create a CSV for
$result = mysql_query("SELECT * FROM dbname.v2ReportingTable");
if (!$result) die('Couldn\'t fetch records');
$num_fields = mysql_num_fields($result);
$headers = array();
for ($i = 0; $i < $num_fields; $i++)
{
$headers[] = mysql_field_name($result , $i);
}
$csv_filename = "export-" .$datetime.".csv";
$fp = fopen($csv_filename, 'w+');
if ($fp && $result)
{
fputcsv($fp, $headers);
while ($row = mysql_fetch_row($result))
{
fputcsv($fp, array_values($row));
}
}
//works till here
$ftp_server = "ftp.server.co.za";
$ftp_user_name = "un";
$ftp_user_pass = "pw";
$file = $csv_filename;
$remote_file = "/LocExports/".$file;
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
// upload a file
if (ftp_put($conn_id, $remote_file, $file, FTP_ASCII)) {
echo "successfully uploaded $file\n";
} else {
echo "There was a problem while uploading $file\n";
}
// close the connection
ftp_close($conn_id);
?>
Thanks Again
and it creates the file in the correct location but is a 0kb file and all FTP commands thereafter fail. It is likely that the client is behind a firewall. To rectify this use:
<?php
ftp_pasv($resource, true);
?>
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.
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"