Default Option and returning NULL - php

Trying to figure out how to better write this chunk of code. I'm wanting to get the list of the roster members and then create an array of options for the view dropdown to display inside the select dropdown and also have it have an option to display "Please Select An Option". However what if what is returned from the getAllRoster function is NULL which is what I have returned if no results are returned from a query. How should I handle that which I just want the empty option displayed.
Also I need to think about is do a function to retrieve all the allies for that specific matter and then display that ally as the default ally in the dropdown for each dropdown.
Controller:
$rosterList = $this->bios->getAllRoster();
$allies = array();
$allies[''] = 'Please Select An Opion';
foreach ($rosterList AS $ally)
{
$allies[$ally->id] = $ally->rosterName;
}
View:
<?php echo form_label( 'Ally 1', 'ally1'); ?>
<div>
<?php echo form_dropdown( 'ally1', $allies, ''); ?>
</div>
<?php echo form_label( 'Ally 2', 'ally2'); ?>
<div>
<?php echo form_dropdown( 'ally2', $allies, ''); ?>
</div>
<?php echo form_label( 'Ally 3', 'ally3'); ?>
<div>
<?php echo form_dropdown( 'ally3', $allies, ''); ?>
</div>
EDIT :
What I am wanting to do is if the allies array is empty it needs to display the message No wrestlers in database but its instead giving me an error in my view file.
Controller:
pastebin.com/1Bf721zJ
View:
<?php echo form_label( 'Ally 1', 'ally1'); ?>
<div>
<?php if ($allies[''] == 'No Wrestlers In Database') {
echo $allies[''];
}
else {
echo form_dropdown( 'ally1', $allies, '');
} ?>
</div>
I also am curious about something. I have the alliesList variable that either has a value of a resultset or null and what I want to do if its a result set is have each of the allies be the default value in each of the dropdowns.

You could do something like this:
$rosterList = $this->bios->getAllRoster();
$allies = array();
if (empty($rosterList) {
$allies[] = 'nothing to display';
}
else
{
$allies[] = 'Please Select An Option';
foreach ($rosterList AS $ally)
{
$allies[$ally->id] = $ally->rosterName;
}
}
also in your view, if you don't want to display a drop down you could put a conditional in to display something else, e.g.:
<?php if ($allies[0] == 'nothing to display') {
echo $allies[0]
}
else {
echo form_dropdown( 'ally1', $allies, '');
} ?>

Im not sure i fully understand your question but if im right cant you just do
if $_GET['allies'] == "Please select an option"{
$something = Null
}
else{
$something = $_GET['allies']
}
and use $something where you would have used $_GET['allies']?

Related

populating dropdown with PDO::FETCH_ASSOC returns bool(false)

i'm trying to populating dropdowns in PHP, but after the dropdown it returns bool(false)
start.php
$db = new PDO('mysql:host=localhost;dbname=hospital','root','');
?>
this is for the data i'm going to use and for the dropdown for the output
require 'start.php';
$doctorsQuery = "
SELECT
specialties.SID,
specialties.name,
doctors.firstname,
doctors.lastname,
doctors.middleinitial
FROM specialties
LEFT JOIN doctors
ON specialties.SID = doctors.SID";
$doctors = $db->query($doctorsQuery);
?>
This is for the select option in the dropdown
<?php foreach($doctors->fetchAll() as $specialty): ?>
<option value="<?php echo $specialty['SID']; ?>"><?php echo
$specialty['name']; ?></option>
<?php endforeach; ?>
I'm trying to view the data here but it shows bool(false)
<?php if(isset($_GET['specialty'])){
$doctorQuery = "
{doctorsQuery}
WHERE specialties.SID == :S_ID";
$doctor = $db->prepare($doctorQuery);
$doctor->execute(['S_ID' => $_GET['specialty']]);
$selectedDoctor = $doctor->fetch(PDO::FETCH_ASSOC);
var_dump($selectedDoctor);
}
?>
It likes you using prepare statement with named placeholders, try this:
$doctor->execute([':S_ID' => $_GET['specialty']]); // you forget ":"
And... i suggest you to check row count before fetch..
if ($doctor->rowCount() === 1) {
$selectedDoctor = $doctor->fetch(PDO::FETCH_ASSOC); // so you will not get false
// your logic
} else {
// when S_ID not found
}

Getting a conditional message out of a foreach loop

I'm displaying all the posts in the category that have a valid date as follows -
<?php $blog = $pages->find('posts');
foreach($blog->children() as $blogpost): ?>
<?php if ($blogpost->title() <= $latest && $blogpost->category == $thisCat): ?>
//HTML for displaying post goes here
<?php endif ?>
<?php end foreach ?>
That works fine when those posts validate my condition, and displays nothing if it doesn't. What I want to do is display an error message (like 'there are no posts here') when there are no posts that pass the condition. I can't just do a simple else condition in that if query because it's inside the foreach loop. I can't take the if query out of the foreach loop because it relies on a variable that is defined as part of it ($blogpost).
Kind of stuck in this catch 22... Any suggestions?
How about...
<?php
$blog = $pages->find('posts');
$found_something = false;
foreach($blog->children() as $blogpost) {
if ($blogpost->title() <= $latest && $blogpost->category == $thisCat) {
$found_something = true;
//HTML for displaying post goes here
}
}
if(!$found_something) {
// display error message
}
?>
By the way, is there a specific reason why you're using the alternative PHP syntax?
I'd create a counter variable which increments each time when you display a post.
<?php $blog = $pages->find('posts');
$displayedPosts = 0;
foreach($blog->children() as $blogpost): ?>
<?php if ($blogpost->title() <= $latest && $blogpost->category == $thisCat):
$displayedPosts++; ?>
//HTML for displaying post goes here
<?php endif ?>
<?php end foreach ?>
<?php
if ($displayedPosts == 0) {
echo 'ERROR!';
}
?>
Using a boolean variable (as tmh did) is probably better in this case unless you want to count the posts.
Just count your posts , if it's 0 display just the message , else execute foreach loop :
<?php $blog = $pages->find('posts');
if(count($blog->children())==0){ echo 'No post Here'; }
else{
foreach($blog->children() as $blogpost): ?>
<?php if ($blogpost->title() <= $latest && $blogpost->category == $thisCat): ?>
//HTML for displaying post goes here
<?php endif ?>
<?php end foreach ?>
<?php } ?>

Displaying menu names from CMS

I have been trying to display a menu name from my CMS database that I created myself, I got it displayed perfectly but there is a really weird error, I spent many hours to discover the solution but I couldn't.
The problem is that I want to display the menu name as page H1 in line 50 exactly so whenever you click on the menu name its also displaying as H1 title.
The menu name is displaying correctly, but the sub menu(pages) displaying N instead of the page name, I don't know where is that N is coming from.
NOTE: There is no problem with the database connection or retrieving data.
This is my content page code:
<?php include("includes/header.php"); ?>
<?php require_once 'includes/db_connection.php'; ?>
<?php require_once 'includes/b_functions.php'; ?>
<?php require_once 'includes/cms_constants.php'; ?>
<?php db_connect();?>
<?php
if (isset ( $_GET ['subj'] )) {
$sel_subject = get_subject_by_id ( $_GET ['subj'] );
$sel_page = "NULL";
} elseif (isset ( $_GET ['pages'] )) {
$sel_subject = false;
$sel_page = get_page_by_id ( $_GET ['pages'] );
} else {
$sel_subject = "NULL";
$sel_page = "NULL";
}
?>
<table id="structure">
<tr>
<td id="navigation">
<ul class="subjects">
<?php
$subject_set = get_all_subjects();
while ($subject = mysql_fetch_array($subject_set)) {
echo "<li";
if ($subject["id"] == $sel_subject["id"]) { echo " class=\"selected\""; }
echo "><a href=\"contents.php?subj=" . urlencode($subject["id"]) .
"\">{$subject["menu_name"]}</a></li>";
$page_set = get_pages_for_subject($subject["id"]);
echo "<ul class=\"pages\">";
while ($page = mysql_fetch_array($page_set)) {
echo "<li";
if ($page["id"] == $sel_page["id"]) { echo " class=\"selected\""; }
echo "><a href=\"contents.php?pages=" . urlencode($page["id"]) .
"\">{$page["menu_name"]}</a></li>";
}
echo "</ul>";
}
?>
</ul>
</td>
<td id="page">
<?php if (!is_null($sel_subject)) { // subject selected ?>
<h2><?php echo $sel_subject['menu_name']; ?></h2>
<?php } elseif (!is_null($sel_page)) { // page selected ?>
<h2><?php echo $sel_page['menu_name']; ?></h2>
<div class="page-content">
<?php echo $sel_page['content']; ?>
</div>
<?php } else { // nothing selected ?>
<h2>Select a subject or page to edit</h2>
<?php } ?> </td>
</tr>
</table>
<?php require_once 'includes/footer.php';?>
Your 'N' is coming from the "NULL" string. I believe you meant to set your variables with actual NULL and not a string. Like:
$var = NULL;
As opposed to:
$var = "NULL";
When you access a variable that is set to "NULL" as an array, you will get the 'N' (as the string is treated as an array). For instance;
$var = "NULL";
echo $var[0]; // 'N'
Furthermore, if you test for NULL on a string it will return false (the variable is non-null);
$var = "NULL";
if($var) {
echo "var is: " . $var;
}
else {
echo "var is NULL!";
}
The above should output "var is: NULL".
I say this from experience (I did this when I started coding PHP). However, the root of your problem likely doesn't stop there as your variables should be set in subsequent conditionals. I would go through your while statements, and if statements and ensure your variables are being set appropriately. (var_dump($var) or print_r($var) through suspect blocks).

SlickGrid error: Slick.Editors.Text is not a constructor

I'm trying to implement SlickGrid on the edit page of a CakePHP project, and when the page loads I get this error in the javascript console:
slick.grid.js:2173TypeError:'Slick.Editors.Text is not a constructor' (evaluating 'new (editor || getEditor(activeRow, activeCell))')
The data renders correctly in the grid on my page, but when I click on a cell to edit it, it just turns white and I can't type anything. If I click on another cell, that cell will turn white and the first one will stay white.
Here is my php/jQuery code:
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-1.7.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery.event.drag-2.0.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-ui-1.8.16.custom.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.core.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.grid.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.editors.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.formatters.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.dataview.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellselectionmodel.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangedecorator.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangeselector.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.rowselectionmodel.js"); ?>
<?php // Setup rows and cols array for grid
$columns = array();
foreach($route['Stop'] as $stop) {
$columns[] = array( "name" => $stop['name'],
"field" => $stop['id'],
"id" => $stop['id'],
"editor" => "Slick.Editors.Text");
}
$tripId = 1;
$thisTrip['id'] = $tripId;
foreach($route['RouteTrip'] as $routeTrip) {
if($routeTrip['trip_id'] != $tripId) {
$rows[] = $thisTrip;
$tripId = $routeTrip['trip_id'];
$thisTrip['id'] = $tripId;
}
else {
$thisTrip[$routeTrip['stop_id']] = $routeTrip['time'];
}
}
?>
<?php
echo $this->Html->scriptBlock('
var rows = '.json_encode($rows).';
var columns = '.json_encode($columns).';
var options = { rowHeight:21,
defaultColumnWidth:100,
editable:true,
enableAddRow:true,
enableCellNavigation:true,
asyncEditorLoading:false,
autoHeight:true,
autoEdit:true
};
slickgrid = new Slick.Grid($("#scheduleTable"), rows, columns, options);
slickgrid.setSelectionModel(new Slick.CellSelectionModel());
slickgrid.updateRowCount();
slickgrid.render();
');
?>
The $rows and $columns are correctly formatted, and each column has an "editor" attribute with "Slick.Editors.Text" as its value.
Help?
I have also got this error initially when i started working with slickgrid.
The error is because you have specified the editor as string and not as a class.
So, remove the double quotes in "editor" => "Slick.Editors.Text" and give as "editor" => Slick.Editors.Text
This solved the error for me. Hope this solution will solve yours too.
Include the slick.editors.js file.
Also, make sure that the editor is being specified as a class, not as a string (I'm not familiar with PHP, so it's not obvious to me from the source code, but I suspect that's the case).

PHP - If null value

I have the following coding:
<div class="product-top-icons">
<div class="energy-rating-1"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_one');?>.jpg"></div>
<div class="energy-rating-2"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_two');?>.jpg"></div>
<div class="energy-rating-3"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_three');?>.jpg"></div>
<div class="guarantee-icon"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('warranty');?>.jpg"></div>
</div>
I would like to add an if statement in there basically to say the following:
If the value in the 'energy_rating_one' attribute is null then don't display the division energy-rating-1, if the 'energy_rating_two' attribute is null then don't display the div energy-rating-2 and so on...
something like this:
<?php if($_product->getAttributeText('energy_rating_one') !== null): ?>
<div class="energy-rating-1"><img src="http://www.justhome.co/skin/frontend/default/just2011/images/assets/<?php echo $_product->getAttributeText('energy_rating_one');?>.jpg"></div>
<?php endif; ?>
and that for all the others as well.
<?php
function echoIfExists($argument) {
$val = $_product->getAttributeText($argument);
if($val)
/*your echo stmt*/
}
echoIfExists('energy_rating_one');
/** continue here*/
?>
Make it easy on yourself. Just change the css class rules from energy-rating-1 to energy-rating-one and echo the variable you already have i.e energy-rating-one
You have a function "int_to_words" to transform "int" value into a text value in this post:
http://www.php.net/manual/en/function.strval.php#41988
After that, you just have to iterate into all values
for(i = 0; i < 100; i++) {
$item = 'energy_rating_'.int_to_words($i);
if($_product->getAttributeText($item) != null){
echo "<div class=\"energy_rating_$i\"><img src=\"http://www.justhome.co/skin/frontend/default/just2011/images/assets/".$_product->getAttributeText($item).".jpg\"></div>";
}
}
Look at short hand if statement:
http://www.scottklarr.com/topic/76/ternary-php-short-hand-ifelse-statement/
$total==1 ? "is 1 item" :
"are ".($total == 0 ? "no items" : "$total items"

Categories