PHP Script to convert .DBF files to .MYSQL - php

Just wondering if anyone can point me in the direction of some tips / a script that will help me create an mysql from an original dbf File, using PHP.
thanks before.

Try the code below...
<?php
$tbl = "cc";
$db_uname = 'root';
$db_passwd = '';
$db = 'aa';
$conn = mysql_pconnect('localhost',$db_uname, $db_passwd);
// Path to dbase file
$db_path = "dbffile/bbsres12.dbf";
// Open dbase file
$dbh = dbase_open($db_path, 0) or die("Error! Could not open dbase database file '$db_path'.");
// Get column information
$column_info = dbase_get_header_info($dbh);
// Display information
// print_r($column_info);
$line = array();
foreach($column_info as $col) {
switch($col['type']) {
case 'character':
$line[]= "`$col[name]` VARCHAR( $col[length] )";
break;
case 'number':
$line[]= "`$col[name]` FLOAT";
break;
case 'boolean':
$line[]= "`$col[name]` BOOL";
break;
case 'date':
$line[]= "`$col[name]` DATE";
break;
case 'memo':
$line[]= "`$col[name]` TEXT";
break;
}
}
$str = implode(",",$line);
$sql = "CREATE TABLE `$tbl` ( $str );";
mysql_select_db($db, $conn);
mysql_query($sql, $conn);
set_time_limit(0); // I added unlimited time limit here, because the records I imported were in the hundreds of thousands.
// This is part 2 of the code
import_dbf($db, $tbl, $db_path);
function import_dbf($db, $table, $dbf_file) {
global $conn;
if (!$dbf = dbase_open ($dbf_file, 0)) {
die("Could not open $dbf_file for import.");
}
$num_rec = dbase_numrecords($dbf);
$num_fields = dbase_numfields($dbf);
$fields = array();
for ($i=1; $i<=$num_rec; $i++) {
$row = #dbase_get_record_with_names($dbf,$i);
$q = "insert into $db.$table values (";
foreach ($row as $key => $val) {
if ($key == 'deleted') {
continue;
}
$q .= "'" . addslashes(trim($val)) . "',"; // Code modified to trim out whitespaces
}
if (isset($extra_col_val)) {
$q .= "'$extra_col_val',";
}
$q = substr($q, 0, -1);
$q .= ')';
//if the query failed - go ahead and print a bunch of debug info
if (!$result = mysql_query($q, $conn)) {
print (mysql_error() . " SQL: $q\n");
print (substr_count($q, ',') + 1) . " Fields total.";
$problem_q = explode(',', $q);
$q1 = "desc $db.$table";
$result1 = mysql_query($q1, $conn);
$columns = array();
$i = 1;
while ($row1 = mysql_fetch_assoc($result1)) {
$columns[$i] = $row1['Field'];
$i++;
}
$i = 1;
foreach ($problem_q as $pq) {
print "$i column: {$columns[$i]} data: $pq\n";
$i++;
}
die();
}
}
}
?>

You can try composer package hisamu/php-xbase (https://github.com/hisamu/php-xbase) to read dbf file and insert into your database. Had the same problem and this was most suitable solution.

UPDATED:
in the event that your did not compile PHP with dbase library you could get the following error:
Call to undefined function dbase_open()
in which case (centos)
yum install php-dbase
Here is the updated code for $mysqli
<?php
$mysqli = new mysqli("localhost", "DBusername", "DBpassword", "tableName");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$tbl = "yourTableName";
$db = 'YourDBName';
// Path to dbase file
$db_path = "/path/dbaseFileName.dbf";
// Open dbase file
$dbh = dbase_open($db_path, 0)
or die("Error! Could not open dbase database file '$db_path'.");
// Get column information
$column_info = dbase_get_header_info($dbh);
$line = array();
foreach($column_info as $col) {
switch($col['type']){
case 'character':
$line[]= "`$col[name]` VARCHAR( $col[length] )";
break;
case 'number':
$line[]= "`$col[name]` FLOAT";
break;
case 'boolean':
$line[]= "`$col[name]` BOOL";
break;
case 'date':
$line[]= "`$col[name]` DATE";
break;
case 'memo':
$line[]= "`$col[name]` TEXT";
break;
}
}
$str = implode(",",$line);
$sql = "CREATE TABLE `$tbl` ( $str );";
//mysql_select_db($db,$conn);
//mysql_query($sql,$conn);
$mysqli->query($sql);
set_time_limit(0); // I added unlimited time limit here, because the records I imported were in the hundreds of thousands.
// This is part 2 of the code
import_dbf($db, $tbl, $db_path, $mysqli);
function import_dbf($db, $table, $dbf_file,$mysqli){
//global $conn;
global $mysqli;
if (!$dbf = dbase_open ($dbf_file, 0)){ die("Could not open $dbf_file for import."); }
$num_rec = dbase_numrecords($dbf);
$num_fields = dbase_numfields($dbf);
$fields = array();
for ($i=1; $i<=$num_rec; $i++){
$row = #dbase_get_record_with_names($dbf,$i);
$q = "insert into $db.$table values (";
foreach ($row as $key => $val){
if ($key == 'deleted'){ continue; }
$q .= "'" . addslashes(trim($val)) . "',"; // Code modified to trim out whitespaces
}
if (isset($extra_col_val)){ $q .= "'$extra_col_val',"; }
$q = substr($q, 0, -1);
$q .= ')';
//if the query failed - go ahead and print a bunch of debug info
// if (!$result = mysql_query($q, $conn)){
if (!$result = $mysqli->query($q)){
print (mysql_error() . " SQL: $q\n");
print (substr_count($q, ',') + 1) . " Fields total.";
$problem_q = explode(',', $q);
$q1 = "desc $db.$table";
//$result1 = mysql_query($q1, $conn);
$result1 = $mysqli->query($q1);
$columns = array();
$i = 1;
while ($row1 = $result1->fetch_assoc()){
$columns[$i] = $row1['Field'];
$i++;
}
$i = 1;
foreach ($problem_q as $pq){
print "$i column: {$columns[$i]} data: $pq\n";
$i++;
}
die();
}
}
}
$mysqli->close();
?>

<?php
$mysqli = new mysqli("localhost", "DBusername", "DBpassword", "tableName");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$tbl = "yourTableName";
$db = 'YourDBName';
// Path to dbase file
$db_path = "/path/dbaseFileName.dbf";
// Open dbase file
$dbh = dbase_open($db_path, 0)
or die("Error! Could not open dbase database file '$db_path'.");
// Get column information
$column_info = dbase_get_header_info($dbh);
$line = array();
foreach($column_info as $col) {
switch($col['type']){
case 'character':
$line[]= "`$col[name]` VARCHAR( $col[length] )";
break;
case 'number':
$line[]= "`$col[name]` FLOAT";
break;
case 'boolean':
$line[]= "`$col[name]` BOOL";
break;
case 'date':
$line[]= "`$col[name]` DATE";
break;
case 'memo':
$line[]= "`$col[name]` TEXT";
break;
}
}
$str = implode(",",$line);
$sql = "CREATE TABLE `$tbl` ( $str );";
//mysql_select_db($db,$conn);
//mysql_query($sql,$conn);
$mysqli->query($sql);
set_time_limit(0); // I added unlimited time limit here, because the records I imported were in the hundreds of thousands.
// This is part 2 of the code
import_dbf($db, $tbl, $db_path, $mysqli);
function import_dbf($db, $table, $dbf_file,$mysqli){
//global $conn;
global $mysqli;
if (!$dbf = dbase_open ($dbf_file, 0)){ die("Could not open $dbf_file for import."); }
$num_rec = dbase_numrecords($dbf);
$num_fields = dbase_numfields($dbf);
$fields = array();
for ($i=1; $i<=$num_rec; $i++){
$row = #dbase_get_record_with_names($dbf,$i);
$q = "insert into $db.$table values (";
foreach ($row as $key => $val){
if ($key == 'deleted'){ continue; }
$q .= "'" . addslashes(trim($val)) . "',"; // Code modified to trim out whitespaces
}
if (isset($extra_col_val)){ $q .= "'$extra_col_val',"; }
$q = substr($q, 0, -1);
$q .= ')';
//if the query failed - go ahead and print a bunch of debug info
// if (!$result = mysql_query($q, $conn)){
if (!$result = $mysqli->query($q)){
print (mysql_error() . " SQL: $q\n");
print (substr_count($q, ',') + 1) . " Fields total.";
$problem_q = explode(',', $q);
$q1 = "desc $db.$table";
//$result1 = mysql_query($q1, $conn);
$result1 = $mysqli->query($q1);
$columns = array();
$i = 1;
while ($row1 = $result1->fetch_assoc()){
$columns[$i] = $row1['Field'];
$i++;
}
$i = 1;
foreach ($problem_q as $pq){
print "$i column: {$columns[$i]} data: $pq\n";
$i++;
}
die();
}
}
}
$mysqli->close();
?>

Related

Saving data from localhost to online

I am trying to save my data coming from my localhost database to our live server database using PHP. I am getting a successful response but whenever I try to check the our live database server there is no data in it or the data was not inserted or updated.
Also the response I get is this "Import successful! Found a total of 4 records in patient.file" even though the file I am importing is only to data.
Here is my code:
<?php
//============FUNCTIONS=================
function export_table($target_table,$sdate,$edate,$station){
$i = mysql_num_rows(mysql_query("DESCRIBE $target_table"));
$get_columns = mysql_query("SHOW COLUMNS FROM " . $target_table);
while($row_columns = mysql_fetch_array($get_columns)){
$column_name = $row_columns['Field'] . "|";
$csv_output .= $column_name;
}
$csv_output = rtrim($csv_output, "|");
$csv_output .= "\r\n";
$values = mysql_query("SELECT * FROM ".$target_table." WHERE
dateEncoded >= '2017-07-01' and dateEncoded <= '2017-07-07'");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
if($rowr[$j] == NULL){$rowr[$j] = "NULL";}
if($j==($i-1)){$csv_output .= str_replace(array("\n", "\r"), '', $rowr[$j]);
}else{$csv_output .= str_replace(array("\n", "\r"), '', $rowr[$j])."|";}
}// end for
$csv_output .= "\r\n";
}// end while
return $csv_output;
}// end function export_table
//========CREATION OF THE FILE===========================
include_once "../ewcfg8.php";
include_once "../dbcon.php";
date_default_timezone_set('Asia/Manila');
ini_set('memory_limit', '-1');
set_time_limit(0);
// $startdate = '2017-06-01';
// $enddate = '2017-07-07'; ;
// $defaulStation = $_POST['defaultStation'];
$tables = array('patient',
'tb_adr',
'tb_case',
'tb_casecomment',
'tb_comorbidity',
'tb_consilium',
'tb_consultations',
'tb_contact',
'tb_pe',
'tb_prescript',
'tb_prevcase',
'tb_resultculture',
'tb_resultgx',
'tb_resultdst',
'tb_resultdstdrug',
'tb_resulthiv',
'tb_resultxray',
'tb_symptom',
'tb_resultdssm',
'tb_dot');
//put tables in an array within an array(make a multi-dimensional array)
$dl_table = array();
foreach ($tables as $table) {
$content = export_table($table,$startdate,$enddate,$defaulStation);
$dl_table[$table] = $content;//multi-dimensional array
}
//#mysql_close($con); //close localhost connection
//=========INSERTING VALUES TO DATABASE===============
//===============Open New Connection And Connect to Live Database========
$dbhost = "http/mywebsite.example";
$localport = "3306";
$dbuser = "user";
$dbpass = "12345";
$dbname = "myonlinedb";
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname, $conn);
$fieldseparator = "|";
$lineseparator = "\n";
foreach ($tables as $table) {
$databasetable = $table;
$csvfile = $dl_table[$table]; //variable that hold the multi-dimensional array
$lines = 0;
$header = 0;
$queries = "";
$linearray = array();
$columns = array();
//====================================Get the Columns (First line in the CSV)===================================
while(($header == 0 && $columns = fgetcsv(${$table},0,"|")) != false){
$header = 1;
$num_columns = count($columns);
$list_columns = "";
for ($c=0; $c < $num_columns; $c++) {
$list_columns .= "`" . $columns[$c] . "`" . ", ";
}
$list_columns = substr($list_columns,0,-2);
//echo $list_columns . "<br /><br />";
break;
}// close while(($columns = fgetcsv($file,0,"|")) !== false && $header == 0)
//====================================Get the contents of the CSV===================================
//Set the header to skip the first row
$header = 0;
//opening the csv file
// $size = filesize($csvfile);
// echo $size;
// if(!$size) {echo "File is empty.\n";}
// $csvcontent = fread($file,$size);
// fclose($file);
//foreach(split($lineseparator,$csvcontent) as $line)
foreach(explode($lineseparator,$csvfile) as $line) {
//if($header == 0){
//$header = 1;
//}else{
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
//*********get the csvID id and the columns in the db table to know if an insert or update will be performed****************
if ($databasetable == "patient"){
$csvID = $linearray[2];
$searchField = "patientID";
}else if($databasetable == "tb_case"){
$csvID = $linearray[0];
$searchField = "caseID";
}else if($databasetable == "tb_resultdstdrug"){
$csvID = $linearray[1]. $linearray[2];
$searchField = "CONCAT(caseIDplus, series)";
}else{
$csvID = $linearray[1]. $linearray[2];
$searchField = "CONCAT(caseID, series)";
}
//***********convert id of each row to 0*******************************
if($databasetable != "tb_case"){$linearray['0'] = '';}
//*****************search the csvID in the database************************************
$searchID = mysql_query("SELECT * FROM $databasetable WHERE $searchField = '$csvID'");
//******************count the number of columns in csv and the db table**************
$countcsv = count($linearray);
$countColumns = $num_columns;
//$countColumns = mysql_num_fields($searchID);
//****************count if the csvID exists in the database********************************
$countResults = mysql_num_rows($searchID);
//*************************get the date encoded in the csv and db table***************
$row = mysql_fetch_assoc($searchID);
$db_dateEncoded = $row['dateEncoded'];
if($databasetable == "tb_dot"){$csv_dateEncoded = $linearray[($countcsv-3)];}
else{$csv_dateEncoded = $linearray[($countcsv-2)];}
//*****************if else statement for checking number of fields****************************************
if ($countResults > 0){
//if a result was found, UPDATE the row
if ($csv_dateEncoded>$db_dateEncoded){
// if table is dot, delete all dot of the tb_case
$query = "UPDATE $databasetable SET ";
$i = 1;
while ($i < $countColumns){
$meta = mysql_fetch_field($searchID, $i);
if($linearray[$i] == "NULL"){
$query .= $columns[$i] . "=" . $linearray[$i];
//if last field
if($i == ($countColumns-1)){$query .= " WHERE $searchField = '$csvID';";}else{$query .= ",";}
}else{
$query .= $columns[$i] . "='" . $linearray[$i];
//if last field
if($i == ($countColumns-1)){$query .= "' WHERE $searchField = '$csvID';";}else{$query .= "',";}
}//end if($linearray[$i] == "NULL")
$i = $i + 1;
}//close while ($i < $countColumns)
}// end if($csv_dateEncoded>=$db_dateEncoded)
}else{//if no id was found, INSERT a new row
//$query = "INSERT INTO $databasetable VALUES(";
if($databasetable == 'patient'){$query = "INSERT INTO $databasetable VALUES(";}
else{$query = "INSERT INTO $databasetable ($list_columns) VALUES(";}
$i = 0;
while ($i < $countColumns){
if($linearray[$i] == "NULL"){
$query .= $linearray[$i];
if($i == ($countColumns-1)){$query .= ");";}else{$query .= ",";}
}else{
$query .= "'" . $linearray[$i];
if($i == ($countColumns-1)){$query .= "');";}else{$query .= "',";}
}
$i = $i + 1;
}//end While
}// close if ($countResults > 0){
//$queries .= $query . "\n";
//print "$query<br />";
#mysql_query($query);
//}//close if($header == 0)
}// close foreach(split($lineseparator,$csvcontent) as $line)
//unlink("data_uploading/files/" . $user . "/" . $databasetable . ".csv");
echo "Import successful! Found a total of $lines records in $table.file.\n<br /><br />";
//mysql_close($conn);
#mysql_close($con);
//====================================Get the Contents===================================
}//close foreach ($tables as $table)
//rmdir("data_uploading/files/" . $user);
//==========END OF INSERTING VALUES TO DATABASE ===========

Copying Row, Losing NULL value

I have this working where it will copy the row, and then link the new row to the previous row.
Where my issue is, is in copying over the NULL values. When I run this all null values go into the new row as blank.
How would I get it to change the value to NULL if it was originally NULL?
$result = $mysqli->query("SELECT * FROM rdpricing WHERE psid = '$dupsid';");
if($result->num_rows >= "1"){
$count = $result->num_rows;
$cols = array();
$result = $mysqli->query("SHOW COLUMNS FROM rdpricing");
while ($r = $result->fetch_array(MYSQLI_ASSOC)) {
if (!in_array($r["Field"], array("rdpid", "psid", "rdold"))) { //Excluding these columns
$cols[] = $r["Field"];
}
}
// Build and do the insert
$result = $mysqli->query("SELECT * FROM rdpricing WHERE psid = '$dupsid';");
while ($r = $result->fetch_array(MYSQLI_ASSOC)) {
$insertSQL = "INSERT INTO rdpricing (" . implode(", ",$cols) . ", rdold) VALUES (";
$count = count($cols);
foreach($cols as $counter=>$col) {
**// This is where I Believe it needs to happen, and what I have attempted, and it is NOT working**
if(empty($r[$col]) || is_null($r[$col]) || $r[$col] == ""){
$r[$col] = NULL;
}
$insertSQL .= "'" . $mysqli->real_escape_string($r[$col]) . "'";
if ($counter < ($count - 1)) {
$insertSQL .= ", ";
}
} // END foreach
$insertSQL .= ", '".$r["rdpid"]."');";
$mysqli->query($insertSQL);
if ($mysqli->affected_rows < 1) {
printf("%s\n", $mysqli->error);
} else {
}
$new_id = $mysqli->insert_id;
$statement = $mysqli->prepare("UPDATE rdpricing SET `psid`=? WHERE `rdpid`=?");
$statement->bind_param('ss', $new_psid, $new_id);
// Execute the prepared query.
$statement->execute();
$statement->close();
}
}
Generated from info in the comments:
#reset/create before the foreach, create an empty array
$insertSQLValues=array();
#in the foreach do some on given type
if(is_null($r[$col])){#real null
$r[$col] = "null";
} else if (empty($r[$col]) || $r[$col] == ""){#empty values
$r[$col] = "''";
} else {#standart data
$r[$col] = "'".$mysqli->real_escape_string($r[$col])."'";
}
$insertSQLValues[]=$r[$col];
#later
$insertSQL .= implode(', ',$insertSQLValues).", '".$r["rdpid"]."');";
Hopefully you can merge that into your code.

backup mysql tables with php [duplicate]

This question already has answers here:
Export and Import all MySQL databases at one time
(13 answers)
Closed 2 years ago.
I would like to backup tables (with PHP) from a db if the table prefix is matching with a sub string. What I was trying and is not working
error_reporting(1);
$dbname = 'wp_dev';
if (!mysql_connect('127.0.0.1', 'root', '')) {
echo 'Connection Error';
exit;
}
$sql = "SHOW TABLES FROM $dbname LIKE 'wp_%'";
$result = mysql_query($sql);
if (!$result) {
echo "DB tables could not be listed\n";
echo 'MySQL Fehler: ' . mysql_error();
exit;
}
while ($row = mysql_fetch_row($result)) {
echo "<pre>Table: {$row[0]}\n</pre>";
system( 'mysqldump $dbname $row[0] > verlag_$row[0].sql');
}
mysql_free_result($result);
Here is a function for making bakups from db or only some tables
function &backup_tables($host, $user, $pass, $name, $tables = '*'){
$data = "\n/*---------------------------------------------------------------".
"\n SQL DB BACKUP ".date("d.m.Y H:i")." ".
"\n HOST: {$host}".
"\n DATABASE: {$name}".
"\n TABLES: {$tables}".
"\n ---------------------------------------------------------------*/\n";
$link = mysql_connect($host,$user,$pass);
mysql_select_db($name,$link);
mysql_query( "SET NAMES `utf8` COLLATE `utf8_general_ci`" , $link ); // Unicode
if($tables == '*'){ //get all of the tables
$tables = array();
$result = mysql_query("SHOW TABLES");
while($row = mysql_fetch_row($result)){
$tables[] = $row[0];
}
}else{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
foreach($tables as $table){
$data.= "\n/*---------------------------------------------------------------".
"\n TABLE: `{$table}`".
"\n ---------------------------------------------------------------*/\n";
$data.= "DROP TABLE IF EXISTS `{$table}`;\n";
$res = mysql_query("SHOW CREATE TABLE `{$table}`", $link);
$row = mysql_fetch_row($res);
$data.= $row[1].";\n";
$result = mysql_query("SELECT * FROM `{$table}`", $link);
$num_rows = mysql_num_rows($result);
if($num_rows>0){
$vals = Array(); $z=0;
for($i=0; $i<$num_rows; $i++){
$items = mysql_fetch_row($result);
$vals[$z]="(";
for($j=0; $j<count($items); $j++){
if (isset($items[$j])) { $vals[$z].= "'".mysql_real_escape_string( $items[$j], $link )."'"; } else { $vals[$z].= "NULL"; }
if ($j<(count($items)-1)){ $vals[$z].= ","; }
}
$vals[$z].= ")"; $z++;
}
$data.= "INSERT INTO `{$table}` VALUES ";
$data .= " ".implode(";\nINSERT INTO `{$table}` VALUES ", $vals).";\n";
}
}
mysql_close( $link );
return $data;
}
How to use:
// create backup
//////////////////////////////////////
$backup_file = 'db-backup-'.time().'.sql';
// get backup
$mybackup = backup_tables("myhost","mydbuser","mydbpasswd","mydatabase","*");
// save to file
$handle = fopen($backup_file,'w+');
fwrite($handle,$mybackup);
fclose($handle);
You can modify the line:
$result = mysql_query("SHOW TABLES");
for the table präfix
I set up simple functions 'openDb()' and get($SQL) to open databases and execute PHP mysql queries. There may be instances where the row by row copy is more useful but you can also use, if it works (using my simple functions above):
openDb($db,$user,$pw);
get("CREATE TABLE `TABLE1_backup` LIKE `TABLE1`");
get("INSERT INTO `TABLE1_backup` (SELECT * FROM `TABLE1`)");
(NB This is a skeletal description. Add DROPs etc as needed. The 'get' returns T/F depending on success so for debugging it may be necessary to test for false and provide the MySQLi_ERROR)
and with poo
<?php
//backup
//function &backup_tables($host, $user, $pass, $name, $tables = '*'){
function &backup_tables($host, $user, $pass, $name, $tables){
$data = "\n/*---------------------------------------------------------------".
"\n SQL DB BACKUP ".date("d.m.Y H:i")." ".
"\n HOST: {$host}".
"\n DATABASE: {$name}".
"\n TABLES: {$tables}".
"\n ---------------------------------------------------------------*/\n";
include "connexion.php";
$myquery="SET NAMES `utf8` COLLATE `utf8_general_ci`";
$result = $mylink->query($myquery);
if($tables == '*'){ //get all of the tables
$tables = array();
$myquery="SHOW TABLES";
$result = $mylink->query($myquery);
while($row = mysqli_fetch_row($result)){
$tables[] = $row[0];
}
}else{
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
foreach($tables as $table){
$data.= "\n/*---------------------------------------------------------------".
"\n TABLE: `{$table}`".
"\n ---------------------------------------------------------------*/\n";
$data.= "DROP TABLE IF EXISTS `{$table}`;\n";
$myquery="SHOW CREATE TABLE `{$table}`";
$result = $mylink->query($myquery);
$row = $result->fetch_row();
$data.= $row[1].";\n";
$myquery="SELECT * FROM `{$table}`";
$result = $mylink->query($myquery);
$num_rows = $result->num_rows;
if($num_rows>0){
$vals = Array(); $z=0;
for($i=0; $i<$num_rows; $i++){
$items = mysqli_fetch_row($result);
$vals[$z]="(";
for($j=0; $j<count($items); $j++){
if (isset($items[$j])) { $vals[$z].= "'".$mylink->real_escape_string($items[$j]) ."'"; } else { $vals[$z].= "NULL"; }
if ($j<(count($items)-1)){ $vals[$z].= ","; }
}
$vals[$z].= ")"; $z++;
}
$data.= "INSERT INTO `{$table}` VALUES ";
$data .= " ".implode(";\nINSERT INTO `{$table}` VALUES ", $vals).";\n";
}
}
$mylink->close();
return $data;
}
//***********
// called by :
$backup_file = 'db-backup-'.time().'.sql';
// get backup
$host = "yourhost";
$user = "youruser";
$pass = "your_pw";
$name = "your base";
$tables= 'your_table';
$mybackup = backup_tables($host,$user,$pass,$name,$tables);
// save to file
$handle = fopen($backup_file,'w+');
fwrite($handle,$mybackup);
fclose($handle);
//affichage des résultats, pour savoir si la modification a marchée:
echo("La sauvegarde à été correctement effectuée") ;
?>
where connection.php is :
<?php
$mylink = new mysqli("host", "user", "pw", "base");
if ($mylink->connect_errno) {
echo "Echec lors de la connexion à MySQL : " . $mylink->connect_error;
exit();
}
function backup_tables($tables = '*', $filepath) {
$data = "\n/*---------------------------------------------------------------" .
"\n SQL DB BACKUP " . date("d.m.Y H:i") . " " .
"\n HOST: {$host}" .
"\n DATABASE: {$name}" .
"\n TABLES: {$tables}" .
"\n ---------------------------------------------------------------*/\n";
mysql_query("SET NAMES `utf8` COLLATE `utf8_general_ci`"); // Unicode
if ($tables == '*') { //get all of the tables
$tables = array();
$result = mysql_query("SHOW TABLES");
while ($row = mysql_FetchRecordsFromCSV_row($result)) {
$tables[] = $row[0];
}
} else {
$tables = is_array($tables) ? $tables : explode(',', $tables);
}
foreach ($tables as $table) {
$data.= "\n/*---------------------------------------------------------------" .
"\n TABLE: `{$table}`" .
"\n ---------------------------------------------------------------*/\n";
$data.= "DROP TABLE IF EXISTS `{$table}`;\n";
$res = mysql_query("SHOW CREATE TABLE `{$table}`");
$row = mysql_fetch_row($res);
$data.= $row[1] . ";\n";
$result = mysql_query("SELECT * FROM `{$table}`");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
$vals = Array();
$z = 0;
for ($i = 0; $i < $num_rows; $i++) {
$items = mysql_fetch_row($result);
$vals[$z] = "(";
for ($j = 0; $j < count($items); $j++) {
if (isset($items[$j])) {
$vals[$z].= "'" . mysql_real_escape_string($items[$j]) . "'";
} else {
$vals[$z].= "NULL";
}
if ($j < (count($items) - 1)) {
$vals[$z].= ",";
}
}
$vals[$z].= ")";
$z++;
}
$data.= "INSERT INTO `{$table}` VALUES ";
$data .= " " . implode(";\nINSERT INTO `{$table}` VALUES ", $vals) . ";\n";
}
}
//mysql_close( $link );
$handle = fopen($filepath, 'w+');
fwrite($handle, $data);
fclose($handle);
}
Same as user3365179 but using PDO.
Change ISO-8859-1 to utf8
$mylink is in $GLOBALS['db_pdo']
function backup_tables_pdo($host, $user, $pass, $name, $tables) {
$data = "\n/*---------------------------------------------------------------".
"\n SQL DB BACKUP ".date("d.m.Y H:i")." ".
"\n HOST: {$_SERVER['SERVER_NAME']}".
"\n DATABASE: {$name}".
"\n TABLES: {$tables}".
"\n ---------------------------------------------------------------*/\n";
// include "connexion.php";
$myquery="SET NAMES `ISO-8859-1` COLLATE `latin1_spanish_ci`";
$result = $GLOBALS['db_pdo']->query($myquery);
if($tables == '*'){ //get all of the tables
$tables = array();
$myquery="SHOW TABLES";
$result = $GLOBALS['db_pdo']->query($myquery);
while($row = mysqli_fetch_row($result)){
$tables[] = $row[0];
}
} else {
$tables = is_array($tables) ? $tables : explode(',',$tables);
}
foreach($tables as $table) {
$data.= "\n/*---------------------------------------------------------------".
"\n TABLE: `{$table}`".
"\n ---------------------------------------------------------------*/\n";
$data.= "DROP TABLE IF EXISTS `{$table}`;\n";
$myquery="SHOW CREATE TABLE `{$table}`";
$result = $GLOBALS['db_pdo']->query($myquery);
$row = $result->fetch(); // fetch_row()
$data.= $row[1].";\n";
$myquery="SELECT * FROM `{$table}`";
$result = $GLOBALS['db_pdo']->query($myquery);
$num_rows = $result->rowCount(); // num_rows
if($num_rows>0) {
$vals = Array(); $z=0;
for($i=0; $i<$num_rows; $i++) {
$items = $result->fetch(PDO::FETCH_NUM); // mysqli_fetch_row($result)
//var_dump($items); exit;
$vals[$z]="(";
for($j=0; $j<count($items); $j++) {
if (isset($items[$j])) {
$vals[$z].= $GLOBALS['db_pdo']->quote($items[$j]); //real_escape_string($items
} else {
$vals[$z].= "NULL";
}
if ($j<(count($items)-1)){ $vals[$z].= ","; }
}
$vals[$z].= ")"; $z++;
}
$data.= "INSERT INTO `{$table}` VALUES ";
$data .= " ".implode(";\nINSERT INTO `{$table}` VALUES ", $vals).";\n";
}
}
return $data;
}

array pulling out no results

public function GetRoomTotalForDay($room, $date = null) {
if(!isset($date)) {
$date = date("Y-m-d");
}
// This function is going to return the number of shoes processed that day
// First of all work out which scanner number is required for the room
$scanner = $this->GetScannerNumber($room);
// Next generate the SQL
$sql = "SELECT `scanners.KordNo`, `scanners.BundleNumber`
FROM `scanners`
WHERE `scanners.Date` = '" . $date . "'
AND `scanners.Scanner` IN (";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$return[] = $row;
}
// It is more complicated for Kettering, Closing & Rushden, we need to filter the list
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanner.BundleNumber'] . "
ORDER BY `scanners.Date` DESC
LIMIT 1,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
// If scanner 7, it's been through bottom stock so need to find previous
if($row[0] == 7) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanners.BundleNumber'] . "
ORDER BY `scanners.Date` DESC
LIMIT 2,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
}
if($row[0] == 10 && $room == 3) {
$finalReturn[] = $x;
} elseif($row[0] == 11 && $room == 4) {
$finalReturn[] = $x;
} elseif($row[0] == 15 && $room == 5) {
$finalReturn[] = $x;
}
}
$return = $finalReturn;
}
// Now we have a list of tickets, we need to query how many pairs are in each ticket
$total = 0;
foreach($return as $x) {
$sql = "SELECT `QtyIssued`
FROM `ArchiveBundle`
WHERE `ArchiveBundle.KordNo` = '" . $x['scanners.KordNo'] . "'
AND `ArchiveBundle.BundleNumber` = '" . $x['scanners.BundleNumber'] . "';";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total += $row[0];
}
return $total;
}
I have edited the class above which pulls no results. However the original class below pulls results out. Please can someone help.
public function GetRoomTotalForDay($room, $date = null) {
if(!isset($date)) {
$date = date("Y-m-d");
}
// This function is going to return the number of shoes processed that day
// First of all work out which scanner number is required for the room
$scanner = $this->GetScannerNumber($room);
// Next generate the SQL
$sql = "SELECT `KordNo`, `BundleNumber`
FROM `scanners`
WHERE `Date` = '" . $date . "'
AND `Scanner` IN (";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$return[] = $row;
}
// It is more complicated for Kettering, Closing & Rushden, we need to filter the list
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `Scanner`
FROM `scanners`
WHERE `KordNo` = " . $x['KordNo'] . "
AND `BundleNumber` = " . $x['BundleNumber'] . "
ORDER BY `Date` DESC
LIMIT 1,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
// If scanner 7, it's been through bottom stock so need to find previous
if($row[0] == 7) {
$sql = "SELECT `Scanner`
FROM `scanners`
WHERE `KordNo` = " . $x['KordNo'] . "
AND `BundleNumber` = " . $x['BundleNumber'] . "
ORDER BY `Date` DESC
LIMIT 2,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
}
if($row[0] == 10 && $room == 3) {
$finalReturn[] = $x;
} elseif($row[0] == 11 && $room == 4) {
$finalReturn[] = $x;
} elseif($row[0] == 15 && $room == 5) {
$finalReturn[] = $x;
}
}
$return = $finalReturn;
}
// Now we have a list of tickets, we need to query how many pairs are in each ticket
$total = 0;
foreach($return as $x) {
$sql = "SELECT `QtyIssued`
FROM `ArchiveBundle`
WHERE `KordNo` = '" . $x['KordNo'] . "'
AND `BundleNumber` = '" . $x['BundleNumber'] . "';";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total += $row[0];
}
return $total;
}
The class above counts the amount of shoes produced. I have had to edit this class so it can exclude certain types of shoes but it does not seem to pull any results for some reason.
UPDATE.
This is the class scanners. This is what its currently at the moment. I'm fairly new to php and this code was writted by my predecessor.
<?php
class CHScanners {
var $conn;
// Constructor, connect to the database
public function __construct() {
require_once "/var/www/reporting/settings.php";
define("DAY", 86400);
if(!$this->conn = mysql_connect(DB_HOST, DB_USERNAME, DB_PASSWORD)) die(mysql_error());
if(!mysql_select_db(DB_DATABASE_NAME, $this->conn)) die(mysql_error());
}
public function ListRoomBundles($room, $date, $dateTo = null) {
// If dateTo hasn't been set, make it now
if(!isset($dateTo) or $dateTo == "") {
$dateTo = $date;
}
// Return an array with each bundle number and the quantity for each day
$scanner = $this->GetScannerNumber($room);
$sql = "SELECT * FROM `scanners` WHERE `Scanner` IN (";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0)
AND `Date` BETWEEN '" . $date . "' AND '" . $dateTo . "'
GROUP BY `KordNo`, `BundleNumber`;";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$sql = "SELECT `BundleReference`, `QtyIssued`, `WorksOrder`
FROM `ArchiveBundle`
WHERE `KordNo` = '" . $row['KordNo'] . "'
AND `BundleNumber` = '" . $row['BundleNumber'] . "';";
$result2 = mysql_query($sql);
while($row = mysql_fetch_array($result2)) {
if($row[0] != "") {
$final[] = $row;
} else {
$final[] = array("Can't find bundle number", "N/A");
}
}
}
return $final;
}
public function GetRoomTotalForDay($room, $date = null) {
if(!isset($date)) {
$date = date("Y-m-d");
}
// This function is going to return the number of shoes processed that day
// First of all work out which scanner number is required for the room
$scanner = $this->GetScannerNumber($room);
// Next generate the SQL
$sql = "SELECT `scanners.KordNo`, `scanners.BundleNumber`
FROM `scanners,TWOrder,Stock`
INNER JOIN TWORDER ON `scanners.KordNo` = `TWOrder.KOrdNo`
AND `scanners.Date` = '" . $date . "'
INNER JOIN Stock ON `TWOrder.Product` = `Stock.ProductCode`
AND `Stock.ProductGroup` NOT BETWEEN 400 AND 650
AND `scanners.Scanner` IN (
ORDER BY `scanners.KordNo' ASC";
foreach($scanner as $x) {
$sql .= $x . ",";
}
$sql .= "0);";
// And query the database
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$return[] = $row;
}
// It is more complicated for Kettering, Closing & Rushden, we need to filter the list
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanners.BundleNumber'] . "
ORDER BY `scanners.Date` DESC
LIMIT 1,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
// If scanner 7, it's been through bottom stock so need to find previous
if($row[0] == 7) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanners.BundleNumber'] . "
ORDER BY `Date` DESC
LIMIT 2,1;";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
}
if($row[0] == 10 && $room == 3) {
$finalReturn[] = $x;
} elseif($row[0] == 11 && $room == 4) {
$finalReturn[] = $x;
} elseif($row[0] == 15 && $room == 5) {
$finalReturn[] = $x;
}
}
$return = $finalReturn;
}
// Now we have a list of tickets, we need to query how many pairs are in each ticket
$total = 0;
foreach($return as $x) {
$sql = "SELECT `QtyIssued`
FROM `ArchiveBundle`
WHERE `KordNo` = '" . $x['scanners.KordNo'] . "'
AND `BundleNumber` = '" . $x['scanners.BundleNumber'] . "';";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
$total += $row[0];
}
return $total;
}
// We need a function to select the previous Monday from a given date
public function GetPreviousMonday($timestamp) {
if(date("N", $timestamp) == 1) {
return $timestamp;
} elseif(in_array(date("N", $timestamp), array(2, 3, 4, 5))) {
return $timestamp - (date("N", $timestamp)-1)*DAY;
} elseif(in_array(date("N", $timestamp), array(6, 7))) {
return $timestamp + (date("N", $timestamp)*(-1)+8)*DAY;
} else {
return false;
}
}
public function GetRoomName($room) {
// Return the room name from the room number
switch($room) {
case 1:
return "Skin Room";
case 2:
return "Clicking Room";
case 3:
return "Kettering";
case 4:
return "Closing Room";
case 5:
return "Rushden";
case 6:
return "Assembly Room";
case 7:
return "Lasting Room";
case 8:
return "Making Room";
case 9:
return "Finishing Room";
case 10:
return "Shoe Room";
}
}
public function GetDueDateForWorksOrder($worksOrderNumber) {
$sql = "SELECT `DueDate`
FROM `TWOrder`
WHERE `WorksOrderNumber` = '" . $worksOrderNumber . "';";
mysql_select_db(DB_DATABASE_NAME, $this->conn);
$result = mysql_query($sql, $this->conn);
$row = mysql_fetch_row($result);
return $row[0];
}
private function GetScannerNumber($room) {
// Get the room number from the scanner number
switch($room) {
case 1:
$scanner = array(3);
break;
case 2:
$scanner = array(10,11,15);
break;
case 3:
$scanner = array(5);
break;
case 4:
$scanner = array(5);
break;
case 5:
$scanner = array(5);
break;
case 6:
$scanner = array(6);
break;
case 7:
$scanner = array(9);
break;
case 8:
$scanner = array(8);
break;
case 9:
$scanner = array(12);
break;
case 10:
$scanner = array(14);
break;
default:
$scanner = array(0);
break;
}
return $scanner;
}
}
?>
You have a typo - a letter is missing in the last line of this block of code:
if(in_array($room, array(3,4,5))) {
foreach($return as $x) {
$sql = "SELECT `scanners.Scanner`
FROM `scanners`
WHERE `scanners.KordNo` = " . $x['scanners.KordNo'] . "
AND `scanners.BundleNumber` = " . $x['scanner.BundleNumber'] .
Here the array item should be $x['scanners.BundleNumber'].

FilePutContents in PHP

I cant put my file into a directory...
$swfpath = "swf/";
file_put_contents($swfpath . $swf, file_get_contents($swf_url));
it goes into /example.swf instead of /swf/example.swf
<?php
include "mysql.php";
echo "you shouldn't be here";
$gt = $_POST["game_tag"];
connect() or die (mysql_error());
$pubId = 'censored';
if (!$gt)
exit;
$data = file_get_contents("http://www.mochimedia.com/feeds/games/$pubId/$gt/?format=xml");
$response = new DOMDocument();
$response->loadXML($data);
$obj = $response->getElementsByTagName("entry")->item(0);
$sql = "INSERT INTO games (title, swfname, description, category, thumb) VALUES('";
$sql .= addslashes($obj->getElementsByTagName("title")->item(0)->nodeValue) . "','";
$swf_url = $obj->getElementsByTagName("link")->item(1)->getAttribute("href");
$swf = md5($sql);
$swfpath = "swf/";
file_put_contents($swfpath . $swf, file_get_contents($swf_url));
echo " URL = $swf_url";
$sql .= "$swf','"; //swfpath is the path of the directory where you store the swf files
$sql .= addslashes($obj->getElementsByTagName("description")->item(0)->nodeValue) . "','";
switch($obj->getElementsByTagName("category")->item(0)->nodeValue) {
case "Action" : $sql .= "act','"; break;
case "Shooting" : $sql .= "s','"; break;
case "Shooter" : $sql .= "s','"; break;
case "Classic" : $sql .= "c','"; break;
case "Arcade" : $sql .= "a','"; break;
default : $sql .= "m','"; break;
}
include "functions.php";
$thumbnail_url = $obj->getElementsByTagName("thumbnail")->item(0)->getAttribute("url");
$thumb = substr($thumbnail_url, -4, 4);
$thumbs = "".$gt."$thumb";
$thumbpath = "thumbs/";
file_put_contents($thumbpath . $thumbs, file_get_contents($thumbnail_url));
$sql .= "$thumbs');"; //thumbpath is the path of the directory where you store the thumb files
mysql_query("$sql") or die (mysql_error());
//insert the $sql to your database
?>

Categories