How to assign data to excel sheets in alphabetical order in PHPExcel - sql

I am trying to create excel generated file. I want to get usernames from database and then print names according to each letter in alphabet. I am able to create sheets in alphabetical order but cant print names on each sheet.
Here is what i have so far:
<?php
require_once ('PHPExcel/Classes/PHPExcel.php');
include('inc/database_connection.php');
$conn = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME);
$conn->set_charset('utf8_unicode_ci');//if not by default
// Create new PHPExcel object
$objPHPExcel = new PHPExcel();
$F = $objPHPExcel->getActiveSheet();
$Letter='B';
$Number=2;
for($i=321; $i<347; $i++)
{
$F = $objPHPExcel->createSheet($i); //Setting index when creating
$F->setCellValue('A1', "Username")
->setCellValue('B1', "Project")
->setCellValue('C1', "Processes");
$request="SELECT username FROM user WHERE username LIKE '".chr($i+32)."%'";
$result= $conn->query($request);//get the result (ressource)
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$username=$row["username"];
$F->setCellValue('A'.$Number, ' '.$username.' ');
$F->getRowDimension('1')->setRowHeight(20);
$F->getColumnDimension($Letter)->setWidth(30);
++$Number;
}
} else
{
echo "0 results";
}
$F->setTitle(chr($i));
}
// Redirect output to a client’s web browser (Excel5)
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="HeadCount.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
?>
Is there way to print usernames for each spreedsheet? Thank you.

Problem was solved by removing if statement
$objPHPExcel = new PHPExcel();
$F = $objPHPExcel->getActiveSheet();
for($i=321; $i<347; $i++)
{
$Letter='B';
$Number=2;
$F = $objPHPExcel->createSheet($i); //Setting index when creating
$objPHPExcel->setActiveSheetIndex(1);
$F->setCellValue('A1', "Username")
->setCellValue('B1', "Project")
->setCellValue('C1', "Processes");
$request="SELECT username FROM user WHERE username LIKE '".chr($i+32)."%'";
$result= $conn->query($request);//get the result (ressource)
// output data of each row
while($row = $result->fetch_assoc())
{
$username=$row["username"];
$F->setCellValue('A'.$Number, ' '.$username.' ');
$F->getRowDimension('1')->setRowHeight(20);
$F->getColumnDimension($Letter)->setWidth(30);
++$Number;
}
$F->setTitle(chr($i));
}

Related

I can't access admin panel of my script : Invalid query You have an error in your SQL syntax

I have an error message when i try to access my script (php):
Invalid query: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's marketing advertising'' at line 1
This is a admin php file contain mysql query
<?php
$stt_query = $ocdb->get_rows("SELECT * FROM ".$config->prefix."search order by id desc limit 13" );
if (count( $stt_query ) > 0) {
foreach ($stt_query as $row) :
?>
<li><?php echo $row['title'];?></li>
<?php
endforeach;
}
?>
the php query page:
<?php class OCDB { var $server = ""; var $port = ""; var $db = ""; var $user = ""; var $password = ""; var $prefix = ""; var $insert_id; var $link; function __construct($_server, $_port, $_db, $_user, $_password, $_prefix) { $this->server = $_server; $this->port = $_port; $this->db = $_db; $this->user = $_user; $this->password = $_password; $this->prefix = $_prefix; $host = $this->server; if (defined('DB_HOST_PORT') && !empty($this->port)) $host .= ':'.$this->port; $this->link = mysqli_connect($host, $this->user, $this->password) or die("Could not connect: " . mysqli_connect_error()); mysqli_select_db($this->link, $this->db) or die ('Can not use database : ' . mysqli_error($this->link)); mysqli_query($this->link, 'SET NAMES utf8'); } function get_row($_sql) { //$res = $this->link->query($_sql); //if ($this->link->error) { //try { //throw new Exception("MySQL error $mysqli->error <br> Query:<br> $query", $this->link->errno); //} catch(Exception $e ) { //echo "Error No: ".$e->getCode(). " - ". $e->getMessage() . "<br >"; //echo nl2br($e->getTraceAsString()); //} //} $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $row = mysqli_fetch_array($result, MYSQL_ASSOC); mysqli_free_result($result); return $row; mysqli_close($this->link); } function get_rows($_sql) { $rows = array(); $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) { $rows[] = $row; } mysqli_free_result($result); return $rows; } function get_var($_sql) { $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $row = mysqli_fetch_array($result, MYSQL_NUM); mysqli_free_result($result); if ($row && is_array($row)) return $row[0]; return false; } function query($_sql) { $result = mysqli_query($this->link, $_sql) or die("Invalid query: " . mysqli_error($this->link)); $this->insert_id = mysqli_insert_id($this->link); return $result; } function escape_string($_string) { return mysqli_real_escape_string($this->link, $_string); } } ?>
Please can you help me i can't access admin panel because of this error.
Thanks

change password code is not working

I was just working on a password changing program for my website, it resulted in all my users passwords changed into the same password.
The code which I used is displayed below.
If any one could help me out it would be a big thanks to him/her.
//if form has been submitted process it
<br/>
if(isset($_POST['submit'])){
$stmt = $db->prepare('SELECT password FROM user WHERE password = :hashedpassword');
$stmt->execute(array(':hashedpassword' => $_POST['password']));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if(strlen($_POST['password']) < 3){
$error[] = 'Password is too short.';
}
if(strlen($_POST['passwordConfirm']) < 3){
$error[] = 'Confirm password is too short.';
}
if($_POST['password'] != $_POST['passwordConfirm']){
$error[] = 'Passwords do not match.';
}
//if no errors have been created carry on
if(!isset($error)){
//hash the password
$hashedpassword = $user->password_hash($_POST['password'], PASSWORD_BCRYPT);
try {
//insert into database with a prepared statement
$sql="UPDATE user SET password = :hashedpassword";
$stmt = $db->prepare($sql);
$stmt->execute(array(
':hashedpassword' => $hashedpassword
));
//redirect to index page
header('Location: login.php?action=resetAccount');
exit;
//else catch the exception and show the error.
} catch(PDOException $e) {
$error[] = $e->getMessage();
}
}
}

ModX PDO SQL returns empty array

I pretty much copy/pasted this from the ModX RTFM:
$results = $modx->query("SELECT * FROM `saved_jobs` WHERE `job_id` = $job_id AND `user_id` = $user");
if (!is_object($results)) {
return 'No result!';
}
else {
$r = $results->fetchAll(PDO::FETCH_ASSOC);
echo $r;
echo "<br>count " . count($r);
print_r($r);
}
But even though there are no records in the database I still get the 'else' occurring. The line echo "count " . count($r); produces the output: count 0
Does anyone know whats going on and how to fix it?
If your query is successful, you still create an object with your first statement.
take a peek [also from the docs]:
$result = $modx->query("SELECT * FROM modx_users WHERE id='blah'");
echo '<pre>'; var_dump($result); echo '</pre>';
if (!is_object($result)) {
return 'No result!';
}
else {
$row = $result->fetch(PDO::FETCH_ASSOC);
return 'Result:' .print_r($row,true);
}
What you want to do is find out if the object actually contains a result set:
$result = $modx->query("SELECT * FROM modx_users WHERE id='1'");
echo '<pre>'; var_dump($result); echo '</pre>';
if (!is_object($result)) {
return FALSE;
}
if(sizeof($result) > 0){
while($row = $result->fetch(PDO::FETCH_ASSOC)){
echo'Result:' .print_r($row,true);
}
}
so you can either test the size of the $result variable or just run the while loop & test if it has any data as well.

yii phpexcel file reader no response

I have a piece of code that is
$excelFile = '/tmp/sheet.xls' ;
Yii::import('application.vendors.PHPExcel',true);
$inputFileType = PHPExcel_IOFactory::identify($excelFile);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($excelFile);
$objWorkSheet = $objPHPExcel->getActiveSheet();
$highestRow = $objWorkSheet->getHighestRow();
$hightestColumn = $objWorkSheet->getHightestColumn();
$hightestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
echo '<table>'."\n" ;
for($row=2; $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" ;
But when this code execute I do not get any file display. I also tried to put debugs to check where it failed, I could localize the error to getActiveSheet.
Any help would be appreciated
Thanks
Try import PHPExcel like this:
spl_autoload_unregister(array('YiiBase', 'autoload'));
Yii::import('application.vendors.PHPExcel', true);
$this->objPHPExcel = new PHPExcel();
spl_autoload_register(array('YiiBase', 'autoload'));
Here is how i display the imported excel file and works:
spl_autoload_unregister(array('YiiBase','autoload'));
Yii::import("application.vendors.phpexcel.Classes.PHPExcel", true);
$inputFileType = PHPExcel_IOFactory::identify($path);
$objReader = PHPExcel_IOFactory::createReader($inputFileType); //Excel5);
$objPHPExcel = $objReader->load($path);
spl_autoload_register(array('YiiBase','autoload'));
foreach ($objPHPExcel->getWorksheetIterator() as $worksheet) {
foreach ($worksheet->getRowIterator() as $row) {
$rowIndex=$row->getRowIndex();
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set
foreach ($cellIterator as $cellIndex=>$cell) {
if (!is_null($cell)) {
if($rowIndex >1 && $cellIndex<=55){
$cellVal=$cell->getCalculatedValue();
echo $cellVal;
}
}
}
}
}

MODx querying custom db table

See the code below. I'm trying to get some data from a database is modx. The data is there, meaning, when i query the database in phpmyadmin, i get results. I can't figure out why it doesnt work in modx.
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
$stmt = $modx->prepare($sql);
$stmt->execute();
// Put data in array
$order_data = $stmt->fetch(PDO::FETCH_ASSOC);
if ($order_data == '') {
return 'Resultset empty for user '. $user_id.'.<br />'.$sql;
} else {
return 'Data found!';
}
Perhaps try using xPDO:
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
$c = new xPDOCriteria($modx,$sql);
if ($c->stmt && $c->stmt->execute()) {
$order_data = $c->stmt->fetch(PDO::FETCH_ASSOC);
var_dump($order_data);
}
You need to loop through your output, the result will be an array of arrays.
The below example will return the data and present it according to a chunk format
<?php
$sql = "SELECT * FROM `table_name`";
$query = $modx->query($sql);
$rows = array();
if ($query) {
// loop through the result set and inspect one row at a time
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
array_push($rows, $row);
$output .= $modx->getChunk($tpl,$row);
}
}
$output = "<table border=\"1\" cellpadding=\"5\" >
<th>ID</th><th>row1_Head</th><th>row2_Head</th><th>row3_Head</th><th>row4_Head</th><th>row5_Head</th>
$output</table>";
return $output;
This is an example of the chunk:
<tr>
<td>[[+id]]</td> <td>[[+row1]]</td> <td>[[+row2]]</td> <td>[[+row3]]</td> <td>[[+row4]]</td> <td>[[+row5]]</td>
</tr>
Now in a resource call your snippet like
[[!Snippet_name? &tpl=`chunk_name`]]
$sql = 'SELECT * FROM orders ORDER BY created DESC LIMIT 1';
Assume your schema is like
<?xml version="1.0" encoding="UTF-8"?>
<model package="your_package_name" baseClass="xPDOObject" platform="mysql" defaultEngine="MyISAM" version="1.1">
<object class="Orders" table="orders" extends="xPDOSimpleObject">
<field key="order_no" dbtype="varchar" precision="255" phptype="string" null="false" />
<!-- and everything else below -->
</object>
<!-- and everything else below -->
</model>
What you need to do is as simple as this:
$modx->addPackage('your_package_name'); // Add your table schema to MODX object
$orders = $modx->getCollection('Orders'); // class's name, not table's name
$output = '';
if ($orders){
$outputArray = array();
foreach ($orders as $order) {
$orderArray = $order->toArray();
$outputArray[] = $modx->getChunk('your_row_chunk_name', $orderArray);
}
$wrapper = array(
'orders' => #implode("\n", $outputArray);
);
$output = $modx->getChunk('your_wrapper_chunk_name', $wrapper);
}
return $output;