I have used the following code to read the data of exceltodb.xlsx file and import it into the table city of database world. The library to read the file is PHPExcel which is very common library.The code I found is as follows but the code is executing but the row is not added into the database.
<?php
include 'PHPExcel-develop/Classes/PHPExcel/IOFactory.php';
$inputFileName = 'exceltodb.xlsx';
// Read your Excel workbook
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load('exceltodb.xlsx');
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 1; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
// Insert row data array into your database of choice here
mysql_connect('localhost','root','');
mysql_select_db('world');
mysql_query('insert into city("city","id","stateid","countryid") values("$rowData")');
}
?>
This code segment will upload your xml data sheet in to a particular location in the server:
<?php
$uploadedStatus = 0;
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
if (file_exists($_FILES["file"]["name"])) {
unlink($_FILES["file"]["name"]);
}
$storagename = "discussdesk.xlsx";
move_uploaded_file($_FILES["file"]["tmp_name"], $storagename);
$uploadedStatus = 1;
}
} else {
echo "No file selected <br />";
}
}
?>
This will upload the data taken from xml to the database:
<?php
/************************ YOUR DATABASE CONNECTION START HERE ****************************/
define ("DB_HOST", "localhost"); // set database host
define ("DB_USER", ""); // set database user
define ("DB_PASS",""); // set database password
define ("DB_NAME",""); // set database name
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
$db = mysql_select_db(DB_NAME, $link) or die("Couldn't select database");
$databasetable = "YOUR_TABLE";
/************************ YOUR DATABASE CONNECTION END HERE ****************************/
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
// This is the file path to be uploaded.
$inputFileName = 'discussdesk.xlsx';
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++){
$userName = trim($allDataInSheet[$i]["A"]);
$userMobile = trim($allDataInSheet[$i]["B"]);
$query = "SELECT name FROM YOUR_TABLE WHERE name = '".$userName."' and email = '".$userMobile."'";
$sql = mysql_query($query);
$recResult = mysql_fetch_array($sql);
$existName = $recResult["name"];
if($existName=="") {
$insertTable= mysql_query("insert into YOUR_TABLE (name, email) values('".$userName."', '".$userMobile."');");
Related
I have been trying to generate excel of database earlier I was trying this with mysql And the code was working but when I started trying with SQL-SERVER I am facing several issues Like excel is getting generated but with only column names it is unable to fetch data stored inside it and my error log is also not generating anything I am sharing my code too except the designing part .. feel free to edit my code and any help would be highly appreciated
<?php
session_start();
date_default_timezone_set("Asia/Kolkata");
ini_set('display_errors',1);
ini_set('log_errors',1);
ini_set('error_log',dirname(__FILE__).'/errorlog.txt');
error_reporting(E_ALL);
$serverName = "192.168.22.68"; //serverName\instanceName
$connectionInfo = array( "Database"=>"Interopdb", "UID"=>"uatkrasqluser", "PWD"=>"CV!u#t2018");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if($conn) {
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\Writer\Xls;
use PhpOffice\PhpSpreadsheet\Writer\Csv;
if(isset($_POST['export_excel_btn']))
{
$file_ext_name = $_POST['export_file_type'];
$fileName = "student-sheet";
$student = "SELECT * FROM priyat";
$query_run = sqlsrv_query($conn, $student, array(), array("Scrollable"=>"buffered"));
if(sqlsrv_num_rows($query_run) > 0)
{
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'ID');
$sheet->setCellValue('B1', 'Full Name');
$sheet->setCellValue('C1', 'Email');
$sheet->setCellValue('D1', 'Phone');
$sheet->setCellValue('E1', 'Course');
$rowCount = 2;
if (is_array($query_run) || is_object($query_run))
{
foreach($query_run as $data)
{
$sheet->setCellValue('A'.$rowCount, $data['id']);
$sheet->setCellValue('B'.$rowCount, $data['fullname']);
$sheet->setCellValue('C'.$rowCount, $data['email']);
$sheet->setCellValue('D'.$rowCount, $data['phone']);
$sheet->setCellValue('E'.$rowCount, $data['course']);
$rowCount++;
while($row = sqlsrv_fetch_array($query_run, SQLSRV_FETCH_ASSOC)) {
var_dump($row);
}
}
}
if($file_ext_name == 'xlsx')
{
$writer = new Xlsx($spreadsheet);
$final_filename = $fileName.'.xlsx';
}
elseif($file_ext_name == 'xls')
{
$writer = new Xls($spreadsheet);
$final_filename = $fileName.'.xls';
}
elseif($file_ext_name == 'csv')
{
$writer = new Csv($spreadsheet);
$final_filename = $fileName.'.csv';
}
// $writer->save($final_filename);
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attactment; filename="'.urlencode($final_filename).'"');
$writer->save('php://output');
}
else
{
$_SESSION['message'] = "No Record Found";
header('Location: index.php');
exit(0);
}
}
?>
sqlsrv_query only returns the cursor to the statement. You can't itereate over the cursor. To itereate over the results you can use:
//Fetching Data by array
while($row = sqlsrv_fetch_array($query_run, SQLSRV_FETCH_ASSOC)) {
var_dump($row);
}
Or
//Fetching Data by object
while($row = sqlsrv_fetch_object($query_run)) {
var_dump($row);
}
I want to upload the contents of a CSV while one PHP page is running. I don't want any browse button to upload the CSV. Whenever the page is running the page should find the CSV which the path is already defined in the PHP page and contents should be inserted into the table. Now I am getting error related with fopen.
Here is my code
<?php
//database connection details
$connect = mysql_connect('localhost', 'root', '');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid = mysql_select_db('test', $connect);
// path where your CSV file is located
define('CSV_PATH', 'D:/xamp/htdocs/test/');
// Name of your CSV file
$csv_file = CSV_PATH . "test.csv";
echo $csv_file;
if (($handle = fopen($csv_file, "r")) !== FALSE) {
fgetcsv($handle);
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
for ($c = 0; $c < $num; $c++) {
$col[$c] = $data[$c];
}
$col1 = $col[0];
$col2 = $col[1];
$col3 = $col[2];
$col4 = $col[3];
$col5 = $col[4];
$col6 = $col[5];
// SQL Query to insert data into DataBase
$query = "INSERT INTO testcsv(Line,Part No,Make,Model,Year,Part Type) VALUES('" . $col1 . "','" . $col2 . "','" . $col3 . "','" . $col4 . "','" . $col5 . "','" . $col6 . "')";
$s = mysql_query($query, $connect);
}
fclose($handle);
}
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
I am getting this error
Warning: fopen(D:/xamp/htdocs/test/test.csv): failed to open stream: No such file or directory in D:\xamp\htdocs\test\test.php on line 22
File data successfully imported to database!!
Can anyone help me?
I'm not sure why you are getting that particular error - one might assume that the file does not exist or that the directory is not readable but you are using the now deprecated mysql_ functions and directly embedding variables in the sql - thus making it vulnerable to sql injection. However, as this looks to be only a test that is probably not an issue.
The preferred method for this type of thing would be to use either mysqli or PDO in conjunction with prepared statements - below is an example of how you might implement that - I tested this with different data and database details and it seemed to work fine.
define('CSV_PATH','D:/xamp/htdocs/test/');
$filepath = CSV_PATH . "test.csv";
/* database connection details */
$host = 'localhost';
$uname = 'xxx';
$pwd = 'xxx';
$db = 'xxx';
/* create db connection */
$con = new mysqli( $host, $uname, $pwd, $db );
/* construct required sql statement */
$sql='insert into `testcsv` (`Line`,`Part No`,`Make`,`Model`,`Year`,`Part Type`) values (?,?,?,?,?,?)';
/* create prepared statement */
$stmt=$con->prepare( $sql );
if( !$stmt ){
echo 'error preparing sql statement!';
$con->close();
} else {
/* bind the columns to variables which will be populated later */
/* use "i" for integer and "s" for string values */
$stmt->bind_param( 'ssssss', $line,$part,$make,$model,$year,$type );
/* access csv file */
$file=new SplFileObject( $filepath );
/* Process each row of the csv file */
while( !$file->eof() ) {
/* read the line into a variable */
$data=$file->fgetcsv();
if( !empty( $data ) ){
/* assign a variable to each field value for this row */
list( $line,$part,$make,$model,$year,$type )=$data;
/* execute statement with the now defined variables */
$stmt->execute();
}
}
/* tidy up */
$stmt->close();
$con->close();
echo 'database updated with new records from csv';
}
I have a script to upoad an excel file and insert data from the xlsx file to a mysql table . It is like this
<?php
require_once('Connections/met.php');
$file = './uploads/windrose_data.xlsx';
if (move_uploaded_file($_FILES['uploadfile']['tmp_name'], $file)) {
$msg="File upload successful";
$db=mysql_select_db($database_met,$met);
set_include_path(get_include_path() . PATH_SEPARATOR . 'Classes/');
include 'PHPExcel/IOFactory.php';
// This is the file path to be uploaded.
$inputFileName = $file;
try {
$objPHPExcel = PHPExcel_IOFactory::load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
$arrayCount = count($allDataInSheet); // Here get total count of row in that Excel sheet
for($i=2;$i<=$arrayCount;$i++){
$date = trim($allDataInSheet[$i]["A"]);
$time = trim($allDataInSheet[$i]["B"]);
$dir = trim($allDataInSheet[$i]["C"]);
$spd = trim($allDataInSheet[$i]["D"]);
$insertTable= mysql_query("insert into wr_copy (date,time,dir,spd) values('$date', '$time',$dir,$spd)") or die(mysql_error());
$msg=$i-1." records inserted into the table";
}
echo $msg;
} else {
echo "Upload Failed";
}
?>
here for each row in excel one insert statement is executed., then I am sending a response using the iteration variable as the number of records inserted. There are two issues, one, I want to use a single insert statement which can be used for inserting all the rows in excel. second issue is using iterating variable values as no. of records can be a problem because, the query may not execute if there is any error in data. Can anybody suggest a work around for this?
For creating the one statement:
$statement = 'insert into wr_copy (date,time,dir,spd) values';
$values = [];
for($i=2;$i<=$arrayCount;$i++){
$date = trim($allDataInSheet[$i]["A"]);
$time = trim($allDataInSheet[$i]["B"]);
$dir = trim($allDataInSheet[$i]["C"]);
$spd = trim($allDataInSheet[$i]["D"]);
$values[] = "('$date', '$time',$dir,$spd)";
}
$statement .= implode(',',$values);
To get the real numbers of records that are inserted (i copied the example from here and change it):
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
/* prepare statement */
if ($stmt = $mysqli->prepare($statement)) {
/* execute statement */
$stmt->execute();
printf("rows inserted: %d\n", $stmt->affected_rows);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
I have an admin store dashboard with an update button that triggers a php file which empties a mySQL database that then puts in new data from three .txt files (they are new stores). There is an issue where the table just gets wiped and/or the data from the .txt file is not being sent. I recently upgraded my PHP to 5.4 from 5.3 and am unsure what the issue is. Can anyone recommend me a suggestion on how to fix this issue?
PHP:
<?php
header('Content-Type: application/json; charset=UTF-8');
$argv = $_SERVER['argv'];
$totalArgv = count($argv);
// Use PDO to connect to the DB
$dsn = 'mysql:dbname=busaweb_stores;host=127.0.0.1';
$dsn_training = 'mysql:dbname=busaweb_busaedu;host=127.0.0.1';
$user = 'busaweb_*****';
$password = '*****';
try {
$dbs = new PDO($dsn, $user, $password);
$dbt = new PDO($dsn_training, $user, $password);
$dbs->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo 'Connected to SQL Server';
}
catch (PDOException $e) {
die_with_error('PDO Connection failed: ' . $e->getMessage());
}
//Check request
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "move":
move_files();
echo_success("Files have been moved.");
break;
case "update-stores":
$count = update_stores_db($dbs);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
case "geocode":
$count = geocode_remaining($dbs);
echo_success($count . " stores geocoded.");
break;
case "update-training":
update_training_db($dbt);
echo_success("Training DB Updated.");
break;
case "update-all":
$count = update_stores_db($dbs);
update_training_db($dbt);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
case "backup":
$backupFile = backup_db();
echo_success("DB Backed Up: <br>" . $backupFile);
break;
default:
//Close PDO Connections
$dbs = null;
$dbt = null;
break;
}
}
}
//if being executed from the shell, update all
else if($totalArgv > 0){
$count = update_stores_db($dbs);
update_training_db($dbt);
echo_success("DB Updated.<br>" . $count . " Stores Geocoded.");
break;
};
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
//Error handling
function die_with_error($error) {
$return = array(
"status" => "Failed",
"data" => $error
);
//Close PDO Connections
$dbs = null;
$dbt = null;
die(json_encode($return));
}
function echo_success($message){
$return = array(
"status" => "OK",
"data" => $message
);
$return["json"] = json_encode($return);
echo json_encode($return);
//Close PDO Connections
$dbs = null;
$dbt = null;
}
//Move all files
function move_files(){
try {
move_file('sfinder/StoreList.txt');
move_file('sfinder/StoreProductIndex.txt');
move_file('sfinder/StoreTypeIndex.txt');
move_file('training/TrainingCustomerList.txt');
}
catch(Exception $e){
die_with_error($e->getMessage());
}
//sleep(1);
//Return JSON
$return["json"] = json_encode($return);
echo json_encode($return);
}
//Move a file
function move_file($filename){
$source ="/home/busaweb/public_html/b3/" . $filename;
$dest = "/home/busaweb/public_html/adminportal/includes/sfupdate/" . $filename;
if(!copy($source, $dest)){
throw new Exception("Failed to copy file: " . $filename);
}
else{
//echo "Successfully moved $filename.<br>";
}
}
//Empty a SQL Table
function empty_table($dbconnection, $tablename){
try{
$sql = "TRUNCATE TABLE " . $tablename;
$sth = $dbconnection->prepare($sql);
//$sth->bindParam(':tablename', $tablename, PDO::PARAM_STR);
// The row is actually inserted here
$sth->execute();
//echo " [+]Table '" . $tablename . "' has been emptied.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
//Import CSV file from JDE to DB
function load_csv($dbconn, $filename, $tablename){
try{
$sql = "LOAD DATA LOCAL INFILE '/home/busaweb/public_html/adminportal/includes/sfupdate/" . $filename . "' INTO TABLE " . $tablename . " FIELDS TERMINATED BY '\\t' ENCLOSED BY '\"' ESCAPED BY '\\\' LINES TERMINATED BY '\\n'";
$sth = $dbconn->prepare($sql);
// The row is actually inserted here
$sth->execute();
//echo " [+]CSV File for '" . $tablename . "' Table Imported.<br>";
$sth->closeCursor();
}
catch(PDOException $e) {
die_with_error($e->getMessage());
}
}
function update_stores_db($dbs){
move_files();
empty_table($dbs, "stores");
load_csv($dbs, 'sfinder/StoreList.txt', 'stores');
empty_table($dbs, 'stores_product_type_link');
load_csv($dbs, 'sfinder/StoreProductIndex.txt', 'stores_product_type_link');
empty_table($dbs, 'stores_store_type_link');
load_csv($dbs, 'sfinder/StoreTypeIndex.txt', 'stores_store_type_link');
return $count;
}
function update_training_db($dbt){
move_file('training/TrainingCustomerList.txt');
empty_table($dbt, 'customers');
load_csv($dbt, 'training/TrainingCustomerList.txt', 'customers');
}
}
?>
In PHP, I am looping through an excel file and inserting it into an MSSQL database. I am getting this error:
Uncaught exception 'PHPExcel_Exception' with message 'Invalid cell coordinate A'
I don't get this error if I only run one of the queries in the loop. Separately, both queries work. So I am pretty sure it has to do with the fact that the 2 queries are running. With the following code, there is one row inserted in both tables and then the error. Any ideas on how to fix this?
Heres the code...
$dbc = odbc_connect(DB_DRIVER, DB_USER, DB_PASSWORD);
$inputFileName = 'lib/test.xlsx';
try {
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
} catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
// Get worksheet dimensions
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
// Loop through each row of the worksheet in turn
for ($row = 2; $row <= $highestRow; $row++){
// Read a row of data into an array
$rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row,
NULL,
TRUE,
FALSE);
$name = ms_escape_string($rowData[0][0]);
$city = ms_escape_string($rowData[0][2]);
$state = ms_escape_string($rowData[0][3]);
$phone = ms_escape_string($rowData[0][4]);
$website = ms_escape_string($rowData[0][5]);
$profit_status = ms_escape_string($rowData[0][6]);
$query = "insert into account2 ([name], [city], [state], [phone], [website], [type], [created_by], [last_modified_by])
values ('$name', '$city', '$state', '$phone', '$website', '6', '3', '3')
SELECT SCOPE_IDENTITY() AS ins_id";
$data = odbc_exec($dbc, $query);
if (odbc_next_result($data)){
while ($row = odbc_fetch_object($data)) {
$account_id = $row->ins_id;
}
$query = "insert into account_hic2 (account_id, profit_status)
values ('$account_id', '$profit_status')";
}
$data2 = odbc_exec($dbc, $query);
odbc_free_result($data);
odbc_free_result($data2);
}
The error message suggests that you're mis-setting the value of $row at some point, perhaps setting it to null, or to an empty string...
... or perhaps to a resource, as you're using the same variable name in your database fetch in the same loop where you're using it to keep track of the Excel row number