I found the PHPExcel library brilliant to manipulate Excel files with PHP (read, write, and so on).
But nowhere in the documentation is explained how to read a XLSX worksheet to feed a MySQL table...
Sorry for this silly question, but i need it for my work and found no answer on the web.
A small example could be very helpful.
Thanks a lot.
UPDATED :
I precise my question :
The only part of code i found in the documentation that could help me is to read an Excel file and display it in a HTML table :
`require_once 'phpexcel/Classes/PHPExcel.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load("edf/equipement.xlsx");
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
echo '<table border="1">' . "\n";
for ($row = 1; $row <= $highestRow; ++$row) {
echo '<tr>' . "\n";
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
echo '<td>' . $objWorksheet->getCellByColumnAndRow($col, $row)->getValue() . '</td>' . "\n";
}
echo '</tr>' . "\n";
}
echo '</table>' . "\n";`
I know i can use the loop to feed my MySQL table, but i don't know how... I'm not aware in OOP...
Can somebody help me, please ?
Here is the code
$inputFileName = $upload_path . $filename;
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$objWorksheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorksheet->getHighestRow();
$highestColumn = $objWorksheet->getHighestColumn();
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$rows = array();
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$rows[$col] = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
}
mysql_query("INSERT INTO upload (`item_number`,`qty_sold`,`cost_home`) VALUES ($rows[1],$rows[2],$rows[3])");
}
?>
I have tried mysql_query("INSERT INTO upload (col1,col2) VALUES ($rows[1],$rows[2])"); as well but didn't work. The table stays empty
The first for loops through rows, and the second one loops through columns.
So, there are plenty of solutions to your "problem".
You could, for example, populate an array and make an insert statement for each row.
As the following :
$rows = array();
for ($row = 1; $row <= $highestRow; ++$row) {
for ($col = 0; $col <= $highestColumnIndex; ++$col) {
$rows[$col] = mysql_real_espace_string($objWorksheet->getCellByColumnAndRow($col, $row)->getValue());
}
mysql_query("INSERT INTO your_table (col1,col2) VALUES ($rows[1],$rows[2])");
}
Obviously, this code can be improved.
Related
I'm fairly new to WordPress and SQL. I have a contact form that I want to have the data be submitted to my WordPress database but only if the data that has been entered has not been entered before.
This is what i have so far, which sends data to my database when form is submitted.
if(isset($_POST['contact_us'])) {
$invalidContact = "<h5 class='invalidBooking'> Nope try again</h5>";
$successContact = "<h5 class='invalidBooking'> Message Sent!</h5>";
$table_name='contact_table';
global $wpdb;
$contact_name = esc_attr($_POST['contact_name']);
$contact_email = sanitize_email($_POST['contact_email']);
$subject = esc_attr($_POST['subject']);
$message = esc_attr($_POST['message']);
$error= array();
if (empty($contact_name)) {
$error['name_invalid']= "Name required";
}
if (empty($contact_email)){
$error['email_invaild']= "Email required";
}
// Im guessing some code here to check if row exists in database
if (count($error) >= 1) {
echo $invalid;
}
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
echo $successContact;
}
}
You may try this code
if (count($error) == 0) {
$data_array=array(
'Contact_Name'=>$contact_name,
'Contact_Email'=> $contact_email,
'Contact_Subject'=> $subject,
'Contact_Message'=> $message,
);
$query = "SELECT * FROM $table_name WHERE 'Contact_Name'= '$contact_name' AND 'Contact_Email' = '$contact_email' AND 'Contact_Subject' = '$subject' AND 'Contact_Message' = '$message'";
$query_results = $wpdb->get_results($query);
if(count($query_results) == 0) {
$rowResult=$wpdb->insert($table_name, $data_array,$format=NULL);
}
}
Hope this works for you.
fetch data using this code
$query = "SELECT * FROM {$wpdb->prefix}table WHERE column = 1";
echo $query;
$results = $wpdb->get_results($query);
and then you know what to do...
i can't get more than one return in this json. when the original query returns 90k results.
i can't figure out what's hapening.
also the return i get isn't organized as it should. it return the following
{"material":["R8190300000","0"],"grid":["R8190300000","0"]}
sorry to ask this i have been looking for an answer but couln't get it in the internet.
<?php
$link = mysqli_connect("localhost","blablabla","blablabla","blablabla");
if (mysqli_connect_error()) {
die("Could not connect to database");
}
$query =" SELECT material,grid FROM ZATPN";
if( $result = mysqli_query( $link, $query)){
while ($row = mysqli_fetch_row($result)) {
$resultado['material']=$row;
$resultado['grid']=$row;
}
} else {
echo"doesnt work";
}
file_put_contents("data.json", json_encode($resultado));
?>
The problem is that you are overriding the value for the array keys:
$resultado['material']=$row;
$resultado['grid']=$row;
At the end you will have only the last 2 rows; I suggest you to use something like:
$resultado['material'][] = $row;
$resultado['grid'][] = $row;
This will save you pair rows in $resultado['grid'] and unpaired rows in $resultado['material'];
After the information in comments you can use this code:
$allResults = array();
while ($object = mysqli_fetch_object($result)) {
$resultado['id'] = $object->id;
$resultado['name'] = $object->name;
$resultado['item'] = $object->item;
$resultado['price'] = $object->price;
$allResults[] = $resultado;
}
file_put_contents("data.json", json_encode($allResults));
I am trying to use phpexcel to let users upload a spreadsheet and insert into mysql. I have it working except if the user has blank rows in the spreadsheet it puts several unnecessary rows in the database. I have read and mysql doesnt support check constraints and most of that would need to be done at the application level which is what I am trying to do. How in PHP could have it check if a specific column is empty and skip that row. Any help would be appreciated or if there is a better solution I am up for all options. I was trying for a while to get it that is the bldg column was empty than just skip that row but wasnt having any luck..
<?php require '../Classes/PHPExcel.php';
require_once '../Classes/PHPExcel/IOFactory.php';
$path = "../upload/uploads/$Filename";
$objPHPExcel = PHPExcel_IOFactory::load($path);
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
$worksheetTitle = $worksheet->getTitle();
$highestRow = $worksheet->getHighestRow();
$highestColumn = 'L'; // e.g 'F'
$highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
$nrColumns = ord($highestColumn) - 64;
$objReader = PHPExcel_IOFactory::createReaderForFile($path);
$objReader->setReadDataOnly(true);
echo '<br>Data: <table width="100%" cellpadding="3" cellspacing="0"><tr>';
for ($row = 16; $row <= $highestRow; ++ $row) {
echo '<tr>';
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val = $cell->getValue();
if($row === 1)
echo '<td style="background:#000; color:#fff;">' . $val . '</td>';
else
echo '<td>' . $val . '</td>';
}
echo '</tr>';
}
echo '</table>';
for ($row = 16; $row <= $highestRow; ++ $row) {
$val=array();
for ($col = 0; $col < $highestColumnIndex; ++ $col) {
$cell = $worksheet->getCellByColumnAndRow($col, $row);
$val[] = $cell->getValue();
}
$sql="insert into excess1(date_excessed, bldg, floor, jack, equipment_owner, contact_name, contact_phone, qty, type_of_excess, asset_tag, service_tag, comments)
values('".$val[0] . "','" . $val[1] . "','" . $val[2]. "','" . $val[3]. "','" . $val[4]. "','" . $val[5]. "','".$val[6] . "','".$val[7] . "','".$val[8] . "','".$val[9] . "','".$val[10] . "','".$val[11] . "')";
$result = mysql_query($sql) or die(mysql_error());
print "$result";
}
}
unlink("../upload/uploads/$Filename");
?>
</article>
$inputFileType = PHPExcel_IOFactory::identify($filename);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($inputFileName);
$allDataInSheet = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);
$i=0;
foreach ($allDataInSheet as $value) {
if ($value === null){
continue;
} //this is skipping empty rows
$data[$i] = $value['A'];
$data[$i] = $value['B'];
$i++;
}
trying to check to see if the file already exist but it doesn't work LINE 6
if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];
if (file_exists($_FILES['userfile']['name']))
{
echo $_FILES['userfile"]["name'] . " already exists. ";
}else{
$fp= fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
//include 'library/config.php';
//include 'library/opendb.php';
$query = "INSERT INTO upload (name, size, type, content )
VALUES ('$fileName', '$fileSize', '$fileType', '$content')";
mysql_query($query) or die('Error, query failed');
//include 'library/closedb.php';
echo "<br>File $fileName uploaded<br>";
}
}
$_FILES['userfile"]["name']
Make sure your opening quotes match the closing ones. Example valid strings are "this" and 'this', for example.
echo $_FILES['userfile']['name'] . " already exists. ";
echo $_FILES["userfile"]["name"] . " already exists. ";
// etc.
I am reading .csv file through PHP using fgetcsv(). Now I am able to fetch I mean read data from .csv file.
Then I need to check SKU column with my fetch result & accordingly have to perform either Insertion Or Updation.
Suppose SKU is already present there, then I have to update my row in table else I need to insert new record.
I have write following code...Plz check n tell me where I am doing mistake-:
<?php
$row = 1;
if (($handle = fopen("localhost/data/htdocs/magento/var/import/Price.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 8000, ",")) !== FALSE)
{
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
for ($c=0; $c < $num; $c++)
{
$temp = $data;
$string = implode(";", $temp);
}
$pieces = explode(";", $string);
$col1 = $pieces[0];
$col2 = $pieces[1];
$col3 = $pieces[2];
$col4 = $pieces[3];
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password");
If (!$con)
{
die('Could not connect: ' . mysql_error());
mysql_close($con);
}
$seldb = mysql_select_db($db_name, $con);
$query_fetch = "SELECT `sku` from `imoprt_prices`";
$result_fetch = mysql_query($query_fetch);
$num_rows = mysql_num_rows($result_fetch);
for($i = 0; $i < $num_rows; $i++)
{
$value = mysql_result($result_fetch, i, 'sku');
if(strcmp('".$value."', '".$col2."') == 0)
{
$flag = 1;
break;
}
else
{
$flag = 0;
break;
}
}
if($flag == 1)
{
$query_upadte = "(UPDATE imoprt_prices SET customer_id= '".$col1."', sku ='".$col2."', price= '".$col3."', website= '".$col4."'
)";
mysql_query($query_upadte);
$row++;
}
if($flag == 0)
{
mysql_query("INSERT INTO `imoprt_prices`(`customer_id`,`sku`,`price`,`website`) VALUES('".$col1."','".$col2."','".$col3."','".$col4."')");
$row++;
}
}
}
?>
If you have an actual UNIQUE index on your imoprt_prices table, you can use the ON DUPLICATE KEY UPDATE syntax and simplify your code a bit to something similar to; (note, can't test, so see as pseudo code)
$db_name = "magento";
$con = mysql_connect("localhost", "magento", "password") or die(mysql_error());
$seldb = mysql_select_db($db_name, $con);
if (($handle = fopen("localhost/data/htdocs/magento/var/import/Price.csv", "r")) !== FALSE)
{
while (($data = fgetcsv($handle, 8000, ",")) !== FALSE)
{
$col1 = $pieces[0];
$col2 = $pieces[1];
$col3 = $pieces[2];
$col4 = $pieces[3];
$query_upadte = "INSERT INTO imoprt_prices (customer_id, sku, price, website) ".
"VALUES('".$col1."','".$col2."','".$col3."','".$col4."') ".
"ON DUPLICATE KEY UPDATE customer_id='".$col1."', price='".$col3.
"',website='".$col4."'";
mysql_query($query_upadte);
}
}
You may also want to either mysql_real_escape_string() or use parameterized queries to make sure there's no ' in your inserted values though. That is always a danger with building sql strings like this.
Simple demo here.
In the following snippet:
$query_upadte = "UPDATE imoprt_prices SET customer_id= '".$col1."', sku ='".$col2."', price= '".$col3."', website= '".$col4."'";
You're trying to update all the rows repeatedly, instead of just updating a single row. This is normally not allowed in MySQL. You need to specify a particular unique ID to be updated.