Excel Not Saved as Numeric Format (MySQL to Excel) - mysql

I have a script that allows me to convert a database from MySQL to Excel .xls format, It was a success,
here is the code
<?php
// DB TABLE Exporter
//
// How to use:
//
// Place this file in a safe place, edit the info just below here
// browse to the file, enjoy!
// CHANGE THIS STUFF FOR WHAT YOU NEED TO DO
$cdate = date("Y-m-d");
$dbhost = "localhost";
$dbuser = "-";
$dbpass = "-";
$dbname = "-";
$dbtable = "-";
$filename = "C:\xxx";
// END CHANGING STUFF
// first thing that we are going to do is make some functions for writing out
// and excel file. These functions do some hex writing and to be honest I got
// them from some where else but hey it works so I am not going to question it
// just reuse
// This one makes the beginning of the xls file
function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
// This one makes the end of the xls file
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
// this will write text in the cell you specify
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
// make the connection an DB query
$dbc = mysql_connect( $dbhost , $dbuser , $dbpass ) or die( mysql_error() );
mysql_select_db( $dbname );
$q = "SELECT * FROM ".$dbtable." ";
$qr = mysql_query( $q ) or die( mysql_error() );
//start the object
ob_start();
// start the file
xlsBOF();
// these will be used for keeping things in order.
$col = 0;
$row = 0;
// This tells us that we are on the first row
$first = true;
while( $qrow = mysql_fetch_assoc( $qr ) )
{
// Ok we are on the first row
// lets make some headers of sorts
if( $first )
{
// di comment karena ini ngasih label tabelnya, sepertinya nggak butuh
//foreach( $qrow as $k => $v )
//{
// // take the key and make label
// // make it uppper case and replace _ with ' '
// xlsWriteLabel( $row, $col, strtoupper( ereg_replace( "_" , " " , $k ) ) );
// $col++;
//}
// prepare for the first real data row
$col = 0;
$row = 0;//$row++; // nyoba
$first = false;
}
// go through the data
foreach( $qrow as $k => $v )
{
// write it out
xlsWriteLabel( $row, $col, $v );
$col++;
}
// reset col and goto next row
$col = 0;
$row++;
}
xlsEOF();
//write the contents of the object to a file
file_put_contents($filename, ob_get_clean());
?>
this code produced a .xls file. I used Matlab to read my .xls file through readxls function, but it didn't recognize the value inside the .xls file as a numeric data, so my script on matlab couldn't make a matrix from reading my xls file. I had to convert it manually inside excel, there were some pop-ups near the value that offers me to convert it into numbers

If your goal is to take data from MySQL and put it in Matlab it might be easier to directly connect to MySQL from Matlab rather than sending the data through the xls format.
http://www.mathworks.com/help/database/ug/database.fetch.html

Related

gravity forms validate field entry values against mysql table value

Basically, I have a table with 8 million codes for promotion. The contestant will enter the code on a gravity form, which will then query the database for code, once it is there the code will be marked as used, and the contestant should be redirected to the entry form. If not the form should tell the user code is invalid. This is my code below which I pulled from other sources because I am not a coder. However, when I submit, the correct code, it says incorrect. Any help will be appreciated just bear in mind I am not a programmer
add_filter( 'gform_field_validation_4', 'validate_code' );
function validate_code($validation_result){
$form = $validation_result['form'];
foreach( $form['fields'] as &$field ) {
if ( strpos( $field->cssClass, 'validate-code' ) === false ) {
continue;
}
}
$field_value = rgpost( "input_1" );
$is_valid = is_code( $field_value );
$validation_result['is_valid'] = false;
$field->failed_validation = true;
$field->validation_message = 'The code you have entered is not valid. Please enter another.';
$validation_result['form'] = $form;
return $validation_result;
}
function is_code($code){
$info = 'mysql response';
require_once(ABSPATH . '/wp-config.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
echo 'Unable to connect to server, please use the back button in your browser and resubmit the form';
exit();
}
$code = mysqli_real_escape_string($conn, $_POST['codes']);
$sql_check = mysqli_query($conn, "SELECT * FROM entrycode WHERE codes = '$code' AND valid = 0");
$sql_checkrows = mysqli_num_rows($sql_check);
if ($sql_checkrows > 0) {
$sql_update = "UPDATE entrycode SET used = 1 WHERE codes ='$code'";
if (mysqli_query($conn, $sql_update)) {
$info = mysqli_affected_rows($conn) . " Row updated.\n";
$info = 'success';
return true;
} else {
return false;
}
mysql_close($conn);
}
}
add_filter('gform_confirmation_4', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$success_url = 'https://sample.com/enter' . '/?code=' . $lead[1];
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
so I modified the code from Phill, I am no longer getting the error, but the code is not being validated, as a matter of fact, any code I type in is valid., I am at a lost. My table is structured like this
entry codes table
ID
Codes
Used
34
98j65XF16
O
add_filter('gform_validation_4_1', 'validate_code');
function validate_code($validation_result){
// this assumes the code is entered in field one on your form
// change this input_ number if it's a different field
if($is_code_valid($_POST['input_1'])){
$validation_result['is_valid'] = false;
foreach($validation_result['form']['fields'] as &$field){
// field 1 is the field where we want to show the validation message
if($field['id'] == 1){
$field['failed_validation'] = true;
$field['validation_message'] = 'The code you entered is invalid: please try again.';
break;
}
}
}
return $validation_result;
}
// use this function to validate codes
function is_code_valid($thiscode){
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( $matched_codes > 0) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
// doing this here because the redirect URL does not support variables or shortcodes
// change the 70 here to your form ID
add_filter('gform_confirmation_4', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$success_url = 'https://demo.com/enter' . '/?code=' . $lead[1];
$confirmation = array('redirect' => $success_url);
return $confirmation;
}
Updated function to validate codes:
function is_code_valid($thiscode){
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( !empty ( $matched_codes ) ) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
this code i have still is not checking the database with codes for validation ,, all codes returning invalid code message
add_filter('gform_validation_2', 'validate_code');
GFCommon::log_debug( __METHOD__ . '(): The POST => ' . print_r( $_POST, true ) );
function validate_code($validation_result){
// this assumes the code is entered in field one on your form
// change this input_ number if it's a different field
if(!is_code_valid($_POST['input_1'])){
$validation_result['is_valid'] = false;
foreach($validation_result['form']['fields'] as &$field){
// field 1 is the field where we want to show the validation message
if($field['id'] == 1){
$field['failed_validation'] = true;
$field['validation_message'] = 'The code you entered is invalid: please try again.';
break;
}
}
}
return $validation_result;
}
function is_code_valid($thiscode){
GFCommon::log_debug( __METHOD__ . '(): The POST => ' . print_r( $_POST, true ) );
global $wpdb;
// Get match count (consider using transient ref table).
$matched_codes = $wpdb->get_var(
$wpdb->prepare(
"
SELECT sum(meta_value)
FROM $wpdb->entrycode
WHERE codes = %s
AND valid = 0
",
$thiscode
)
);
// If matches found , update table count?.
if ( !empty ( $matched_codes ) ) {
$wpdb->query( $wpdb->prepare(
"
UPDATE $wpdb->entrycode
SET used = %d
WHERE codes = %s
",
1,
$thiscode
) );
return true;
}
return false;
}
// doing this here because the redirect URL does not support variables or shortcodes
// change the 70 here to your form ID
add_filter('gform_confirmation_2', 'valid_invitation_confirmation', 10, 4);
function valid_invitation_confirmation($confirmation, $form, $lead, $ajax){
// customize this URL - I send the code in the query string
$country = ($_POST['input_3']);
$success_url = 'https://sample.com/enter' . '/?code=' .$lead[1] .'&country=' .$country;
$confirmation = array('redirect' => $success_url);
return $confirmation;
}

"No Excel data found in file." when reading input from .xlsx and writing the output to .xml file (i/p file to be in .xlsx format) + perl

My excel file has three columns. Xml format can be of any type. Just I need to extract the contents. Any help is appreciated.
Input(as in .xlsx):
Date Name Subject
07/22/2020 AAA Severity: 1 - Critical has been assigned
07/23/2020 BBB Severity: 2 - Medium has been assigned
My Code:
use warnings;
use Spreadsheet::ParseExcel;
use XML::Writer ();
use XML::Writer::String ();
use IO::File;
use File::Find;
my $parser = Spreadsheet::ParseExcel->new();
my $workbook = $parser->parse("D:/input.xlsx");
if ( !defined $workbook ) {
die $parser->error(), ".\n";
}
my $xml_doc = XML::Writer::String->new();
my $xml_file = new IO::File("D:/output.xml");
my $xml_doc_writer = new XML::Writer(OUTPUT => $xml_file);
for my $worksheet ( $workbook->worksheets() ) {
my ( $row_min, $row_max ) = $worksheet->row_range();
my ( $col_min, $col_max ) = $worksheet->col_range();
my %header = ();
for my $row ( $row_min .. $row_max ) {
for my $col ( $col_min .. $col_max ) {
my $cell = $worksheet->get_cell( $row, $col );
if ($row == 0) {
$header{$col} = $cell->unformatted();
} else {
$xml_doc_writer->dataElement($header{$col},$cell->unformatted());
}
}
}
}
$xml_doc_writer->endTag();
$xml_doc_writer->end();
$xml_file->close();
Output:
No Excel data found in file.
Can any one tell me, why its showing this error?
Thanks in advance.

SQL can't found any values

i'm having trouble returning values of sql rows, my SQL request work well on console but can't return a row of it with my code, any help ? thanks !
<?php
require_once 'sql.php';
$sqlConnexion = new mysqli($hn,$un,$pw,$db);
if($sqlConnexion->connect_error){
die ('Soucis de connexion SQL');}
$date = date("d/m/y G:i:s");
if(isset($_POST['zoneDeText'])){
$area = $_POST['zoneDeText'];
$queryone= "SELECT SortieTraitée FROM entry WHERE entréesUtilisateurs=?";
$instruction = $sqlConnexion->prepare($queryone);
if(!$instruction->prepare($queryone)){
echo "$instruction->errno";
}else{
$instruction->bind_param('s', $area);
$instruction->execute();
$result = $instruction->get_result();
while ($row = $result->fetch_array(MYSQLI_NUM)){
foreach ($row as $out){
if($out == $area){
echo $out;
}elseif($out != $area){
echo 'Still not found';
}
}
}
$instruction->close();
}
?>
You don't actually print anything, you just return the value, which makes no sense unless your code is inside a function.
if($out == $area){
return $out;
}
The documentation http://php.net/return says:
If return is called from within the main script file, then script execution ends.
Unless the code you show above has been included in another PHP script, that means it will just end the script and output nothing.
There are several other confusing things your script, but the above is probably the one directly responsible for the problem you're asking about.
Here's how I might write this code:
if (isset($_POST['zoneDeText'])) {
$area = $_POST['zoneDeText'];
$queryone = "SELECT SortieTraitée FROM entry WHERE entréesUtilisateurs=?";
$instruction = $sqlConnexion->prepare($queryone);
// if the prepare fails, it is false
if ($instruction === false) {
// false is not an object, it has no error attribute
// the error is an attribute of the connection
die($sqlConnexion->error);
}
$instruction->bind_param('s', $area);
$instruction->execute();
$result = $instruction->get_result();
// if there are zero rows in the result, the while loop
// will finish before it starts, so there will be no output
// so first check for a result of zero rows in the result
if ($result->num_rows == 0) {
echo("Found zero rows");
} else {
while ($row = $result->fetch_assoc()) {
echo $row["SortieTraitée"];
}
}
$instruction->close();
}

Memory Efficient reading + writing of .csv and .xlsx data

I am looking to implement memory efficient reading and writing of .xlsx/.csv files.
I am currently using phpExcel and am having trouble with large files. (Known issue)
I found the following library for reading: https://github.com/nuovo/spreadsheet-reader
This seems that it will work.
For writing files currently I create an array and then loop the array to output the file. Is this why it uses a lot of memory? What is the best way to not use a lot of memory when writing csv/xlsx when getting data from mysql database using code igniter?
This is what I do now:
/* added for excel expert */
function excel_export() {
$data = $this->Customer->get_all($this->Customer->count_all())->result_object();
$this->load->helper('report');
$rows = array();
$header_row = $this->_excel_get_header_row();
$header_row[] = lang('customers_customer_id');
$rows[] = $header_row;
foreach ($data as $r) {
$row = array(
$r->first_name,
$r->last_name,
$r->email,
$r->phone_number,
$r->address_1,
$r->address_2,
$r->city,
$r->state,
$r->zip,
$r->country,
$r->comments,
$r->account_number,
$r->taxable ? 'y' : '',
$r->company_name,
$r->person_id
);
$rows[] = $row;
}
$content = array_to_spreadsheet($rows);
force_download('customers_export.'.($this->config->item('spreadsheet_format') == 'XLSX' ? 'xlsx' : 'csv'), $content);
exit;
}
function array_to_spreadsheet($arr)
{
$CI =& get_instance();
$objPHPExcel = new PHPExcel();
//Default all cells to text
$objPHPExcel->getDefaultStyle()->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_TEXT);
for($k = 0;$k < count($arr);$k++)
{
for($j = 0;$j < count($arr[$k]); $j++)
{
$objPHPExcel->getActiveSheet()->setCellValueExplicitByColumnAndRow($j, $k+1, $arr[$k][$j]);
}
}
if ($CI->config->item('spreadsheet_format') == 'XLSX')
{
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
}
else
{
$objWriter = new PHPExcel_Writer_CSV($objPHPExcel);
}
ob_start();
$objWriter->save('php://output');
$excelOutput = ob_get_clean();
return $excelOutput;
}

PHP MySQL script gone wrong

I'm working on a site and created this experimental script which populates a category menu dynamically based on the database entry.
It worked for a day and then suddenly stopped. I changed my includes for requires and it gave me this error message
Fatal error: Maximum execution time of 30 seconds exceeded in /home1/advertbo/public_html/dev_area/origocloud/include/views/blog/dbget.php on line 34
function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ado_ocblog", $con);
$htmlString = "";
$result = mysql_query(
"SELECT *
FROM subCat
JOIN headCat ON subCat.headid = headCat.id
ORDER BY headid ASC;");
$array = mysql_fetch_array($result);
mysql_close($con);
$pre = NULL;
$hc = 0;
$sc = 1;
while ($array) {
if($pre == NULL){
$pre = $row["headc"];
$test[0][0]=$row["headc"];
$test[0][1]=$row["subc"];
}
else
{
if($pre ==$row["headc"]){
$sc++;
$test[$hc][$sc] = $row["subc"];
}
else
{
$hc++;
$sc = 1;
$test[$hc][0]=$row["headc"];
$test[$hc][$sc]=$row["subc"];
$pre = $row["headc"];
}
}
}
foreach( $test as $arrays=>$cat)
{
$first = TRUE;
foreach($cat as $element)
{
if($first == TRUE)
{
$htmlString.= '<h3>'.$element.'</h3>
<div>
<ul>
';
$first = FALSE;
}
else
{
$htmlString.= '<li><a class="sub_menu" href="#">'.$element.'</a></li>';
}
}
$htmlString.= '</ul> </div>';
}
return $htmlString;
}
I'm really stuck, the page just keeps timing out the point where i call the function
Try this:
while ($array = mysql_fetch_array($result)) {}
Take a look on PHP docs http://php.net/mysql_fetch_array
If does not work, your SQL Query returns too much values and craches the php execution
=]
I think it's time to take a step back and look at what you're doing :) This function should do what you want (even if you fixed the infinite loop problem in the function you gave, I don't think it would act how you want it to.):
function getBlogMenu(){
$dbhost = 'localhost';
$dbuser = ' ';
$dbpass = ' ';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("ado_ocblog", $con);
$htmlString = "";
$result = mysql_query(
"SELECT *
FROM subCat
JOIN headCat ON subCat.headid = headCat.id
ORDER BY headid ASC;");
// arrays can have strings as keys as well as numbers,
// and setting $some_array[] = 'value'; (note the empty brackets [])
// automatically appends 'value' to the end of $some_array,
// so you don't have to keep track of or increment indexes
while ($row = mysql_fetch_assoc($result))
{
$test[$row["headc"]][] = $row["subc"];
}
// don't close the connection until after we're done reading the rows
mysql_close($con);
// $test looks like: array('headc1' => array('subc1', 'subc2', 'sub3'), 'headc2' => array('subc4', 'subc5'), ...)
// so we step through each headc, and within that loop, step through each headc's array of subc's.
foreach($test as $headc => $subc_array)
{
$htmlString.= '<h3>'.$headc.'</h3><div><ul>';
foreach($subc_array as $subc)
{
$htmlString.= '<li><a class="sub_menu" href="#">'.$subc.'</a></li>';
}
$htmlString.= '</ul></div>';
}
return $htmlString;
}