I'm printing out a table with 27 cols from a database, so its obvious that it'll be aesthetically displeasing if 27 cols were visible on my screen. so this is one of the conditions i've been using to see if a particular col is empty, if it is empty then the table header will not be printed and if that isnt printed another if isset condition will not print the table data. But it isn't working out as planned. These are the variations i've tried and none of them are working P.S. $result = number of rows being returned by the query.
$i = 1;
while ($i <= $result)
{
if (!empty($array['Others'][$i]))
{
$others = print "<th>Others</th>";
break;
}
$i++;
}
$i = 0;
while ($i <= $result)
{
$emptyothers = !empty($array['Others'][$i]);
if ($emptyothers == '1')
{
$others= print "<th>Others</th>";
break;
}
$i++;
}
Your code should be like this:
$sql = mysql_query("SELECT * FROM table");
if (mysql_num_rows($sql) > 0) {
//your code...
} else {
print 'is empty';
}
Could you use array_key_exists()?
foreach($row in $result) {
if(array_key_exists('Others', $row)) {
if(!empty($row['Others']) {
print "<th>Others</th>";
break;
}
}
}
Related
I have a script that reads values in an external XML file using PHPExcel.php, then it prints results reading the last time a number is $extraset is found into the XML file.
My problem : i should reverse the way the script calculates the result, since my values go from the newer to the older.
Example : if the 10 value appears in row 2 and then in row 6, correct result should be : 10 appears in row 2. At the moment I get '10 appears in row 10'.
Is there a way to reverse the way phpexcel read the file ? Or maybe i can just reverse the way values are processed ? Here is the script :
<?php
require_once "Classes/PHPExcel.php";
$path = "original_source.xls";
$reader = PHPExcel_IOFactory::createReaderForFile($path);
$excel_Obj = $reader->load($path);
//Get the last sheet in excel
//$worksheet=$excel_Obj->getActiveSheet();
//Get the first sheet in excel
$worksheet=$excel_Obj->getSheet('0');
$lastRow = $worksheet->getHighestRow();
$columncount = $worksheet->getHighestDataColumn();
$columncount_number = PHPExcel_Cell::columnIndexFromString($columncount);
$row_start = 6;
$row_end = 26;
$col_start = 2; //Index of column - C
$col_end = 21; //Index of column - V
$sets = array();
for ($row = 0; $row <= $lastRow; $row++) {
$set = array();
for ($col = 0; $col <= $columncount_number; $col++) {
if ($row >= $row_start && $row <= $row_end && $col >= $col_start && $col <= $col_end) {
array_push($set, $worksheet->getCell(PHPExcel_Cell::stringFromColumnIndex($col).$row)->getValue());
}
else if ($row > $row_end) {
break;
}
}
if ($row >= $row_start && $row <= $row_end) {
array_push($sets, $set);
}
else if ($row > $row_end) {
break;
}
}
//echo '<pre>'; print_r($sets); die;
$extraset = ['113', '15', '313'];
$reverse_sets = array_reverse($sets);
foreach ($extraset as $element) {
foreach ($reverse_sets as $index => $set) {
if (in_array($element, $set)) {
$actual_index = count($reverse_sets)-$index-1;
echo "Extraset element '$element' is in set $actual_index<br>";
break;
}
}
}
?>
I was trying with array_reverse, but I only keep getting 'error 500'. I'm a bit confused.
Thanks for your help
EDIT :
The modify i did with array reverse was to remove the array reverse function, changing that part in this way, and it works properly :
foreach ($extraset as $element) {
foreach ($sets as $index => $set) {
if (in_array($element, $set)) {
$actual_index = count($sets)-$index-1;
echo "Extraset element '$element' is in set $actual_index<br>";
break;
}
}
}
?>
Now the script outputs me the right value, but what I can't fix is the way $actual_index works.
This is my actual output :
Extraset element '113' is in set 0
Extraset element '15' is in set 20
Extraset element '313' is in set 20
My problem :
The way it search the values is correct, but is wrong the way it calculates the set. Set 0 should be set 20, while set 20 should be set 0.
Here is my Code
<?php
for ($x = 0; $x <= $n; $x++)
{
//Counting of rows
$countrow = get_rows($getvids);
if($offline == "Offline")
{
$apsys = "APSYS";
$offlined = "";
if ($getvids == $apsys || $getvids == $offlined )
{
echo "<tr>
<th>$x</th>
<th>$accntid[$x]</th>
<th>$fname[$x]</th>
<th>$lname[$x]</th>
<th>$vid[$x]</th>
<th>$vplatenum[$x]</th>
<th>$imei[$x]</th>
<th>$datas[1]</th>
<th>$datas[0]</th>
<th>$offline</th>";
echo "<th>$getvids</th>";
echo "<th><button type = 'button' class = 'btn btn-success viewbtn'> View Troubleshoot Report History</button></th>";
echo "</tr> ";
echo "total number of Rows:";
echo str_word_count($countrow);
}
else
{
}
}
else
{
}
}
?>
and here is my Function
<?php
function get_rows($getrowscount)
{
require ('db_connection.php');
$getrowscounts = $getrowscount;
//echo $getrowscounts;
return $getrowscounts;
}
//get_rows(); // call the function
?>
the table shows Two Rows with the value of = "APSYS"
I want to count the rows and show the output like this:
Total number of Rows: 2
but the output I can only get is like This:
Total number of Rows:1
Total number of Rows:1
Total number of Rows:0
can someone help me, I am a little bit confused about what will I use to count the rows?
Thanks.
How about this? Does this satifsfy your requirement?
<?php
$countrow = 0;
for ($x = 0; $x <= $n; $x++)
{
//Counting of rows
$countrow = $countrow + get_rows($getvids);
if($offline == "Offline")
{
//omitted
}
else
{
}
}
}
echo "total number of Rows:";
echo str_word_count($countrow);
?>
If you are trying to count them after fetching from the database, try to write a SQL query instead of your current approach.
I'm a begginer with php, and I have some troubles with it. My question is about PHP and MySQL. The purpose of the code is that I have a parameter called $sql in which I will write the SQL query. The problem is that my code only prints one row of the consult. I mean, if I have a table with 4 columns (the attributes) and in that table I have 4 rows, the code only prints one row of each column.
The method consult code:
public function makeConsult($sql){
$result = mysqli_query($this->conn, $sql);
$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
for($i = 0;$i<count($nrows);$i++) {
$row= mysqli_fetch_array($result,MYSQLI_NUM);
for ($j=0; $j < count($row) ; $j++) {
array_push($this->results, $row[$j]);
}
}
} else {
echo "No matches found";
}
}
The following method is where I print all the consults:
public function printResult(){
foreach ($this->results as $key => $value) {
echo $key . ": " . $value . "<br>";
}
$this->results = array();
}
The variable $conn is the variable where I have my sql connection.
My execution code:
$db = new dbConnection("localhost","root","","sportsweb");
$db->connect();
echo "Database name: " . $db->getDBname();
$consult = $db->makeConsult("SELECT * FROM articles A");
$db->printResult();
$db->closeConnection();
The columns (attributes) of the table "articles" are the following ones: Id,Name,Units,BranchOffice.
Thank you! :)
You have two mistakes here
$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
for($i = 0;$i<count($nrows);$i++) {
$row= mysqli_fetch_array($result,MYSQLI_NUM);
for ($j=0; $j < count($row) ; $j++) {
array_push($this->results, $row[$j]);
}
}
}
So $nrows will be a count of how many rows you got back. So count($nrows) is useless because it's not an array
Second, I don't know where you got the idea to iterate rows like that, but you're doing it wrong. Use a while loop instead. I also removed the inner for loop and switched to a simpler foreach
$nrows= mysqli_num_rows($result);
if ($nrows> 0) {
while($row = mysqli_fetch_array($result,MYSQLI_NUM)) {
foreach($row as $val) $this->results[] = $val;
}
}
When I launch my web page, increment doesn't work correctly!
It should go like this: $i = from 1 to x (0,1,2,3,4,5,6 etc..).
But instead it jumps over every step giving result of (1,3,5,7 etc..).
Why is this code doing this?
<ul class="about">
<?php
$result = mysql_query("SELECT * FROM info WHERE id = 1");
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
$endBioTxt = explode("\n", $bioText);
for ($i=0; $i < count($endBioTxt);)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
$i++;
}
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
?>
</ul>
Output:
Sometext!(right side)
0
1
Sometext2!(right side)
2
3
...
Please DONT do this as other suggested:
for ($i=0; $i < count($endBioTxt); $i++)
do this:
$count = count($endBioTxt);
for ($i=0; $i < $count; $i++) {
}
No need to calculate the count every iteration.
Nacereddine was correct though about the fact that you don't need to do:
$i++;
inside your loop since the preferred (correct?) syntax is doing it in your loop call.
EDIT
You code just looks 'strange' to me.
Why are you doing:
while ($row = mysql_fetch_assoc($result))
{
$bioText = $row['bio'];
}
???
That would just set $bioText with the last record (bio value) in the recordset.
EDIT 2
Also I don't think you really need a function to calculate the modulo of a number.
EDIT 3
If I understand your answer correctly you want 0 to be in the left li and 1 in the right li 2 in the left again and so on.
This should do it:
$endBioTxt = explode("\n", $bioText);
$i = 0;
foreach ($endBioTxt as $txt)
{
$class = 'left';
if ($i%2 == 1) {
$class = 'right';
}
echo '<li class="'.$class.'"><div>'.$txt.'</div></li>';
echo $i; // no idea why you want to do this since it would be invalid html
$i++;
}
Your for statement should be:
for ($i=0; $i < count($endBioTxt); $i++)
see http://us.php.net/manual/en/control-structures.for.php
$i++; You don't need this line inside a for loop, it's withing the for loop declaration that you should put it.
for ($i=0; $i < count($endBioTxt);$i++)
{
if (checkNum($i) == true)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
echo $i;
}
//$i++; You don't need this line inside a for loop otherwise $i will be incremented twice
}
Edit: Unrelated but this isn't how you check whether a number is prime or not
// Function to check if number is prime
function checkNum($num){
return ($num % 2) ? TRUE : FALSE;
}
This code works, please test it in your environment and then uncomment/comment what you need.
<?php
// This is how query should look like, not big fan of PHP but as far as I remember...
/*
$result = mysql_query("SELECT * FROM info WHERE id = 1");
$row = mysql_fetch_assoc($result);
$bioText = $row['bio'];
$endBioTxt = explode("\n", $bioText);
*/
$endBioTxt[0] = "one";
$endBioTxt[1] = "two";
$endBioTxt[2] = "three";
$endBioTxt[3] = "four";
$endBioTxt[4] = "five";
$totalElements = count($endBioTxt);
for ($i = 0; $i < $totalElements; $i++)
{
if ($i % 2)
{
echo "<li class='left'><div>".$endBioTxt[$i]."</div></li>";
}
else
{
echo "<li class='right'><div>".$endBioTxt[$i]."</div></li>";
}
/*
// This is how you should test if all your array elements are set
if (isset($endBioTxt[$i]) == false)
{
echo "Array has some values that are not set...";
}
*/
}
Edit 1
Try using $endBioTxt = preg_split('/$\R?^/m', $bioTxt); instead of explode.
Got this code which is troubling me and am eager to accept any help!
$x=0;
while($row = mysql_fetch_array($result))
{
if ($me == $x)
{
echo "You are $me";
break;
}
else
{
$x++;
}
}
When I include the break; it returns :
You have selected the 1
However, when I remove the break; it returns
You have selected the 1 You have selected the 1 You have selected the 1 You have selected the 1
There are currently 6 records in the database and if the code were to work it would display "You are 4th"
Any ideas?
Your $x++; only executes on else. In order to have it increment on every iteration you need to remove the else:
$x=0;
while($row = mysql_fetch_array($result))
{
if ($me == $x)
{
echo "You are $me";
break;
}
$x++;
}
Just a side note: $row doesn't seem to be related to $me and $x here. I'll assume your loop contains some other code that you've omitted, but this alone will probably answer your question.
You are icrementing $x in the else, this is never getting executed.
You need to do the increment in the same part as the echo.
So either:
$x=0;
while($row = mysql_fetch_array($result))
{
if ($me == $x)
{
echo "You are $me";
$x++;
}
else
{
$x++;
}
}
Or if you never need to increment $x without echoing:
$x=0;
while($row = mysql_fetch_array($result))
{
if ($me == $x)
{
echo "You are $me";
x++;
}
}