printing last company in the excel file - php

I have done a program using PHPExcel and TCPDF on PHP. where I can select companies listed in excel file according to column that they are located.
I am tracking companies between already defined columns and between rows that I can scan till "next company's name". So that I can print them out in the screen.
I upload a screenshot how my excel file looks like...
after I retrieve the data from excel file it looks like
However, when I select last company since there is no "next company", it doesn't return result; on the contrary it gives an error.
my question: how can I control "last company" and print it out like the others. I couldn't put an exceptional condition for last one.
related part of my code looks like this:
if(isset($_POST['submit']))
{
$selected_val = $_POST['my_select']; // Storing Selected Value In Variable
$only_row = explode('.',$selected_val);
//echo "You have selected :" .$selected_val. "<br />"; // Displaying Selected Value
//echo "selected row value :".$only_row[1]. "<br />"; this shows selected company's row number
for($i=0; $i< $count; $i++)
{
if ($comp[$i][2]== $only_row[1])
{
$info_end=($comp[$i+1][2]-1);// here table ends before the next company's name begins
}
}
}
else{error_reporting(E_ALL ^ E_NOTICE);}
$rowCompanyInfoStart = $only_row[1]+2;
$rowCompanyInfoEnd = $info_end;
$colCompanyInfoStart = 'C';
$colCompanyInfoEnd = 'M';
PS: it would be appreciated if you can give a clear answer.
If something is unclear on the question, please let me know.

All you got to do is a test on $i, because you can't access $comp[$i+1][2]-1 when $i = $count-1.
So to do something different if this is the last line :
for($i=0; $i< $count; $i++) {
if ($comp[$i][2]== $only_row[1]) {
// line found
if($i == ($count - 1)) {
// what you want to do on last line...
} else {
// what to do normally
$info_end=($comp[$i+1][2]-1);
}
}
}

thanks to #Random
here is my full solution with exception for the last company
if(isset($_POST['submit']))
{
$selected_val = $_POST['my_select']; // Storing Selected Value In Variable
$only_row = explode('.',$selected_val);
//echo "You have selected :" .$selected_val. "<br />"; // Displaying Selected Value
//var_dump($only_row);
//echo "selected row value :".$only_row[1]. "<br />";
for($i=0; $i< $count; $i++) {
if ($comp[$i][2]== $only_row[1]) {
// line found
if($i == ($count - 1)) {
// what you want to do on last line...
$info_end=($objPHPExcel->setActiveSheetIndex(0)->getHighestRow());
}
else {
$info_end=($comp[$i+1][2]-1);
}
}
}
}

Related

PHP condition fails while using Session

I made a card game with PHP but there I'm facing some issue.
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
I'm getting an input from the user. The problem is, when the game loads at first, and the user enters an input and clicks submit, the game won't work. The condition ($_SESSION["bet"] != NULL) is giving true and bankroll is not defined.
Is there a way I can set this up properly? Is there some PHP method that can initialize the variable once then only works it on session start, then the rest of the code can take care of how that variable gets updated? The bankroll variable gets initialized if the user clicks submit without anything in it right now, so the game still works but it starts improperly.
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
The bankroll variable gets initialized to 1000 every time user submits a NULL input. I want to change this.
More code... Updating...
session_start();
$_SESSION["bet"] = $_POST["bet"];
echo "<br>";
//print_r($_SESSION);
if ($_SESSION["bet"] != NULL)
{
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
echo "Your bet is: " . $_SESSION["bet"] . "<br>";
}
if ($_SESSION["bet"] == NULL)
{
$_SESSION["bankroll"] = 1000;
}
else if ($_SESSION["bet"] > 1000 || $_SESSION["bet"] < 0)
{
echo " Please enter between 0 and 1000.";
}
else if ($_SESSION["bet"] > $_SESSION["bankroll"])
{
echo "You can't enter more than what you have.";
}
else
{
$deck = array();
for($x = 0; $x < 54; $x++) {
$deck[$x] = $x;
}
shuffle($deck);
//Then more stuff. This one for example...
if(($houseSuits[0] == -100) || ($houseSuits[1] == -100) || ($houseSuits[2] == -100) || ($houseSuits[3] == -100))
{
echo "<br>";
echo '<center> PLAYER WINS! (HOUSE HAS JOKER) </center>';
echo "<br>";
$_SESSION["bankroll"] = $_SESSION["bankroll"] + $_SESSION["bet"]; //THESE NEED TO BE ADDRESSED.
}
I JUST WANT TO FIND A WAY TO INITIALIZE BANKROLL TO 1000 AT START. THE WAY I'M DOING IT IS BY SUBMITTING A NULL VALUE THEN ASSUMING USER NEVER SUBMITS NULL VALUE AGAIN.
I WOULD LIKE BANKROLL TO BE INITIALIZED TO 1000, THEN FOR THE GAME TO TAKE CARE OF HOW BANKROLL GETS UPDATED.
I FOUND A WAY TO DO IT BUT IT'S NOT A PROPER WAY SO THAT'S WHY I'M ASKING FOR HELP.
THANK YOU.
Ok try this.
So if the bankroll is not set, then set it, once it's set it wont get set again because it's set.
Then any conditions after are fine.
session_start();
// Initialise bankroll if not already
if (!isset($_SESSION['bankroll'])) {
$_SESSION['bankroll'] = 1000;
echo "Your starting bankroll is: " . $_SESSION["bankroll"] . "<br>";
}
$_SESSION['bet'] = $_POST['bet'];
if ($_SESSION['bet'] != NULL) {
echo "Your bet is: " . $_SESSION['bet'] . "<br>";
}
if ($_SESSION['bet'] > 1000 || $_SESSION['bet'] < 0) {
echo " Please enter between 0 and 1000.";
} elseif ($_SESSION['bet'] > $_SESSION['bankroll']) {
echo "You can't enter more than what you have.";
} else {
// Your card game stuff
}
Notes: you may have issues with using session as it'll store their bet wherever they are, so issuing a bet sets the session, then navigate elsewhere and come back and their bet will still be as before. Maybe this doesn't matter.
You also might not want to check if the bet is null, more perhaps empty or whatever. Test either way to be sure.

Is it possible to execute a code block for first looping, then a different code block for every loop after?

Is it possible to have one code block execute when the loop runs throught once, then every time after it run a different code block?
for example, I have:
while ($blank > 0) {
echo "<td></td>";
$blank--;
$day_count++;
}
I would like to change it to this for the first time it runs:
echo "<td class = 'left'></td>";
Then after the first loop through, go to this:
echo "<td></td>";
Is that possible at all?
$firstrow = true;
while ($blank > 0) {
if ($firstrow) {
echo "<td class = 'left'></td>";
$firstrow = false;
} else {
echo "<td></td>";
}
$blank--;
$day_count++;
}
It's not exactly clear from your question what "first time" means for you. But in principle, you should be able to create a variable that indicates whether this is the first time. For example, you can use isset:
while($blank>0) {
if !isset($notTheFirstTime){
...
}
else {
}
$notTheFirstTime = 1
}
The first time you encounter this loop, the variable $notTheFirstTime does not yet exist, and the first block of code is run; once you've been through the loop once, the variable exists. That means this will only run once. On the other hand, if you want to do something "on the first pass through the loop, every time I encounter the loop" then I would recommend just putting the relevant code outside of the loop, rather than inside.
This should work for you:
<?php
//$blank = 3;
//$day_count = 0;
for($i = $blank; $blank > 0; $blank--) {
if($i == $blank)
echo "<td class = 'left'></td>";
else
echo "<td></td>";
$day_count++;
}
?>
Output:
<td class = 'left'></td><td></td><td></td>

Trouble with retrieving data from mysql with HTML select box

Okay so I am developing a search engine for a non-profit group using MYSQL and PHP. The data appears fine from all the other fields. But when I try to get data from a drop down select box the data doesn't appear.
I know my code is pron to SQL injections however there isn't any important data kept on the server, it just info about treatments and research studies.
I would like to do it with a function. I was also wondering if there is anyway to retrieve data from multiple boxes. Like I have a keyword search and a drop down combo box both of them are set. How do I retrieve data from both columns in the database using the function I have? Thanks
Here is my code if you guys could help me that would be great thanks
The code for the html box
Broad Research Topic <select name="Treatment1">
<option value="Other">
Other
</option>
<option value="Treatment">
Treatment
</option>
<option value="PracticalCure">
Practical Cure
</option>
The php code to check if it is set
if (isset($_GET['Treatment1']) && in_array($_GET(['Treatment1']),
array('Treatment', 'PracticalCure', 'Other')) {
$state = $_GET['Treatment1'];
Investigator6($state); }
}
The Function Investigator6
function Investigator6($state)
{
$state = trim($state);
$state = preg_replace('/\s+/', ' ', $state);
//seperate multiple keywords into array space delimited
$keywords = explode(" ", $state);
//Clean empty arrays so they don't get every row as result
$keywords = array_diff($keywords, array(
""
));
//Set the MySQL query
if ($state == NULL or $state == '%') {
} else {
for ($i = 0; $i < count($keywords); $i++) {
$query = ("SELECT * FROM Studies1 WHERE BroadResearchTopic LIKE
' %$keywords[$i]%'");
}
//Store the results in a variable or die if query fails
$result = mysql_query($query) or die(mysql_error());
}
if ($state == NULL or $state == '%') {
} else {
//Count the rows retrived
$count = mysql_num_rows($result);
echo $count;
}
//If search variable is null do nothing, else print it.
if ($state == NULL) {
} else {
echo "You searched for <b><FONT COLOR=\"blue\">";
foreach ($keywords as $value) {
print "$value ";
}
echo "</font></b>";
}
echo "<p> </p><br />";
echo "</center>";
//If users doesn't enter anything into search box tell them to.
if ($state == NULL) {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.
b</font></b><br /></center>";
} elseif ($state == '%') {
echo "<center><b><FONT COLOR=\"red\">Please enter a search parameter to continue.
</font></b><br /></center>";
//If no results are returned print it
} elseif ($count <= 0) {
echo "<center><b><FONT COLOR=\"red\">Your query returned no results from the
database.</font></b><br /></center>";
//ELSE print the data in a table
} else {
//Table header
echo "<center>";
echo "</center>";
//Colors for alternation of row color on results table
$color1 = "#d5d5d5";
$color2 = "#e5e5e5";
//While there are rows, print it.
while ($row = mysql_fetch_array($result)) {
//Row color alternates for each row
$row_color = ($row_count % 2) ? $color1 : $color2;
//table background color = row_color variable
echo "<td style = \"padding: 10px\">" . $row['BroadResearchTopic'] . "</td>";
$row_count++;
if ($state == NULL or $state == '%') {
} else {
//clear memory
mysql_free_result($result);
}
}

Exporting a dynamic table to Excel in PHP

I have a large table with an unknown amount of columns that I want to be able to export to MS Excel via a download link. I have done this before with no issues. However, that was when I had a known number or columns. I currently am able to successfully send data to an Excel file. The table headers display correctly across the top of the table. The problem is with the data. Instead of placing the data across the page in the correct columns, it is putting it all in the first column. Here is part of my code:
while($row = mysql_fetch_row($result))
{
// Loops through the results
for($i=0; $i < $num_cols; $i++)
{
// Prints out the data in a table cell
echo("<Td class='data'>$row[$i]</Td>");
$FileRecord = Array($row[$i]);
$exportFile->Export_Record($FileRecord);
}
}
Normally I do $FileRecord = Array($row[0], $row[1], ..., $row[n]) and everything works great, but I am not sure how to do that if I don't know how many columns there are. Any help would be great!
I am not using any library. $exportFile is from a function that I am using. It looks like this:
class CSV_File {
private $out='';
private $name='';
private $column_names="";
private $count = 0;
//Creates the file name and the header columns
function __Construct($buf, $names) {
$GLOBALS["name"] = $buf;
$GLOBALS["column_names"] = ($names."\n");
}
public function Export_Record($array) {
if (!is_array($array))
throw new Exception("NOT AN ARRAY");
for ($i = 0; $i <= count($array); $i++) {
$GLOBALS["out"] .= $array[$i];
if ($i < count($array)-1) {
$GLOBALS["out"] .= ",";
}
}
$GLOBALS["out"] .= "\n";
$GLOBALS["out"]++;
}
public function ExportButton($align) {
$output = $GLOBALS["out"];
$filename = $GLOBALS["name"];
$columns = $GLOBALS["column_names"];
if ($align == null)
$align = "align";
echo(" <$align><form name=\"export\" action=\"export.php\" method=\"post\">
<button type=\"submit\" style='border: 0; background: transparent; font-size: 12px;font-weight:bold;'>
<img src = 'images/icon_csv.png' width = '16' height ='16' alt ='Download Data'> Download</button>
<input type=\"hidden\" value=\"$columns\" name=\"csv_hdr\">
<input type=\"hidden\" value=\"$filename\" name=\"fileprefix\">
<input type=\"hidden\" value=\"$output\" name=\"csv_output\">
</form></align>");
}
}
And then export.php looks like this:
if (isset($_POST['csv_hdr']))
{
$out .= $_POST['csv_hdr'];
$out .= "\n";
}
if (isset($_POST['csv_output']))
{
$out .= $_POST['csv_output'];
}
if (isset($_POST['fileprefix']))
{
$fname .= $_POST['fileprefix'];
}
//Now we're ready to create a file. This method generates a filename based on the current date & time.
$filename = $fname."_".date("Y-m-d_H-i",time());
//Generate the CSV file header
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header("Content-disposition: filename=".$filename.".csv");
//Print the contents of out to the generated file.
print $out;
//Exit the script
exit;'
That's not an Excel table. It's an html table that you just happen to be feeding into Excel.
Your problem is that you're not starting a new table row for every record you're fetching, so everything just becomes a new cell in the first row.
You need something like
while($row = mysql_fetch_assoc($result)) {
echo '<tr>';
foreach($row as $val) {
echo "<td>$val</td>";
}
echo '</tr>';
}

Drupal 7 Views 3: Displaying the number of displayed nodes? Example: (Showing 3842 of 5382 results)

How could we display the number of displayed nodes in a View? Like:
"Showing 3842 of 5382 results"
Then if all nodes in the View are displayed at once, (often initially), it might say:
"Showing all 5382 results"
Then if no nodes in the View are displayed from the filter, it might say:
"Found no results"
Is this very hard? I think it would be a very useful addition and would appreciate any help with this.
I'm sure this could be done more succinctly. But I wanted to make it clear what I was doing. So here it is. Basically you can use this in the header or footer of your view.
<?php
$view = views_get_current_view();
$c = $view->total_rows;
$cp = $view->get_current_page();
$pp = $view->get_items_per_page();
$si = ($cp * $pp) + 1;
$ei = $si + ($pp - 1);
if($c > 0) {
if($pp < $c) {
if($ei > $c) {
print "Showing $si to $c of $c results";
} else {
print "Showing $si to $ei of $c results";
}
} else {
print "Showing all $c results";
}
} else {
print "Found no results";
}
?>
1) go to edit view
2) add field
3) Global: View result counter
4) Profit.

Categories