How to write file to desktop in laravel? - php

I am trying to write a backup for my database,
I want If a button is clicked the application will export the database to the desktop.
The app exports the file on my database directory if I use laravel database directory path
but if I change the path to desktop location nothing appears on the desktop.
$get_all_table_query = "SHOW TABLES";
$result = DB::select(DB::raw($get_all_table_query));
$tables = [
'users',
'migrations'
];
$structure = '';
$data = '';
foreach ($tables as $table) {
$show_table_query = "SHOW CREATE TABLE " . $table . "";
$show_table_result = DB::select(DB::raw($show_table_query));
foreach ($show_table_result as $show_table_row) {
$show_table_row = (array)$show_table_row;
$structure .= "\n\n" . $show_table_row["Create Table"] . ";\n\n";
}
$select_query = "SELECT * FROM " . $table;
$records = DB::select(DB::raw($select_query));
foreach ($records as $record) {
$record = (array)$record;
$table_column_array = array_keys($record);
foreach ($table_column_array as $key => $name) {
$table_column_array[$key] = '`' . $table_column_array[$key] . '`';
}
$table_value_array = array_values($record);
$data .= "\nINSERT INTO $table (";
$data .= "" . implode(", ", $table_column_array) . ") VALUES \n";
foreach($table_value_array as $key => $record_column)
$table_value_array[$key] = addslashes($record_column);
$data .= "('" . wordwrap(implode("','", $table_value_array),400,"\n",TRUE) . "');\n";
}
}
$file_name = dirname("C:\Users\ADC-2\Desktop") .'/database_backup_on_' . date('y_m_d') . '.sql';
$file_handle = fopen($file_name, 'w + ');
$output = $structure . $data;
fwrite($file_handle, $output);
fclose($file_handle);
echo "DB backup ready";
It will display DB backup ready but nothing really shows up on the desktop.

dirname()
Use
"C:\\Users\\ADC-2\\Desktop"
instead of
"C:\Users\ADC-2\Desktop"

Related

Add data to html table

I have a html table which takes data from database.
Here is my sql query:
// 1.Get data
// data for final table
// format is [username][projectNo] => [process1, process2, ..., processN]
$result = [];
// map project no to its title
$projectNoToTitle = [];
$sql = '
SELECT uid, username, staff_id, longname
FROM `user`
ORDER BY username
';
$query = mysqli_query($conn, $sql);
// for each user
while ($data = mysqli_fetch_assoc($query)) {
$sql2 = '
SELECT a.* FROM
(
(
-- select pairs project - leader
SELECT p.projectNo, p.title, CONCAT(upr.process, (upr.role) ) AS process
FROM project p
LEFT JOIN user_project upr ON p.projectNo = upr.projectNo
AND upr.username = "' . mysqli_real_escape_string($conn, $data['username']) . '"
)
) AS a
ORDER BY a.projectNo
';
$query2 = mysqli_query($conn, $sql2);
// for each project => process pair of user
while ($data2 = mysqli_fetch_assoc($query2)) {
$staff_id = $data['staff_id'];
$longname = $data['longname'];
$username = $data['username'];
$projectNo = $data2['projectNo'];
$projectTitle = $data2['title'];
$process = $data2['process'];
$projectNoToTitle[$projectNo] = $projectTitle;
if (!isset($result[$username])) {
$result[$username] = [];
}
if (!isset($result[$username][$projectNo])) {
$result[$username][$projectNo] = [];
}
if ($process) {
$result[$username][$projectNo][] = $process;
}
}
}
Then I want to print data horizontally and vertically in the table:
<table style="background-color:rgb(238, 238, 238)" id="dataTable4" class="tablesorter" class="tblD" border="0" cellpadding="0" cellspacing="1">
<?php
// 2. Output table
// create table header
// it's columns should contain all projects
if ($result) {
$header ='<th>Staff ID</th>
<th>Full Name</th>
<th>Username</th>' .
array_reduce(array_values($projectNoToTitle), function ($p, $n) {
return $p . '<th>Project ' . htmlspecialchars($n) . '</th>';
});
// output body
$body = '';
foreach ($result as $username => $usernameData) {
$row = '<td>' . htmlspecialchars($longname) . '</td>' . '<td>' . htmlspecialchars($staff_id) . '</td>' . '<td>' . htmlspecialchars($username) . '</td>';
foreach ($projectNoToTitle as $projectNo => $projectTitle) {
$r = isset($usernameData[$projectNo])
? implode(', ', $usernameData[$projectNo])
: 'N/A';
$row .= '<td>' . htmlspecialchars($r) . '</td>';
}
$body .= "<tr>$row</tr>";
}
echo "<thead>$header</thead><tbody>$body</tbody>";
}// \2. Output table
?>
I am able to print username but got problem with staff_id and longname. Here is my output right now.
System takes last name from table username and prints it for every username in the list
The problem is that you're not putting $longname and $staff_id into the $results array. When you print the table, you just use those variables, which contain the values from the last user in the database.
Change the loop that processes the database results to:
while ($data2 = mysqli_fetch_assoc($query2)) {
$staff_id = $data['staff_id'];
$longname = $data['longname'];
$username = $data['username'];
$projectNo = $data2['projectNo'];
$projectTitle = $data2['title'];
$process = $data2['process'];
$projectNoToTitle[$projectNo] = $projectTitle;
if (!isset($result[$username])) {
$result[$username] = [ 'longname' => $longname, 'staff_id' => $staff_id, 'projects' => []];
}
if (!isset($result[$username]['projects'][$projectNo])) {
$result[$username]['projects'][$projectNo] = [];
}
if ($process) {
$result[$username]['projects'][$projectNo][] = $process;
}
}
Then the code that builds the table should be:
foreach ($result as $username => $usernameData) {
$row = '<td>' . htmlspecialchars($usernameData['longname']) . '</td>' . '<td>' . htmlspecialchars($usernameData['staff_id']) . '</td>' . '<td>' . htmlspecialchars($username) . '</td>';
foreach ($projectNoToTitle as $projectNo => $projectTitle) {
$r = isset($usernameData['projects'][$projectNo])
? implode(', ', $usernameData['projects'][$projectNo])
: 'N/A';
$row .= '<td>' . htmlspecialchars($r) . '</td>';
}
$body .= "<tr>$row</tr>";
}

PHP csv upload works on mac but not windows

I have a csv upload plugin for wordpress. I can upload the files on a mac but on a windows pc it fails to upload. The csv files are created on the pc with utf-8 encoding.
if (isset($_POST) && !empty($_POST)) {
if (isset($_FILES) && $_FILES['csv_file']['size'] > 0 && $_FILES['csv_file']['type'] === 'text/csv') {
global $wpdb;
ini_set("auto_detect_line_endings", true);
$start_row = (int) $_POST['start_row'];
/*
* Get CSV data and put it into an array
*/
$fileData = file_get_contents($_FILES['csv_file']['tmp_name']);
$lines = explode(PHP_EOL, $fileData);
$csv = array();
foreach ($lines as $line) {
$csv[] = str_getcsv($line);
}
/*
* Put each row into the database
*/
$x = 1;
$insert_count = 0;
$insert_output = array();
$wpdb->query('TRUNCATE TABLE table');
foreach ($csv as $data) {
if ($x >= $start_row) {
$date = fix_date($data[0]);
$sql = "
INSERT INTO table ( date, column_1, column_2, column_3, column_4, column_5, column_6, column_7 )
VALUES ( '" . $date . "', '" . addslashes( $data[1] ) . "', '" . utf8_encode( $data[2] ) . "', '" . addslashes( $data[3]) . "', '" . $data[4] . "', '" . addslashes( $data[5] ) . "', '" . $data[6] . "', '" . $data[7] . "' )
";
$wpdb->query($sql)/* or die($sql)*/;
$insert_output[] = $insert_count . '. Added: ' . $data[1] . ' - ' . $data[3] . '<br />';
$insert_count++;
}
$x++;
}
echo '<div class="csv_success">Success. ' . number_format($insert_count) . ' rows uploaded.</div>';
} else {
echo '<div class="csv_failure">Please make sure the file you uploaded is a CSV.</div>';
}
}
Any ideas how I can get this to work on windows and mac?
Cheers
<?php
ini_set('max_execution_time', 0);
$con = mysql_connect("localhost", "", "") or die("not connect");
mysql_select_db("demo") or die("select db");
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
//Set path to CSV file
$csvFile = 'page.csv';
$csv = readCSV($csvFile);
//echo count($csv);
for ($i=1; $i <count($csv) ; $i++) {
$sql="insert into demo1 (name,bdate,phonenumber ) values('".$csv[$i][0]."','".$csv[$i][1]."' ,'".$csv[$i][2]."')";
mysql_query($sql);
}
echo 'done';
?>

Character encoding from MySQL to CSV using PHP

I am having problem with special character e.g. Russian characters are converted into ???? when I export MySQL query to CSV file.I used iconv() function but it is not working.
What should I do to fix this issue. I read different posts but nothing seems to be working for me
public function generateReport($nameReport,$db,$query,$host,$user,$pwd){
$con = mysql_connect($host,$user,$pwd);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db($db, $con);
if (!$db_selected)
{
die ("Can\'t use test_db : " . mysql_error());
}
$res = mysql_query($query);
if (!$res) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
$file='/home/'.$nameReport.'.csv';
$fp = fopen($file,'w') or exit("Unable to open file!");
if($fp){
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
$line .= $comma . '"' . str_replace('"', '""', $name) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
mysql_data_seek($res, 0);
while($row = mysql_fetch_assoc($res)) {
$line = "";
$comma = "";
foreach($row as $value) {
iconv( mb_detect_encoding( $value ), 'UTF-8', $value);
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
}
$line .= "\n";
fputs($fp, $line);
}
}
return '/home/'.$nameReport.'.csv';
}
Why not export directly from MySQL to CSV without going through PHP?
SELECT field_you_want, other_field_you_want
FROM your_table
INTO OUTFILE 'c:\\filename.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
for russian only, you can try this
$value = mb_convert_encoding($value, 'KOI8-R','UTF-8' );
$line .= $comma . '"' . str_replace('"', '""', $value) . '"';
$comma = ",";
for other charsets, you have to find a way to get the charset info.
maybe, mb_detect_encoding with mb_detect_order
or maybe if you get that text from a website: from server header or charset defined at the head of page...

Error Trying To Call PHP Class

I am getting an error when tring to call a class
I have included the class in my Site Config File.
include($GLOBALS["webpath"] . "/classes/LM_com.php");
When i call for it I get An error that it cant be found. this is line 35
$loads = LM_com::GetLocationSearchCriteria($sql, $urlappend, "l");
error recieved
Fatal error: Class 'LM_com' not found in /home/{sitename}/public_html/pages/HotLoadSearchResults.php on line 35
Contents of the LM_com.php class
<?php
if (!defined("LM_NS_CLASSES_INCLUDED"))
{
define("LM_NS_CLASSES_INCLUDED", true);
define("HIDE_ORIGIN_CITY", (1 << 1));
define("HIDE_ORIGIN_ZIP", (1 << 2));
define("HIDE_DESTINATION_CITY", (1 << 3));
define("HIDE_DESTINATION_ZIP", (1 << 4));
define("HIDE_DESTINATION", (1 << 5));
define("ARCHIVE_POST", (1 << 6));
$GLOBALS["StatusMessages"] = array(
"Company Deleted.", // 0
"Company Activated.",
"Load Posted.", // 2
"Load Updated.",
"Load Deleted.", // 4
"Truck Posted.",
"Truck Updated.", // 6
"Truck Deleted.",
"User Deactivated.", // 8
"User Activated.",
"Passwords don't match.", // 10
"Password Changed.",
"User Deleted.", // 12
"Error Activating User.",
"Error Deactivating User.", // 14
"Error Deleting User.",
"News Posted.", // 16
"Error Posting News.",
"News Post Deleted.", // 18
"Error Deleting News Post.",
"User Profile Updated.", // 20
"Error Updating User Profile.",
"Company Profile Updated.", // 22
"Error Updating Company Profile.",
"User Moved.", // 24
"Error Moving User.",
"Error Adding User.", // 26
"User Added.",
"Company Added.", // 28
"Error Adding Company.",
"Email Sent.", // 30
"No Emails Sent.",
"Cannot Add Blacklisted Email Address.", // 32
"Bid Placed.",
"Bid Not Placed." // 34
);
class UserOwnedObject
{
var $UserID = -1;
// does this session's user own this object?
function IsUserOwner()
{
if ($this->UserID == -1)
return false;
if (!isset($_SESSION["user"]) || !$_SESSION["user"]->IsLoggedIn())
return false;
//if ($_SESSION["user"]->CheckPrivs("admin", "canDelete"))
// return true;
if ($this->UserID == $_SESSION["user"]->UserID)
return true;
return false;
}
}
function hex2asc($myin)
{
for ($i = 0; $i < strlen($myin) / 2; $i++)
{
$myout .= chr(base_convert(substr($myin, $i*2, 2), 16, 10));
}
return $myout;
}
// get the administrative email address for the site
// search order: config db, site-conf setting, Administrator user email address
function get_admin_email()
{
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$toaddr = "";
// try getting admin email from config table first
$sql = "SELECT ConfigValue FROM config WHERE ConfigName = 'admin_email'";
$conf = &$conn->Execute($sql);
if ($conf->RecordCount() > 0)
$toaddr = $conf->fields[0];
else if (!empty($GLOBALS["site_AdminEmail"])) // try falling back on site-conf setting
{
$toaddr = $GLOBALS["site_AdminEmail"];
}
else // last resort, look for a user named Administrator
{
// toaddr email address should come from username = 'Administrator'
$sql = "SELECT Email FROM users WHERE UserName = 'Administrator'";
$rs = &$conn->Execute($sql);
if ($rs === false)
die("internal error:" . $conn->ErrorMsg() . " SQL: " . $sql);
$toaddr = $rs->fields[0];
}
return $toaddr;
}
// this is a big chunk of search results code that's used for both loads & trucks
function GetEquipmentSearchCriteria(&$sql, &$urlappend, $prefix)
{
// if no equipment search options given, use 0 to mean any equipment matches
if (!isset($GLOBALS["EquipmentID"]) || empty($GLOBALS["EquipmentID"]))
$GLOBALS["EquipmentID"] = array();
// make the equipmentid list an array if it isn't one
if (!is_array($GLOBALS["EquipmentID"]))
$GLOBALS["EquipmentID"] = explode(",", $GLOBALS["EquipmentID"]);
$conn = &$GLOBALS["dbSettings"]->GetConnection();
// if there are any equipment search options, prepare the sql append
if (sizeof($GLOBALS["EquipmentID"]) > 0)
{
$gsql = "SELECT EquipmentID, SearchGroup FROM equipment WHERE EquipmentID IN (" . implode(",", $GLOBALS["EquipmentID"]) . ")";
$groups = $conn->Execute($gsql);
$search_ids = "";
while (!$groups->EOF)
{
if (!empty($search_ids))
$search_ids .= ",";
$search_ids .= $groups->fields[1];
$groups->MoveNext();
}
if (!empty($search_ids))
$sql .= " AND " . $prefix . ".EquipmentID IN ( " . $search_ids . ")";
}
// do the same thing for lengths now
// if no length search options given, use 0 to mean any length matches
if (!isset($GLOBALS["Length"]) || empty($GLOBALS["Length"]))
$GLOBALS["Length"] = array();
// make the length list an array if it isn't one
if (!is_array($GLOBALS["Length"]))
$GLOBALS["Length"] = explode(",", $GLOBALS["Length"]);
// if there are any length search options, prepare the sql append
if (sizeof($GLOBALS["Length"]) > 0)
{
$gsql = "SELECT LengthID, SearchGroup FROM length WHERE LengthID IN (" . implode(",", $GLOBALS["Length"]) . ")";
$len_groups = $conn->Execute($gsql);
if ($len_groups === false)
die($conn->ErrorMsg() . " SQL: " . $gsql);
$group_ids = "";
while (!$len_groups->EOF)
{
if (!empty($group_ids))
$group_ids .= ",";
$group_ids .= $len_groups->fields[1];
$len_groups->MoveNext();
}
if (!empty($group_ids))
$sql .= " AND " . $prefix . ".LengthID IN ( " . $group_ids . ")";
}
$urlappend .= "&EquipmentID=" . implode(",", $GLOBALS["EquipmentID"]) .
"&Length=" . implode(",", $GLOBALS["Length"]);
}
function GetLocationSearchCriteria(&$sql, &$urlappend, $prefix)
{
$origin_id = Location::GetLocationID($GLOBALS["OriginState"], $GLOBALS["OriginCity"], $GLOBALS["OriginZip"]);
$destination_id = Location::GetLocationID($GLOBALS["DestinationState"], $GLOBALS["DestinationCity"], $GLOBALS["DestinationZip"]);
if (!is_array($origin_id))
{
$o = $origin_id;
$origin_id = array();
$origin_id[0] = $o;
}
if (!is_array($destination_id))
{
$d = $destination_id;
$destination_id = array();
$destination_id[0] = $d;
}
if (!empty($GLOBALS["OriginRadius"]))
{
$origin = new Location($origin_id[0]);
$origin_id = $origin->GetRadiusLocations($GLOBALS["OriginRadius"]);
$urlappend .= "&OriginRadius=" . $GLOBALS["OriginRadius"];
}
if (!empty($GLOBALS["DestinationRadius"]))
{
$destination = new Location($destination_id[0]);
$destination_id = $destination->GetRadiusLocations($GLOBALS["DestinationRadius"]);
$urlappend .= "&DestinationRadius=" . $GLOBALS["DestinationRadius"];
}
// remember search params
if (!empty($GLOBALS["OriginState"]))
$urlappend .= "&OriginState=" . $GLOBALS["OriginState"];
if (!empty($GLOBALS["OriginCity"]))
$urlappend .= "&OriginCity=" . $GLOBALS["OriginCity"];
if (!empty($GLOBALS["OriginZip"]))
$urlappend .= "&OriginZip=" . $GLOBALS["OriginZip"];
if (!empty($GLOBALS["DestinationState"]))
$urlappend .= "&DestinationState=" . $GLOBALS["DestinationState"];
if (!empty($GLOBALS["DestinationCity"]))
$urlappend .= "&DestinationCity=" . $GLOBALS["DestinationCity"];
if (!empty($GLOBALS["DestinationZip"]))
$urlappend .= "&DestinationZip=" . $GLOBALS["DestinationZip"];
// build query
if ($origin_id[0] != -1)
$sql .= " AND " . $prefix . ".OriginLocationID IN (" . implode(",", $origin_id) . ") ";
if ($destination_id[0] != -1)
$sql .= " AND " . $prefix . ".DestinationLocationID IN (" . implode(",", $destination_id) . ") ";
}
function GetLocationSearchCriteria1(&$sql, &$urlappend, $prefix)
{
$origin_id = Location::GetMultiLocationID($GLOBALS["OriginState"]);
$destination_id = Location::GetMultiLocationID($GLOBALS["DestinationState"]);
if (!is_array($origin_id))
{
$o = $origin_id;
$origin_id = array();
$origin_id[0] = $o;
}
if (!is_array($destination_id))
{
$d = $destination_id;
$destination_id = array();
$destination_id[0] = $d;
}
if (!empty($GLOBALS["OriginRadius"]))
{
$origin = new Location($origin_id[0]);
$origin_id = $origin->GetRadiusLocations($GLOBALS["OriginRadius"]);
$urlappend .= "&OriginRadius=" . $GLOBALS["OriginRadius"];
}
if (!empty($GLOBALS["DestinationRadius"]))
{
$destination = new Location($destination_id[0]);
$destination_id = $destination->GetRadiusLocations($GLOBALS["DestinationRadius"]);
$urlappend .= "&DestinationRadius=" . $GLOBALS["DestinationRadius"];
}
// remember search params
if (!empty($GLOBALS["OriginState"]))
$urlappend .= "&OriginState=" . $GLOBALS["OriginState"];
if (!empty($GLOBALS["DestinationState"]))
$urlappend .= "&DestinationState=" . $GLOBALS["DestinationState"];
// build query
if ($origin_id[0] != -1)
$sql .= " AND " . $prefix . ".OriginLocationID IN (" . implode(",", $origin_id) . ") ";
if ($destination_id[0] != -1)
$sql .= " AND " . $prefix . ".DestinationLocationID IN (" . implode(",", $destination_id) . ") ";
}
function GetMultiLocationSearchCriteria(&$sql, &$urlappend, $prefix)
{
$state_vals = array();
$city_vals = array();
$zip_vals = array();
if (!empty($GLOBALS["OriginState"]))
{
$GLOBALS["OriginState"] = explode(",", $GLOBALS["OriginState"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE StateInitials IN ('" . implode("','", $GLOBALS["OriginState"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
$state_vals = $vals;
}
if (!empty($GLOBALS["OriginCity"]))
{
$GLOBALS["OriginCity"] = explode(",", $GLOBALS["OriginCity"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE City IN ('" . implode("','", $GLOBALS["OriginCity"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
$city_vals = $vals;
}
if (!empty($GLOBALS["OriginZip"]))
{
$GLOBALS["OriginZip"] = explode(",", $GLOBALS["OriginZip"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE ZipCode IN ('" . implode("','", $GLOBALS["OriginZip"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
$zip_vals = $vals;
}
// remember search params
if (!empty($state_vals))
$urlappend .= "&OriginState=" . implode(",", $GLOBALS["OriginState"]);
if (!empty($city_vals))
$urlappend .= "&OriginCity=" . implode(",", $GLOBALS["OriginCity"]);
if (!empty($zip_vals))
$urlappend .= "&OriginZip=" . implode(",", $GLOBALS["OriginZip"]);
// build query
$vals = array_unique(array_merge($state_vals, $city_vals, $zip_vals));
if (!empty($vals))
$sql .= " AND " . $prefix . ".OriginLocationID IN (" . implode(",", $vals) . ") ";
if (!empty($GLOBALS["DestinationState"]))
{
$GLOBALS["DestinationState"] = explode(",", $GLOBALS["DestinationState"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE StateInitials IN ('" . implode("','", $GLOBALS["DestinationState"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
if (!empty($vals))
{
$sql .= " AND ";
$sql .= $prefix . ".DestinationLocationID IN (" . implode(",", $vals) . ") ";
}
$urlappend .= "&DestinationState=" . implode(",", $GLOBALS["DestinationState"]);
}
if (!empty($GLOBALS["DestinationCity"]))
{
$GLOBALS["DestinationCity"] = explode(",", $GLOBALS["DestinationCity"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE City IN ('" . implode("','", $GLOBALS["DestinationCity"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
if (!empty($vals))
$sql .= " AND " . $prefix . ".DestinationLocationID IN (" . implode(",", $vals) . ") ";
$urlappend .= "&DestinationCity=" . implode(",", $GLOBALS["DestinationCity"]);
}
if (!empty($GLOBALS["DestinationZip"]))
{
$GLOBALS["DestinationZip"] = explode(",", $GLOBALS["DestinationZip"]);
$s = "SELECT DISTINCT LocationID FROM locations WHERE ZipCode IN ('" . implode("','", $GLOBALS["DestinationZip"]) . "')";
$conn = &$GLOBALS["dbSettings"]->GetConnection();
$rs = &$conn->Execute($s);
if ($rs === false) die("panic:" . $conn->ErrorMsg() . " SQL: " . $s);
$vals = array();
while (!$rs->EOF)
{
array_push($vals, $rs->fields[0]);
$rs->MoveNext();
}
if (!empty($vals))
$sql .= " AND " . $prefix . ".DestinationLocationID IN (" . implode(",", $vals) . ") ";
$urlappend .= "&DestinationZip=" . implode(",", $GLOBALS["DestinationZip"]);
}
}
}
?>
First off you don't have a class defined named LM_com in the code you have posted.
A proper class is contained in a class structure like that posted below.
class lm_com
{
public function hex2asc($myin)
{
// ...
}
public function get_admin_email()
{
// ...
}
public function GetEquipmentSearchCriteria(&$sql, &$urlappend, $prefix)
{
// ...
}
public function GetLocationSearchCriteria(&$sql, &$urlappend, $prefix)
{
// ...
}
public function GetLocationSearchCriteria1(&$sql, &$urlappend, $prefix)
{
// ...
}
public function GetMultiLocationSearchCriteria(&$sql, &$urlappend, $prefix)
{
// ...
}
}
Secondly you have attempted to call a method in a class using the syntax with a double colon className::methodName.
This syntax when used outside of a class structure only works when calling static class methods. Static class methods do not require creating an instance of the class before calling those methods.
The following format is used for defining a public static method that can be called without creating an instance of the class
public static function GetLocationSearchCriteria(&$sql, &$urlappend, $prefix)
{
// ...
}
After you have defined the class and method as I've described then you'll be able to properly make a call to LM_com::GetLocationSearchCriteria($sql, $urlappend, "l");

How to change export to mysql to file in php?

Now i have such method:
function exportFromTransbase($table_name) {
$odbc_query = "SELECT * FROM " . $table_name;
$data = odbc_exec($this->odbc_id, $odbc_query);
odbc_longreadlen($data, 10485760);
while($row = odbc_fetch_array($data))
{
foreach($row as $key => $value) {
$keys[] = "`" . $key . "`";
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
$mysql_query = "INSERT INTO `" . strtolower(substr($table_name, 4)) . "` (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";
mysql_query($mysql_query);
set_time_limit(3600);
unset($keys);
unset($values);
unset($row);
}
if ($mysql_query){
print "Ýêñïîðò äàííûõ èç òàáëèöû " . $table_name . " çàâåðøåí!";
//strtolower(substr($table_name, 4))
}
}
But it's very slow when importing to mysql. I decide to change this to export to file .sql, so that in future i can via terminal or phpmyadmin import that table. How to change to export to sql file my data?
Note! i'm converting from transbase to mysql
Instead of...
while($row = odbc_fetch_array($data))
{
foreach($row as $key => $value) {
$keys[] = "`" . $key . "`";
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
$mysql_query = "INSERT INTO `" . strtolower(substr($table_name, 4)) . "` (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";
mysql_query($mysql_query);
set_time_limit(3600); // this should not be here
unset($keys); // this is redundant
unset($values); // and this
unset($row); // and this too
}
Try:
$oufile=fopen("export.sql", 'w') || die("error writing file");
while($row = odbc_fetch_array($data))
{
foreach($row as $key => $value) {
$keys[] = "`" . $key . "`";
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
$mysql_query = "INSERT INTO `" . strtolower(substr($table_name, 4)) . "` (" . implode(",", $keys) . ") VALUES (" . implode(",", $values) . ")";
fputs($outfile, $mysql_query . ";\n";
}
However it'll be much faster if you....
$oufile=fopen("export.sql", 'w') || die("error writing file");
fputs($outfile, "ALTER TABLE `" . . strtolower(substr($table_name, 4)) . "` DISABLE KEYS;\n";
while($row = odbc_fetch_array($data))
{
foreach($row as $key => $value) {
$keys[] = "`" . $key . "`";
$values[] = "'" . mysql_real_escape_string($value) . "'";
}
$head="INSERT DELAYED INTO `" . strtolower(substr($table_name, 4)) . "` (" . implode(",", $keys) . ") VALUES ";
$row[]="(" . implode(",", $values) . ")";
if (count($row)>100) {
flush_ins($outfile, $head, $row);
$row=array();
}
}
if (count($row)) flush_ins($outfile, $head, $row);
fputs($outfile, "ALTER TABLE `" . . strtolower(substr($table_name, 4)) . "` ENABLE KEYS;\n";
fclose($outfile);
...
function flush($rows, $head, $fh)
{
fputs($fh, $head . implode("\n,", $rows) . ";\n");
}
see this post:
Easy way to export a SQL table without access to the server or phpMyADMIN
it uses the select into outfile syntax. The docs for this syntax are here: http://dev.mysql.com/doc/refman/5.1/en/select-into.html
you would do something like this:
mysql_query('SELECT * INTO OUTFILE "/path/to/my_file/my_file.sql" from '.$table_name)
Then this .sql file will be on your server.
If you don't have permissions to run the select into outfile synatx. You can use the mysqldump utility, like this:
<?php
exec('mysqldump db_name '.$table_name.' > my_file.sql');
?>
This will create an .sql file with the name indicated.

Categories