Reputation: 3195
I'm grabbing a row from the the db in a wordpress plugin using:
$ongoing_event = $wpdb->get_row('select * from wp_em_ongoing where event_id='.$EM_Event->id);
This returns the first row as an object.
Later down I'm I have checkboxes that I want to check if a value exists in the db:
e.g.
<input type="checkbox" value="1" name="week_1"
<?php if ($ongoing_event->week_1==1) echo 'checked="checked"' ?> />
However if the row doesn't exist, I get an error since it can't find a property for an empty object.
I have done the following, but not sure if there's a better way:
<input type="checkbox" value="1" name="week_1"
<?php if ($ongoing_event && $ongoing_event->week_1==1) echo 'checked="checked"' ?> />
I will be having many input fields that I need to check this way.
Edit: The last line I showed already works. However, I have many of these checkboxes throught the page. I was hoping for a way to not have to check if the object is empty for every single occurrence.
What I am getting at, is there a way for me to use the following block of code without getting an error:
<input type="checkbox" value="1" name="week_1"
<?php if ($ongoing_event->week_1) echo 'checked="checked"' ?> />
Upvotes: 0
Views: 130
Reputation: 9866
If you're concerned about clutter then you can use short open tags. like so:
<?= ($ongoing_event && $ongoing_event->week_1 == 1) ? 'checked="checked"' : ''; ?>
Additionally, you can use isset()
or is_object()
to check if something exists or if the variable is an object, respectively.
Another way to avoid clutter would be to set a variable at the top like:
$set = isset($ongoing_event) && is_object($ongoing_event);
Then later you can modify your if
statement to something like this:
<?= ($set && $ongoing_event->week_1 == 1) ? 'checked="checked"' : ''; ?>
Otherwise, if your checkboxes are all numbered sequentially, then use a loop:
<?php for ($ctr = 0; $ctr <= $amountOfWeeks; $ctr++): ?>
<?php $week = 'week_' . $ctr; ?>
<input type="checkbox" value="1" name="<?= $week; ?>"
<?= ($set && $ongoing_event->$week == 1) ? 'checked="checked"' : ''; ?>
<?php endfor; ?>
Upvotes: 1
Reputation: 1104
You can always use the PHP func isset() to determine if it exists before trying to access it:
if (isset($ongoing_event->week) && $ongoing_event->week_1==1)
I would do all this near the top, right after you first make the database call and put it into an easily understandable variable like so:
$weekIsOne = isset($ongoing_event->week) && $ongoing_event->week_1 == 1 ? 'checked = "checked"' : "";
And echo $weekIsOne below inside the input element tag.
Upvotes: 0
Reputation: 1850
I mainly use if(empty($var))
to check if a var is empty (need an expert to confirm if this works for objects in the same way...)
But like others, im not sure if you want to find out why the object is empty, or how to check if its empty...
Upvotes: 0