Using PHPEXCEL with SQLSRV - php

I am looking into a way of taking a pre-defined order template (XLSX), which my customer completes and uploads, which then uses PHP Excel to insert the data into my sql database.
I have this working fine using mysql, but really need it to work with sql server, as our database (which pre-dates me) is sql server.
The code I am using for mysql is:
if(isset($_POST['submit'])) {
if(isset($_FILES['uploadFile']['name']) && $_FILES['uploadFile']['name'] != "") {
$allowedExtensions = array("xls","xlsx");
$ext = pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION);
if(in_array($ext, $allowedExtensions)) {
$file_size = $_FILES['uploadFile']['size'] / 1024;
if($file_size < 50) {
$file = "uploads/".$_FILES['uploadFile']['name'];
$isUploaded = copy($_FILES['uploadFile']['tmp_name'], $file);
if($isUploaded) {
include("db.php");
include("Classes/PHPExcel/IOFactory.php");
try {
//Load the excel(.xls/.xlsx) file
$objPHPExcel = PHPExcel_IOFactory::load($file);
} catch (Exception $e) {
die('Error loading file "' . pathinfo($file, PATHINFO_BASENAME). '": ' . $e->getMessage());
}
//An excel file may contains many sheets, so you have to specify which one you need to read or work with.
$sheet = $objPHPExcel->getSheet(0);
//It returns the highest number of rows
$total_rows = $_POST["xNum"]+1;
//It returns the highest number of columns
$highest_column = $sheet->getHighestColumn();
echo '<div class="container-fluid">';
echo '<h4 style="margin-top: 40px;">Data from Excel file</h4>';
echo '<table cellpadding="5" cellspacing="1" border="1" class="table table-striped table-bordered table-sm table-hover">';
$query = "insert into `tblorderitems` (`Vehicle`, `DriveTrain`, `Product`, `otherProduct`, `Price`, `RegNo`, `StockNo`, `ChassisNo`, `CommNo`, `PartNo`, `InStockDate`, `PlannedDate`) VALUES ";
//Loop through each row of the worksheet
for($row =2; $row <= $total_rows; $row++) {
//Read a single row of data and store it as a array.
//This line of code selects range of the cells like A1:D1
$single_row = $sheet->rangeToArray('A' . $row . ':' . $highest_column . $row, NULL, TRUE, FALSE);
echo "<tr>";
//Creating a dynamic query based on the rows from the excel file
$query .= "(";
//Print each cell of the current row
foreach($single_row[0] as $key=>$value) {
echo "<td>".$value."</td>";
$query .= "'".mysqli_real_escape_string($con, $value)."',";
}
$query = substr($query, 0, -1);
$query .= "),";
echo "</tr>";
}
$query = substr($query, 0, -1);
echo '</table>';
// At last we will execute the dynamically created query an save it into the database
mysqli_query($con, $query);
if(mysqli_affected_rows($con) > 0) {
echo '<script> alert("Order Added");</script>';
} else {
echo '<script> aleft("Can\'t update database table! try again"); </script>';
}
// Finally we will remove the file from the uploads folder (optional)
unlink($file);
} else {
echo '<script> alert("File not uploaded"); </script>';
}
} else {
echo '<script> alert("Maximum file size should be 50kb"); </script>';
}
} else {
echo '<script> alert("Incorrect File Type"); </script>';
}
} else {
echo '<script> alert("Select an XLSX File First"); </script>';
}
}
echo '</div>';
?>
Anyone any ideas what I would change to get this to work with sqlsrv?
Thanks
David

You just have to replace the calls to pure mysqli functions.
Replace mysqli_query with sqlsrv_query
Replace mysqli_affected_rows with sqlsrv_rows_affected
Replace mysqli_real_escape_string with your own function mssql_escape :
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}

Related

how to genrate uniq id if we send the data using seprate comma

i m try to use uniqid() to genrate the uniqname of the file and send it to the sql db by spliting seprate comma like('pic.jpg','pic1.jpg','pic2.jpg')
in place of pic i need a uniq name each and every time at the time of uploading of the file,i store all uploaded file into a folder and send the path of the image to the sql
<?php
if (isset($_POST['btnSubmit'])) {
$rep=$_FILES['files']['name'];
for ($i = 0; $i < count($rep); $i++) {
if ($_FILES["files"]["size"][$i] < 1000000) { // Check File size (Allow 1MB)
$nam=$_FILES["files"]["name"][$i];
// $nm = $_FILES["files"]["name"];
$album_cat = "";
$l = 0;
foreach ($rep as $album_cat1) {
$album_cat .= $album_cat1 . ",";
$l++;
}
$_POST['$album_cat'] = $album_cat;
$_POST['$album_cat_count'] = $l;
$temp = $_FILES["files"]["tmp_name"][$i];
$name = pathinfo($nam);
$profile = "group_images/" . uniqid() . '.' . $name['extension'];
if (empty($temp)) {
break;
}
if ($i == 0) {
$err = "File uploaded successfully";
$cls = "success";
}
$groupalbum = "UPDATE group_master SET group_photo='".$_POST['$album_cat']."' WHERE group_id='4'";
//$groupalbum = "UPDATE group_master SET group_photo='$profile' WHERE group_id='4'";
if ($conn->query($groupalbum) === TRUE) {
} else
echo "Error updating record: " . $conn->error;
move_uploaded_file($temp, $profile);
}
else {
$err = "File size is more than 1MB";
$cls = "danger";
}
}
}
?>
When I need an uniqid for a set of elements, I usually call uniqid() only once and after that I use an index (just for optimizing the speed of the script). So, you can call uniqid() before the for declaration:
$rep=$_FILES['files']['name'];
$uniqid = uniqid();
for ($i = 0; $i < count($rep); $i++) {
and then use $i as a suffix for your files
$profile = "group_images/".$uniqid.'-'.$i.'.'.$name['extension'];
On the other hand, you are calling move_uploaded_file($temp, $profile); only if your sql fails.
if ($conn->query($groupalbum) === TRUE) {
} else
echo "Error updating record: " . $conn->error;
move_uploaded_file($temp, $profile);
}
Are you sure that the logic is correct? Don't you need something like:
if ($conn->query($groupalbum) === TRUE) {
if (move_uploaded_file($temp, $profile)) {
// file has been uploaded successfully
} else {
// error in file upload process
}
} else
echo "Error updating record: " . $conn->error;
}
And the final point, your code is open for sql injection
$groupalbum = "UPDATE group_master SET group_photo='".$_POST['$album_cat']."' WHERE group_id='4'";
You should not use $_POST values directly into sql statements.

Can you sum or add in a variable while inserting data?

I would like to ask if it is possible to add together with a variable, I've manage it to echo it and it worked.
But is it possible in a insert statement?
Here is my code!
<?php
include('admin/db/database_configuration.php');
$sql = "SELECT * FROM tblalbums";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
$wow = $row['album_id'];
echo ($row['album_id']+1);
} else {
echo "0 results";
}
$conn->close();
?>
<?php
include('admin/db/database_configuration.php');
if (isset($_FILES["userfile"]) && !empty($_FILES["userfile"])) {
$image = $_FILES['userfile']['tmp_name'];
$imageSize = $_FILES['userfile']['size'];
$imageType = $_FILES['userfile']['type'];
// $job_desc = $_POST['desc'];
$imageName = $_FILES['userfile']['name'];
$len = count($image);
$path = "jobs/";
for ($i = 0; $i < $len; $i++) {
if (isset($imageName[$i]) && $imageName[$i] !== NULL) {
if(move_uploaded_file($image[$i], $path.$imageName[$i])) {
// $result = $conn->query("INSERT INTO tbljoba ( job_img_size, job_img_type, job_desc, job_img) VALUES ('$imageSize[$i]', '$imageType[$i]', '$job_desc', '$imageName[$i]')");
$sql = "INSERT INTO `tblphotos` ( imageName, imageSize, imageType, album_id) VALUES ('$imageName[$i]','$imageSize[$i]', '$imageType[$i]', '$wow');";
// echo"<script>alert('Image upload successfully!');location.href='employer_contact_us.php';</script>";
if ($conn->query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
}
}
$conn->close();
?>
As you can see above the variable $wow is album_id in the database, and i've echo it so the last number in the database + 1.
So i've got the INSERT statement and you can see there I've put the variable $wow. So how can add or sum up + 1 in adding values?
Thank you!
remove single quoted lines ' ' from $wow in VALUES then +1
$wow=1 without single quoted lines so that it will not read as a string to the database
You can find and read information about AUTO_INCREMENT for fields in MySQL
May be this can help you.

How to Check If 10 Most Recent Entries in MySQL DB Begin with a String Using PHP?

I want to allow people to write something like BOLD: or ITALIC: at the beginning of their message to make bold or italic. The only way I can think of is to get the total amount of entries by ID and minus 10 then make an IF statement and minus 9 and so on. Is there a single statement I could query to check if the string in the database begins a certain way and display it in HTML in bold or italic if it does?
<?PHP
$A = "localhost"; // Server Name
$B = "root"; // MySQL Username
$C = ""; // MySQL Password
$D = "sql"; // Database
$CONNECT = new mysqli($A, $B, $C, $D);
if ($CONNECT->connect_error) {
die('<DIV>Connection Failed</DIV>');
}
echo "<DIV>Connected</DIV>";
if (isset($_POST['MSG'])) {
$MSG = htmlspecialchars($_POST['MSG']);
$SQL = "INSERT INTO Messages (Message) VALUES ('$MSG')";
if ($CONNECT->query($SQL) === TRUE) {
echo "<DIV>Message Sent</DIV>";
} else {
echo "<DIV>Error Sending Message</DIV>";
}
}
$SELECT = 'SELECT * FROM Messages ORDER BY ID DESC LIMIT 10';
$RESULT = $CONNECT->query($SELECT);
if (mysqli_num_rows($RESULT) > 0) {
while ($ROW = mysqli_fetch_assoc($RESULT)) {
echo '<DIV>ID: ' . $ROW['ID'] . ' MSG: ' . $ROW['Message'] . '</DIV>';
}
}
I added in some code if somebody begins their message with "'", but the type of strpos if statement doesn't work in the while loop for retrieving messages.
if (isset($_POST['MSG'])) {
$MSG = htmlspecialchars($_POST['MSG']);
$SQL = "INSERT INTO Messages (Message) VALUES ('$MSG')";
if ($CONNECT->query($SQL) === TRUE) {
echo "<DIV>Message Sent</DIV>";
} else {
if (substr($MSG,0,1 == '\'')) {
echo "<DIV>Error Sending Message</DIV>";
} else {
echo "<DIV>Nice Try :')</DIV>";
}
}
In order for this question to have an answer i will sum up what i did in the comments:
if (mysqli_num_rows($RESULT) > 0) {
while ($ROW = mysqli_fetch_assoc($RESULT)) {
$message = $ROW['message'];
if(strpos($ROW['message'], 'BOLD:') !== false){
$message = '<strong>'.substr($ROW['message'], 5).'</strong>';
} else if(strpos($ROW['message'], 'ITALIC:') !== false){
$message = '<i>'.substr($ROW['message'], 7).'</i>';
}
echo '<DIV>ID: ' . $ROW['ID'] . ' MSG: ' . $message . '</DIV>';
}
}
edit: oops i forgot to add the different style tags..
for bold you can wrap the $message in a strong -tag. for italic its the i -tag
edit2: included tags in the code

Upload and insert xls file to mysql?

I´m strugeling to find a tutorial to show me how to code a php script that will let me upload and insert xls (not CSV) into mysql. I have this php script with fgetcsv and it works all fine. But i need to include support for xls.
my PHP
if(isset($_POST["Import"])){
echo $filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
//It wiil insert a row to our subject table from our csv file`
$sql = "INSERT into excell_import (`objekt`, `element_nummer`, `element_hojd`, `element_langd`,COURSE_ID, `AY`, `SEMESTER`)
values('$emapData[1]','$emapData[2]','$emapData[3]','$emapData[4]','$emapData[5]','$emapData[6]','$em apData[7]')";
//we are using mysql_query function. it returns a resource on true else False on error
$result = mysql_query( $sql, $conn );
if(! $result )
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
window.location = \"index.php\"
</script>";
}
}
fclose($file);
//throws a message if data successfully imported to mysql database from excel file
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"index.php\"
</script>";
//close of connection
mysql_close($conn);
}
?>
Working script for collect data from xls file and insert to mysql.
<?php
//include the following 2 files for phpexcel
require 'Classes/PHPExcel.php';
require_once 'Classes/PHPExcel/IOFactory.php';
//Establish connection to mysql
$conn=mysql_connect($host,$username,$password) or die("Could not connect");
mysql_select_db($dbname,$conn) or die("could not connect database");
//Load file
$path = "atbl.xls";
$objPHPExcel = PHPExcel_IOFactory::load($path);
//Loop threw file to get data
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = 20; //$worksheet->getHighestRow(); // e.g. 10
$highestColumn = 'G'; //worksheet->getHighestColumn(''); // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
echo "<br>The worksheet ".$worksheetTitle." has ";
echo $nrColumns . ' columns (A-' . $highestColumn . ') ';
echo ' and ' . $highestRow . ' row.';
echo '<br>Data: <table border="1"><tr>';
for ($row = 11; $row <= $highestRow; ++ $row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getCalculatedValue();
//$dataType = PHPExcel_Cell_DataType::dataTypeForValue($val);
echo '<td>' . $val . '<br></td>';
}
echo '</tr>';
}
echo '</table>';
}
for ($row = 11; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
}
//Insert data from file to mysql
$sql="INSERT INTO phpexcel(objekt_nr, objekt_rev, element_nr, element_langd, element_bredd, element_hojd)
VALUES ('".$val[1] . "','" . $val[2] . "','" . $val[3]. "','" . $val[4]. "','" . $val[5]. "','" . $val[6]. "')";
//echo $sql."\n";
mysql_query($sql) or die('Invalid query: ' . mysql_error());
}
?>

MySQL_Query error in PHP script

The goal is that I would like to cycle through ALL of the .CSV files in my directory and run this script for each file so it appends the data into the DB. The issue stems from when I insert the loop below. I have compiled a PHP script that works perfectly when it comes to reading a SINGLE .CSV file into my MySQL DB. Despite this, I get the following error when I call the mysql_query function after inserting the import script into a loop: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
$con = #mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
//CLEAR old contents from table
$queryDelete = "delete from $databasetable;";
$resultDelete = #mysql_query($queryDelete) or die("Error clearing table of old data: $query<br />" . mysql_error());
//READ directory for CSV files
//path to directory to scan IF NOT IN SAME FOLDER
$directory = "../data/";
//get all files IN CURRENT DIRECTORY with a .csv extension OTHERWISE add $csvfiles = glob($directory . "*.csv");
$csvfiles = glob("*.csv");
$numCSVFiles = count($csvfiles);
//Grab each CSV file and import to DB
for ($i = 0; $i < $numCSVFiles; $i++) {
$csvfile = $csvfiles[$i];
//TEST FILES
if(!file_exists($csvfile)) {
echo "File (" . $csvfile . ") not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$lines = 0;
$queries = "";
$linearray = array();
foreach(split($lineseparator,$csvcontent) as $line) {
$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);
$linemysql = implode("','",$linearray);
if($addauto == 1)
$query = "insert into $databasetable values('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
$queries .= $query . "\n<br />";
//THIS IS WHERE THE ERROR OCCURS WHILE RUNNING INSIDE THE LOOP
$result = #mysql_query($query) or die("Error 1: " . mysql_error() . "<br />Query Attempted: " . $query);
if(!$result) { $resultText = "Failure to execute MySQL queries. Please try again later."; } else { $resultText = "Successfully executed queries."; }
}
#mysql_close($con) or die("Error 2: " . mysql_error());
//LOG mysql queries
if($save) {
if(!is_writable($outputfile)) {
echo "File is not writable, check permissions.\n";
}
else {
$file2 = fopen($outputfile,"w");
if(!$file2) {
echo "Error writing to the output file.\n";
}
else {
fwrite($file2,$queries);
fclose($file2);
}
}
}
}
You're executing mysql_close() INSIDE your loop, so after the first file is inserted, you kill the DB connection, then try to insert the next file.
If your code was properly indented, you'd have seen this problem.
You're closing your database connection inside the loop. Don't close the connection if you want to keep using it.
I think you're missing a closing curly bracket { here...
mysql_close() is called too early: it's called in the for ($i = 0; $i < $numCSVFiles; $i++) loop.

Categories