Code causing page to render blank with PHP - php

So this is the first PHP script (if it's even called that?) that I've ever written from scratch, and I'm having an issue in that when it's applied to the existing (and otherwise working) page, the page shows up blank. I was hoping one of the many people who are better and more experienced than I am can take a look and find what is no doubt a blatant syntax error. Thank you in advance to anyone that shows me the light!
<?php
$sql = "SELECT * FROM 'jos_downloads_files'";
$rows = $db->fetch_all_array($sql);
foreach($rows as $row) {
$filename = $row['filetitle'];
$filepath = $row['realname'];
$featured = $row['featured'];
$id = $row['containerid'];
}
foreach ($id as $containername) {
if ($id == 2) {
$containername ="Incidental Information";
}
if ($id == 3) {
$containername ="Monitoring Reports";
}
if ($id == 4) {
$containername ="Agendas";
}
if ($id == 5) {
$containername ="Decision Prep";
}
if ($id == 6) {
$containername ="Agendas";
}
if ($id == 7) {
$containername ="Policy Governance";
}
echo '<div class = "moduletable">
<h3>' . $containername . '</h3>';
foreach ($featured as $featureedtrue) {
if ($featuredtrue == 1) {
echo '<ul class="weblinks">
<li>
<a>' . $filename . '</a>
</li>';
}
}
}
?>

As celeriko mentioned, you never declared $db prior to using it. As Xatenev mentioned, I'm not sure what fetch_all_array is, perhaps fetchAll()? Finally, as Valery Statichny mentioned, $id will never be an array.
In the future, it is helpful to turn on error reporting so that you can see where your scripts are crashing. You can do so by adding the following:
ini_set('display_errors',1);
error_reporting(E_ALL);
In production environments, turn error reporting off so that users don't see error messages.
Edit
More from Xatenev:
Why are you looping foreach $featured? $featured can only be ONE entry at the moment. You have to write $featured[] = $row['featured']; to get an array where u can loop through. Same to $id. 5. You are looping through $featured but use $filename then? $filename will print an array EVERY TIME you loop through $featured. So for example when you have 100 entries in $featured, you have 100x the same content when you print out $filename. – Xatenev

Related

How to fix Array overwritten after foreach loop php

I am having issue data Array overwritten in foreach loop. Result I am getting like this wrongRight together .Right answer is showing but also wrong for example ZucchiniCauliflower.Please help
CODE 1
$data = array();
$dis_07= null;
$dis_03 = null;
if (is_array($row)) {
foreach ($row as $value) {
$gccat_id = $value->gccat_id;
$ccat_id = $value->ccat_id;
$cat = $value->cat_id;
if (isset($gccat_id) && $gccat_id == $id) {
$dis_07 = $value->category;
$dis_02 = $value->child_id;
}
if (isset($ccat_id) && $ccat_id == $id) {
$dis_03 = $value->category;
$dis_02 = $value->parent_id;
}
}
}
$data['Dis_03'] = $dis_03;
$data['Dis_07'] = $dis_07;
if (isset($data['Dis_03'])) {
echo $data['Dis_03'];
}
if (isset($data['Dis_07'])) {
echo $data['Dis_07'];
}
First I tried this way But In one I was getting right in second link I am getting right So Tried the code previous one .In the prvious I am getting correct and wrong one together EExample ZucchiniCauliflower
CODE 2
if (isset($id)) {
$db = Database::newInstance();
$data = array();
$data['cat_status'] = 1;
$sql = "SELECT * FROM category WHERE cat_status=:cat_status ";
$row = $db->read($sql,$data);
$data['id'] = $crypt->decryptId($id);
echo $data['id'];
$id=$data['id'];
if (is_array($row)) {
foreach ($row as $value) {
$gccat_id=$value->gccat_id;
$ccat_id = $value->ccat_id;
$cat = $value->cat_id;
if (isset($gccat_id) && $gccat_id == $id) {
$data['Dis_03']=$value->category;
}
if (isset($ccat_id) && $ccat_id == $id) {
$data['Dis_03'] = $value->category;
break;
}
}
}
}
--------------------------READ FROM HERE------------------------
Here is a link one when I click on this link
$id=$value11->gccat_id;
$title
I expected the output is
Home>Raspberry
Here is a link Second link when I click on this link
Here id is ($value11->gccat_id)
window.open('<?= BASEURL ?>ap/'+id,'_self');
I expected the output is
Home>Cauliflower
1. WHEN I Use the Code 2 (Added break in this condition
(isset($ccat_id) && $ccat_id == $id)) Then click on link second
it gives output Home>Cauliflower which I was expecting. It is
correct.
2. But this time as I added the break in (isset($ccat_id) && $ccat_id == $id). I click on link one It gives wrong output which I was not expecting. Home>Squash which is wrong.
In one link I was expecting
Home>Cauliflower
ERROR NOTE If I add Break; then link Second gives correct output but when I remove Break; then link one give correct. I wanted Both link should give correct output.
Problem was with cat_id,ccat_id ,gccat_id.
I provided 8 digit unique number with the following output,now I am getting the correct output.
function generateUniqueNumber() {
return sprintf('%08d', mt_rand(1, 99999999));
}

if then nested statements cause page not to load

As per the suggestions of others I have added to the initial code. Same result:
I am having an issue with the following if statement.
When it finds results on either of the two conditions it works great and returns the results using the for each statement. If there are no results then the page doesn't load completely. I have tried using die; in a number of locations which did not improve the functions or make this work.
NEW CODE
if (!empty($query)) {
foreach ($query as $available) {
echo $available->column1 . "<br>\n";
}
} elseif (empty($query)) {
$query_plus->get_results($wpdb->prepare("SELECT column1 FROM mytable"));
foreach ($query as $available_plus_2) {
echo $available_plus_2->column1 . "<br>\n";
}
} elseif (!empty($query_plus)) {
echo "nothing here";
}
if (!empty($query)) {
foreach ($query as $available) {
echo $available->column1 . "<br>\n";
}
} elseif (empty($query)) {
$query_plus=$wpdb->get_results($wpdb->prepare("SELECT column1 FROM mytable"));
foreach ($query as $available_plus_2) {
echo $available_plus_2->column1 . "<br>\n";
}
} elseif (!empty($query_plus)) {
echo "nothing here";
}
The $wpdb-> is necessary before the prepare. Since WP is very bad at error reporting adding ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); to the top of the functions page will allow all fatal errors to be seen

some images missing after implementing RewriteRule

I have been working on this issue for what feels like endless hours, but I feel like I'm really close to solving it.
I have stripped my site down to the bare minimum code to troubleshoot this, and I think I have found the line that is causing me trouble, but I just don't know WHY it is causing me trouble. Here is my code as it is now:
//display all products
if (!isset($_GET['id'])) {
$result = mysqli_query($link, "SELECT products.*, company.company-name FROM products INNER JOIN company ON products.company-id=company.id");
if (!$result) {
echo 'Error';
exit();
}
}
//display one product
if (isset($_GET['id'])) {
$id = $_GET['id'];
$get_item_info = mysqli_query($link, "SELECT products.*, company.company-name FROM products INNER JOIN company ON products.company-id=company.id WHERE products.id='$id'");
$row = mysqli_fetch_assoc($get_item_info);
if (!$row) {
echo 'Error';
exit();
}
$company_name = $row['company-name'];
$model_abbreviation = $row['model-abbreviation'];
if ($row['model-version'] == NULL) { $image_directory_name = "$company_name/$model_abbreviation/"; } else $image_directory_name = "$company_name/$model_abbreviation (" . $row['model-version'] . ")/";
}
if (!isset($_GET['id'])) {
$group = array();
while ($row = mysqli_fetch_assoc($result)) {
$group[ $row['company-name'] ][] = $row;
}
foreach ($group as $company_name => $models) {
foreach ($models as $model) {
echo "<a href='$model[id]/'>$model[model-abbreviation]</a>";
}
}
}
if (isset($_GET['id'])) {
$top_thumb = "$image_directory_name" . "top.jpg";
echo "<img src='$top_thumb'>"; echo '</br>';
$images = glob($image_directory_name."*_thumb*");
if (!$images) {
echo 'No images to display.';
}
else {
foreach ($images as $image) {
$full = str_replace('thumb','full',$image);
echo '<img src="'.$image.'">';
}
}
}
So if I use this code in combination with my rewriterule:
RewriteRule ^products/(.*)/$ /products/index.php?id=$1
And I go to a product page, such as localhost/products/30/
No images display, HOWEVER, in the page source I can see that it is TRYING to display the images (though I get no error from my script, just a blank page), just with the wrong path - it looks like this:
<img src='Company Name/Model Name (Model Version)/top.jpg'></br><img src="Company Name/Model Name (Model Version)/A_thumb.jpg">
So the code is working, but the path is wrong. OK.
So I added /products/ to the $image_directory_name variable in this line:
if ($row['model-version'] == NULL) { $image_directory_name = "/products/$company_name/$model_abbreviation/"; } else $image_directory_name = "/products/$company_name/$model_abbreviation (" . $row['model-version'] . ")/";
This is where it breaks.
The top thumb is fixed and displays, but I get my error when trying to glob() the bottom thumbs - 'No images to display'. And the source doesn't even show as trying to load them anymore.
So. I have gotten really close, I've spent countless hours on this. Anyone got any idea what's going on? Something to do with my $image_directory_name path or the glob() code I'm guessing...I am so mentally desperate to solve this.
edit: additional info: When I go to localhost/products/companyname/productname/ in my browser, I get the Error from the if (!$row) line in my code. But I go to localhost/products/companyname/productname/imagename.jpg, the image loads.
update: I even tried moving all of my images from /products/companyname/productname/
to /images/companyname/productname/
The bottom thumbs still don't show up. Argh.

PHPExcel_Style_Fill infinite recursion

I use library PHPExcel 1.7.9 to work with Excel files. First, I create a template, stylise and polish it. Then, to avoid style hardcoding, using the above mentioned library I open that template, change some values and save it as a new .xlsx file.
First, we fetch that style from cells.
$this->styles = array() ;
$this->styles['category'] = $sheet->getStyle("A4");
$this->styles['subcategory'] = $sheet->getStyle("A5");
Here is the recursive function, that displays categories and subcategories.
private function displayCategories($categories, &$row, $level = 0){
$sheet = $this->content ;
foreach($categories as $category){
if ($category->hasChildren() || $category->hasItems()){ //Check if the row has changed.
$sheet->getRowDimension($row)->setRowHeight(20);
$sheet->mergeCells(Cell::NUMBER . $row . ":" . Cell::TOTAL . $row) ;
$name = ($level == 0) ? strtoupper($category->name) : str_repeat(" ", $level*6) ."- {$category->name}" ;
$sheet->setCellValue(Cell::NUMBER . $row, $name) ;
$sheet->duplicateStyle((($level == 0) ? $this->styles['category'] : $this->styles['subcategory']), Cell::NUMBER . $row);
$row++ ;
if ($category->hasChildren()){
$this->displayCategories($category->children, $row, $level+1);
}
}
}
}
The problem
If $sheet->duplicateStyle() is used, it will be impossible to save document because of infinite recursion.
Maximum function nesting level of '200' reached, aborting! <- FATAL ERROR
The problem is in the next piece of code, inside PHPExcel_Style_Fill class, one object is referencing himself over and over.
public function getHashCode() { //class PHPExcel_Style_Fill
if ($this->_isSupervisor) {
var_dump($this === $this->getSharedComponent()); //Always true 200 times
return $this->getSharedComponent()->getHashCode();
}
return md5(
$this->getFillType()
. $this->getRotation()
. $this->getStartColor()->getHashCode()
. $this->getEndColor()->getHashCode()
. __CLASS__
);
}
Is any workaround to solve this? I would also accept any ideas on how to apply a complete style of one cell to another.
Solution:
As #MarkBaker said in comments, branch develop on GitHub really contains fixes to the bug.
EDIT I added a pull request with a fix: https://github.com/PHPOffice/PHPExcel/pull/251
This happens when you try to duplicate cell's style to the same cell; Take a look at this:
$phpe = new PHPExcel();
$sheet = $phpe->createSheet();
$sheet->setCellValue('A1', 'hi there') ;
$sheet->setCellValue('A2', 'hi again') ;
$sheet->duplicateStyle($sheet->getStyle('A1'), 'A2');
$writer = new PHPExcel_Writer_Excel2007($phpe);
$writer->save('./test.xlsx');
It will work just fine. BUT if I add another line like this:
$sheet->duplicateStyle($sheet->getStyle('A1'), 'A1');
then bang, infinite recursion starts after calling the save method
To fix your code, you should modify this part:
$sheet->duplicateStyle((($level == 0) ? $this->styles['category'] : $this->styles['subcategory']), Cell::NUMBER . $row);
To something along the lines of:
$style = ($level == 0) ? $this->styles['category'] : $this->styles['subcategory'];
$targetCoords = Cell::NUMBER . $row;
if($style->getActiveCell() != $targetCoords) {
$sheet->duplicateStyle($style, $targetCoords);
}
Without knowing the specifics of the library...
How about changing this:
public function getHashCode() { //class PHPExcel_Style_Fill
if ($this->_isSupervisor) {
To this:
public function getHashCode() { //class PHPExcel_Style_Fill
if ($this->_isSupervisor && ( $this != $this->getSharedComponent() ) ) {
If the hash code logic after the if statement does not apply to _isSupervisor, then add another logic statement and return a fixed value, like this:
public function getHashCode() { //class PHPExcel_Style_Fill
if ($this->_isSupervisor) {
if ( $this == $this->getSharedComponent() )
return md5(0);

Optimize existing code and need to list alphabetically

I need help optimizing the code to run faster, unless it is optimized the best.
I also want to alphabetize the list and I am unsure how to do that.
It should be alphabetized by $userinfo[0]["sn"][0]
I am using the adLDAP class: http://adldap.sourceforge.net/
<?php
require_once('adLDAP.php');
//header('Content-type: text/json');
$adldap = new adLDAP();
$groupMembers = $adldap->group_members('STAFF');
//print_r($groupMembers);
$userinfo = $adldap->user_info($username, array("givenname","sn","telephonenumber"));
$displayname = $userinfo[0]["givenname"][0]." ".$userinfo[0]["sn"][0];
print "<ul>";
foreach ($groupMembers as $i => $username) {
$userinfo = $adldap->user_info($username, array("*"));
$displayname = "<strong>".$userinfo[0]["givenname"][0]." ".$userinfo[0]["sn"][0]."</strong> - ".$userinfo[0]["telephonenumber"][0];
if($userinfo[0]["sn"][0] != "" && $userinfo[0]["givenname"][0] != "" && $userinfo[0]["telephonenumber"][0] != "") {
print "<li>".$displayname."</li>";
}
}
print "</ul>";
?>
I dont know about optmizing but to order your array you can use an example on PHP help page called multi_sort:
link text
There is a comment regarding code injection on the example provided but you can workaround that I think.

Categories