Upload excel file in MYSQL using PHP - php

I want to upload an Excel file into a MySQL table without using PDO, but just with a simple MySQL connection.
I want to load the Excel file using DOMDocument::load but can't get it to work.
Here's what I've tried so far:
mysql_connection("localhost", "root", "");
mysql_select_db("excel");
function add_data($abc, $pqr, $xyz) {
$str = "INSERT INTO excel(abc, pqr, xyz) VALUES('$abc', '$pqr', '$xyz')";
$qry = mysql_query($str);
}
if (isset($_FILES['file'])) {
$dom = DOMDocument::load($_FILES['file']['tmp_name']);
$rows = $dom->getElementsByTagName('Row');
$first_row = true;
foreach ($rows as $row) {
if (!$first_row) {
$abc = "";
$pqr = "";
$xyz = "";
$index = 1;
$cells = $row->getElementsByTagName('Cell');
foreach ($cells as $cell) {
$ind = $cell->getAttribute('Index');
if ($ind != null)
$index = $ind;
if ($index == 1)
$abc = $cell->nodeValue;
if ($index == 2)
$pqr = $cell->nodeValue;
if ($index == 3)
$xyz = $cell->nodeValue;
$index += 1;
}
add_data($abc, $pqr, $xyz);
}
$first_row = false;
}
}

Related

PHPExcel: Dynamic Row and Column incrementing is not working for Array in phpexcel?

While printing column and row from an array it's showing blank not exporting any data
$inn_table = "";
if ($result['qualification']['dd1'] != "") {
$dd1 = explode(",", $result['qualification']['dd1']);
}
if ($result['qualification']['dd2'] != "") {
$dd2 = explode(",", $result['qualification']['dd2']);
}
for ($i = 0; $i < count($labels); $i++) {
if ($result['qualification']['dd1'] != "") {
echo '<pre>First';
print_r($dd1); ** //echo arrays**
for ($j = 0; $j < count($dd1); $j++) {
$temp = explode(">", $dd1[$j]);
if ($temp[0] == $labels[$i]) {
$name = explode(">", $dd1[$j]);
echo '<pre>First ';
print_r($name[1]); ** //echo names**
}
}
}
}
Here is my Array structure
and Here names which i am trying to export from Array
So i only trying to export names from that array please help
foreach($labels as $ind => $label) {
$index = $ind + 2;
$letter = range('A', 'Z')[$ind2];
$val = explode('>', $data);
$objPHPExcel->getActiveSheet()->setCellValue($letter . $index, $val[1]);
}

Issue adding data from csv to mysql using PHP

I have a PHP code that is supposed to save values fro a CSV file into a MySql database table. Everything works fine except that only the first row of the CSV is added. Here's the code:
<?php
public function saveProductsFromCsv($productId, $val) {
$productId = (int) $productId;
$data = array();
$fieldNames = $this->_config->getCsvColumnNames();
array_shift($fieldNames);
$numberOfFields = count($fieldNames);
$lines = explode("\n", $val);
foreach ($lines as $line) {
$line = trim($line);
if (empty($line))
continue;
$values = explode(',', $line);
if (count($values) != $numberOfFields){
throw new Exception();
return;
}
$make = trim($values[0]);
$model = trim($values[1]);
$yearFrom = (int) $values[2];
$yearTo = (int) $values[3];
$engine = trim($values[4]);
if ($yearFrom > 0){
if ($yearFrom < 1950){
$yearFrom = 1950;
} elseif ($yearFrom > 2030){
$yearFrom = 2030;
}
}
if ($yearTo > 0){
if ($yearTo < 1950){
$yearTo = 1950;
} elseif ($yearTo > 2030){
$yearTo = 2030;
}
}
$data[] = array($productId, $make, $model, $yearFrom, $yearTo, $engine);
}
if (count($data) > 0){
$this->saveValues($data);
}
}
public function saveValues($data)
{
$valuesStr = '';
foreach ($data as $values){
$cell = '';
foreach ($values as $value)
$cell .= ",'" . esc_sql(trim($value)). "'";
$valuesStr .= ($valuesStr != '' ? ',' : '') . "(NULL{$cell})";
}
$this->_wpdb->query("INSERT IGNORE INTO {$this->_mainTable} VALUES {$valuesStr}");
}
?>
Below is the CSV:
product_sku,make,model,year_from,year_to,engine
63118,Toyota,FJ Cruiser,2000,2008,V6 4.7L 2UZ-FE 20R/22R 1st Gen FJ Cruiser
28216,Toyota,GX470,1992,1997,V8 4.7L 2UZ-FE GX470
62687,Toyota,Land Cruiser,1998,2007,V8 4.7L 2UZ-FE 100-Series
28485,Toyota,Land Cruiser,2007,2018,V8 5.7L 3UR-FE 200-Series
Incidentally, if I use this:
product_sku,make,model,year_from,year_to,engine
63118,Toyota,FJ Cruiser,2000,2008,engine1
28216,Toyota,GX470,1992,1997,engine2
62687,Toyota,Land Cruiser,1998,2007,engine3
28485,Toyota,Land Cruiser,2007,2018,engine4
everything gets inserted fine. I think the problem is with the last column because if I use the same values in the last column in the second or third columns, everything works fine.
Never mind, I've solved it. The problem was with the encoding of the CSV file. I changed it to UTF-8 and everything is working fine.

getting the even index of a string

hey guys im trying to get the even indexes of a string from the db then save them in a variable then echo. but my codes seems doesnt work. please help. here it is
require_once('DBconnect.php');
$school_id = '1';
$section_id = '39';
$select_pk = "SELECT * FROM section
WHERE school_id = '$school_id'
AND section_id = '$section_id'";
$query = mysql_query($select_pk) or die (mysql_error());
while ($row = mysql_fetch_assoc($query)) {
$public_key = $row['public_key'];
}
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
if($key % 2 == 0) {
$priv_key_extract += $public_key[$key];
} else {
$priv_key_extract ="haiiizzz";
}
}
}
echo $priv_key_extract;
as you can see im trying to use modulo 2 to see if the index is even.
I have updated your code as below, it will work now :
<?php
$public_key = 'A0L8V1I5N9';
if ($public_key) {
$leng_public_key = strlen($public_key);
$priv_key_extract = "";
$array_pki = array();
for ($i=0; $i <=$leng_public_key-1 ; $i++) {
array_push($array_pki,$public_key[$i]);
}
foreach ($array_pki as $key => $value) {
//Changed condition below $key % 2 ==0 => replaced with $key % 2 == 1
if($key % 2 == 1) {
// Changed concatenation operator , += replaced with .=
$priv_key_extract .= $public_key[$key];
} /*else {
//Commented this as it is getting overwritten
$priv_key_extract ="haiiizzz";
}*/
}
}
echo $priv_key_extract;
?>
Try this function
function extractKey($key) {
if (empty($key) || !is_string($key)) return '';
$pkey = '';
for ($i=0;$i<strlen($key);$i++) {
if ($i % 2 == 0) {
$pkey .= $key[$i];
}
}
return $pkey;
}
echo extractKey('12345678'); # => 1357

Remove empty array elements from the $_FILES array

I have a photo album, with a 'photos' field in database which has serialized data and is base 64 encoded. I can upload up to 21 photos at the same time for the album (multiple uploading). When trying to add new photos to the album on edit mode, I can't get the new $_FILES array to merge with the old array in the database. I want to update only the values that I have changed. So let's say I already had 2 images inside my album, I would like to add a 3rd image without losing the other 2 images. I know I need to use unset() to delete empty values but I think i'm not doing it correctly. Here's my code:
if (isset($_REQUEST['action']) && $_REQUEST['action'] == 'edit') {
//select photo album and get photos and descriptions to be merged with new.
$album_id = $_REQUEST['album_id'];
$old_photos = null;
$old_descriptions = null;
$getAlbumQ = mysql_query("select * from albums where id='$album_id'");
while ($old_album = mysql_fetch_array($getAlbumQ)) {
$old_photos = unserialize(base64_decode($old_album['photos']));
$old_descriptions = unserialize(base64_decode($old_album['descriptions']));
}
if (isset($_POST['album_name']) && isset($_POST['desc'])) {
$name = $_POST['album_name'];
$desc = $_POST['desc'];
$idesc = array();
$target_path = "../uploads/albums/";
foreach ($_FILES as $k => $v) {
//first upload photos
$path = $target_path . basename($v['name']);
if(move_uploaded_file($v['tmp_name'], $path)) {
$hasUpload = true;
}
}
for ($j = 1; $j < 21; $j++) {
$img_index = $j;
$img_desc = $_POST['desc_' . $img_index];
$asdf = $_FILES['image_' . $img_index]['name'];
array_push($idesc, $img_desc);
}
foreach( $_FILES['images']['name'] as $key => $value ) {
if( empty($value) ) {
unset( $_FILES['images']['name'][$key] );
}
}
for ($i = 1; $i < 21; $i++) {
if($_FILES['image_'.$i]['name']!= '')
{
$hasUpload = true;
$presults = array_merge($old_photos, $_FILES); //THE PROBLEM WITH MERGING ARRAYS OCCURS HERE
$dresults = array_merge($old_descriptions, $idesc);
$images = base64_encode(serialize($presults));
$descriptions = base64_encode(serialize($dresults));
$posted = date("Y-m-d H:i:s");
}
else {
$hasUpload = false;
$presults = $old_photos;
$dresults = $idesc;
$images = base64_encode(serialize($presults));
$descriptions = base64_encode(serialize($dresults));
$posted = date("Y-m-d H:i:s");
}
}
}
}
I tried something similar to what Muu suggested. Combined it with another piece of code of a custom merge function found here http://keithdevens.com/weblog/archive/2003/Mar/30/MergeTwoArrays and it worked fine! Thanks for your help
Just needed to add the following lines of code outside the for ($i = 1; $i < 21; $i++) loop:
//delete empty values for $_FILES array
foreach ($_FILES as $key => $value) {
foreach ($value as $k => $v) {
if ($k=='name' && $v!='') {
break;
} else {
unset($_FILES[$key]);
}
}
}
//custom array merge function
function merge(&$a, &$b){
$keys = array_keys($a);
foreach($keys as $key){
if(isset($b[$key])){
if(is_array($a[$key]) and is_array($b[$key])){
merge($a[$key],$b[$key]);
}else{
$a[$key] = $b[$key];
}
}
}
$keys = array_keys($b);
foreach($keys as $key){
if(!isset($a[$key])){
$a[$key] = $b[$key];
}
}
}
then instead of array_merge(), I used merge() inside the for ($i = 1; $i < 21; $i++) loop:
$presults = merge($old_photos, $_FILES);
Instead of removing the empty values from the array, why not just ignore them?
For example:
$nonEmptyArray = array();
foreach ($_FILES as $k => $v) {
if (!$v) {
continue;
}
$nonEmptyArray[$k] = $v;
}
$_FILES = $nonEmptyArray;

Reading xls (Excel) files in PHP

I'm fairly new to this so I wanted to ask a question. I uploaded an excel file using html and when I try to learn how to read excel files using php, this is what I've got from IBM:
<?php
$filename = basename($_FILES["file"]["name"]);
$ext = substr($filename, strrpos($filename, '.') + 1);
function get_data($qnum, $qtype, $qname, $qtext, $atext, $pcredit, $rcounts, $r, $qcount, $cfac, $sd, $disc_inx, $disc_coef)
{
global $data;
$data[] = array('QNum' => $qnum, 'Qtype' => $qtype, 'Questionname' => $qname, 'Questiontext' => $qtext,
'Answertext' => $atext, 'PartialCredit' => $pcredit, 'RCounts' => $r, 'QCount' => $qcount,
'Correctionfacility' => $cfac, 'DiscriminationIndex' => $disc_inx, 'DiscriminationCoefficient' => $disc_coef);
}
if ($ext == "xls") {
$dom = DOMDocument::load($_FILES['file']['tmp_name']);
$rows = $dom->getElementsByTagName('Row');
$first_row = true;
foreach ($rows as $row) {
if (!$first_row) {
$qnum = "";
$qtype = "";
$qname = "";
$qtext = "";
$atext = "";
$pcredit = "";
$r = "";
$qcount = "";
$cfac = "";
$disc_inx = "";
$disc_coef = "";
$index = 1;
$cells = $row->getElementsByTagName('Cell');
foreach ($cells as $cell) {
$ind = $cell->getAttribute('Index');
if ($ind != null)
$index = $ind;
if ($index == 1)
$qnum = $cell->nodeValue;
if ($index == 2)
$qtype = $cell->nodeValue;
if ($index == 3)
$qname = $cell->nodeValue;
if ($index == 4)
$qtext = $cell->nodeValue;
if ($index == 5)
$atext = $cell->nodeValue;
if ($index == 6)
$pcredit = $cell->nodeValue;
if ($index == 7)
$r = $cell->nodeValue;
if ($index == 8)
$qcount = $cell->nodeValue;
if ($index == 9)
$cfac = $cell->nodeValue;
if ($index == 10)
$disc_inx = $cell->nodeValue;
if ($index == 11)
$disc_coef = $cell->nodeValue;
$index += 1;
}
get_data($qnum, $qtype, $qname, $qtext, $atext, $pcredit, $r, $qcount, $cfac, $disc_inx, $disc_coef);
}
$first_row = false;
}
}
else {
echo "Invalid file!";
}
?>
And I got a syntax error
Warning: DOMDocument::load(): Start tag expected, '<' not found in /tmp/phpwUIpyZ, line: 1 in /var/www/moodle/question/upload_file.php on line 16 Fatal error: Call to a member function getElementsByTagName() on a non-object in /var/www/moodle/question/upload_file.php on line 17.
What is the error on my code? Need help please thanks!
Excel is not an valid DOMDocument , so of course you can't use DOMDocument for it :)
I would suggest using something ready such as PHPExcelReader.
Good Luck,Shai.
As the error message say, $dom is a non-object - in other words, DOMDocument::load returned something, but not an object. There could be various reasons for that, but the most likely ones are:
file doesn't exist or not readable
file is malformed (not a valid DOM document), parsing failed
See the manual: http://php.net/manual/en/domdocument.load.php
Note also that you seem to be trying to parse an XLS file as a DOM document - that won't fly, those are completely different file formats.

Categories