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"' ?> />
If you’re concerned about clutter then you can use short open tags. like so:
Additionally, you can use
isset()oris_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:
Then later you can modify your
ifstatement to something like this:Otherwise, if your checkboxes are all numbered sequentially, then use a loop: