Wordpress format meta_value column to get only option values - php

In wordpress i have created a choices value for custom field like below:
I am trying to get the choices values in magento
field_57bdd83367bb1 is my fieldkey
public function getPostType2()
{
try{
$resource = Mage::getSingleton('core/resource');
$readConnection = $resource->getConnection('new_db');
$query = 'SELECT meta_value FROM ' . $resource->getTableName('wp_postmeta'). ' WHERE meta_key = "field_57bdd83367bb1"';
$results = $readConnection->fetchAll($query);
return $results[0]['meta_value'];
}catch (Exception $e) {
return true;
}
}
in phtml:
$recentpost = Mage::helper('wordpress')->getblogmainbannerpost($bannercheckedblogpost['post_id']);
$posttype= Mage::helper('wordpress')->getPostType2();
$posttype = explode(',',$posttype);
echo 'Post type:';print_r($posttype);
output:
Array ( [0] => a:12:{s:3:"key";s:19:"field_57bdd83367bb1";s:5:"label";s:4:"Type";s:4:"name";s:4:"type";s:4:"type";s:6:"select";s:12:"instructions";s:0:"";s:8:"required";s:1:"0";s:7:"choices";a:7:{s:7:"Article";s:7:"article";s:9:"Blog Post";s:9:"blog_post";s:16:"Artists & Makers";s:16:"artistsandmakers";s:6:"Videos";s:6:"videos";s:12:"In The Press";s:12:"in_the_press";s:14:"Did You Know ?";s:12:"did_you_know";s:14:"Glossary A - Z";s:8:"glossary";}s:13:"default_value";s:39:"blog_post in_the_press did_you_know ";s:10:"allow_null";s:1:"0";s:8:"multiple";s:1:"1";s:17:"conditional_logic";a:3:{s:6:"status";s:1:"0";s:5:"rules";a:1:{i:0;a:2:{s:5:"field";s:4:"null";s:8:"operator";s:2:"==";}}s:8:"allorany";s:3:"all";}s:8:"order_no";i:0;} )
How to properly format the above output so that i can get only Article, Blog Post, Artists & Makers, etc in my drop down
<div class="category-list">
<?php // echo $this->__('All Types') ?>
<select id="blogcat">
<option><?php echo $this->__('Article Type') ?></option>
<option value=""><?php echo $this->__('All Types..') ?></option>
<option value="<?php echo $posttype;?>"> </option>
</select>
</div>

I believe the data format that you see there is a result of the serialize() unserialize() functions of PHP. So you would change return $results[0]['meta_value']; to return (unserialize($results[0]['meta_value']))->choices;

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
}

Codeigniter "group_by" query isn´t working?

I´ve been trying this to work but seems isn´t going anywhere.
The problem is, the data doesn´t show in the View as a combobox it displays this error;
A PHP Error was encountered Severity: Notice Message: Undefined property: stdClass::$Campus Filename: views/energy_search_campus.php Line Number: 28 " >c_name.
So dunno where the problem should be... in the model, view, controller or even the db. Thanks in advance.
Model:
function campus_finder()
{
$this->db->group_by('campus');
$this->db->order_by('faculty', 'asc');
$query = $this->db->get('cpanel_energy');
if($query->num_rows()>0) {
foreach($query->result() as $row) {
$services[$row->id] = $row;
}
return $services;
}
}
View:
<div class="finder">
<div>
<label>Campus</label>
</div>
<select
id="campus"
name="campus"
class="form-control"
>
<option value="">----</option>
<?php foreach($catalogue as $item): ?>
<option value="<?php echo $item->Campus; ?>"
<?php if($campus) echo ($item->campus==$campus)? 'selected' : ''; ?>
><?php echo $item->campus; ?></option>
<?php endforeach; ?>
</select>
</div>
Controller:
function campus_search()
{
$submit = $this->input->post('send');
$campus = $this->input->post('campus');
$year = $this->input->post('year');
if($submit=='goback')
{
redirect("energy/catalogue/");
}
else
{
$data['catalogue'] = $this->model_energy_consumption->campus_finder();
$data['voucher'] = $this->model_energy_consumption->results_campus();
$data['services'] = $this->modelo_energy_consumption->services_catalogue_campus();
$data['campus'] = $campus;
$data['year'] = $year;
DB:
MAINTENANCE_JOB_ITEMS
|----|---------|---------|--------|
| id | account | faculty | campus |
|----|---------|---------|--------|
1 898946 f_name c_name
In the model you are returned $services , but the values are saved in $servicios variable
first call select function to select some record then group them
like this :
$this->db->select('user_id, first_name,last_name');

code igniter - form dropdown selecting correct value from database (state & city using javascript)

I have a similar problem like this one: Code Igniter - form_dropdown selecting correct value from the database, but in this case, i have 2 dropdown, State & City (using JavaScript). The dropdown option for City is repopulated based on what user choose in State dropdown.
For example, when a user choose a State (eg: New York), then the dropdown options for City become only cities in New York (eg: Albany, Amsterdam etc).
After user selects a value, then hits save, its saved to the database.
The problem is, how do i get the dropdown to automatically choose the one thats been selected by the user in the initial stage? I can do it if it's only 1 dropdown option. But in this case, the dropdown for City is repopulated based on what user choosed in State dropdown option.
Controller:
//this one i managed to get it automatically choose the one that's been selected by the user in the initial stage
$username=$this->session->userdata('username');
$data['orgtype'] = $this->m_user->get_orgtype_dropdown($username);
//these two are the problem
$data['state'] = $this->m_user->get_state_dropdown($username);
$data['city'] = $this->m_user->get_city_dropdown($username);
Model:
function get_orgtype_dropdown($username){
$sqlstr="SELECT * FROM a01 WHERE username='$username'";
$hslquery=$this->db->query($sqlstr);
foreach($hslquery->result_array() as $row){
$return[$row['orgtype']] = $row['orgtype'];
}
return $return;
}
function get_state_dropdown($username){
$sqlstr="SELECT * FROM a01 WHERE username='$username'";
$hslquery=$this->db->query($sqlstr);
foreach($hslquery->result_array() as $row){
$return[$row['state']] = $row['state'];
}
return $return;
}
function get_city_dropdown($username){
$sqlstr="SELECT * FROM a01 WHERE username='$username'";
$hslquery=$this->db->query($sqlstr);
foreach($hslquery->result_array() as $row){
$return[$row['city']] = $row['city'];
}
return $return;
}
View:
<?php
$orgtypeOption = array(
'Academic' => 'Academic',
'Professional' => 'Professional',
);
echo form_label("Organization Type : ");
echo form_dropdown('orgtype', $orgtypeOption, $orgtype);
echo br();
echo form_label("State : ");
?>
<select name ="state" id="countrySelect" size="1" onChange="makeSubmenu(this.value)">
<option></option>
<option value="USA" <?php if ($state=="USA") echo 'selected="selected"';?>>USA</option>
<option value="Singapore" <?php if ($state=="Singapore") echo 'selected="selected"';?>>Singapore</option>
<option value="Jawa Timur" <?php if ($state=="Jawa Timur") echo 'selected="selected"';?>>Jawa Timur</option>
<option value="Jawa Barat" <?php if ($state=="Jawa Barat") echo 'selected="selected"';?>>Jawa Barat</option>
</select>
<?php
echo br();
echo form_label("City : ");
?>
<select name="city" id="citySelect" size="1">
<option></option>
</select>
JavaScript:
var citiesByState = {
USA: ["NY","NJ"],
Singapore: ["taas","naas"],
"Jawa Timur": ["Surabaya","Malang"],
"Jawa Barat": ["Bandung","Banjar"]
};
function makeSubmenu(value) {
if(value.length==0) document.getElementById("citySelect").innerHTML = "<option></option>";
else {
var citiesOptions = "";
for(cityId in citiesByState[value]) {
citiesOptions+="<option>"+citiesByState[value][cityId]+"</option>";
}
document.getElementById("citySelect").innerHTML = citiesOptions;
}
}
function displaySelected() {
var country = document.getElementById("countrySelect").value;
var city = document.getElementById("citySelect").value;
alert(country+"\n"+city);
}
function resetSelection() {
document.getElementById("countrySelect").selectedIndex = 0;
document.getElementById("citySelect").selectedIndex = 0;
}
Here's the preview: application preview picture
Help please

Array doesn't appear to be holding data

I have a system where I rearrange navigational items.
It stores the new order in an array and then I use a for loop to go through the array and update the database.
<?php
$apageid = array();
$apagename = array();
$apageorder = array();
$q = "SELECT g.id, g.title, n.order FROM tbl_general g INNER JOIN tbl_navigation n ON n.pageid = g.id WHERE n.type = '$_SESSION[parent]' ORDER BY n.order";
$return = $database->query($q);
while($row=mysql_fetch_assoc($return)){
$apageid[] = $row['id'];
$apagename[] = $row['title'];
$apageorder[] = $row['order'];
}
$count = count($apageid);
$bpageid = array();
$bpageorder = array();
?>
<div class="form-holder">
<?php
//run through each page one at a time and update the order of the menu
mysql_data_seek( $return, 0 ); //reset the pointer to do the same query
$i = 0; //the count for saving the new configuration
while($row=mysql_fetch_assoc($return)){
$id = $row['id'];
$title = $row['title'];
$order = $row['order'];
?>
<div class="form-row">
<div class="form-label">
Page Name
</div>
<div class="form-field">
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
<?php
for($j=0; $j<$count; $j++){
if($apageid[$j] == $id) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageid[$j]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apagename[$j]; ?></option>
<?php
}
?>
</select>
<select class="select-small" name="<?php echo $bpageorder[$i]; ?>">
<?php
for($k=0; $k<$count; $k++){
if($apageorder[$k] == $order) {
$selected = true;
} else {
$selected = false;
}
?>
<option value="<?php echo $apageorder[$k]; ?>" <? echo ($selected == true) ? 'selected="selected"' : ''; ?>><?php echo $apageorder[$k]; ?></option>
<?php
}
?>
</select>
</div>
</div>
<?php
$i++;
}
?>
This first chunk of code is the menu where you can reorder items.
Initially it loads up the current select and allows you to change the ordering.
function reorderChildren($pageid, $pageorder){
global $database;
$count = count($pageid);
//run through each page one at a time and update the order of the menu
for($i=0; $i<$count; $i++){
//set a few variables
$pid = $pageid[$i];
$porder = $pageorder[$i];
echo "pid = $pid porder = $porder";
$q = "UPDATE tbl_navigation SET order = '$porder' WHERE pageid = '$pid' AND type = '$_SESSION[parent]'";
$database->query($q);
}
return 0;
}
The information then ends up being passed here and the problem appears to be the for loop is never executed.
Can anyone see why this would be?
It's not the naming used, I've checked them.
Am I storing information in the arrays correctly?
Can I make it clear that it's $bpageid and $bpageorder that are the arrays carrying the information forward.
Thanks!
Was a simple fix!
The problem was that the select name needed to be just name="bpageid[]" rather than what I listed above. Silly!
You have just initilized $bpageid = array(); at top after first while loop.No value is assigned
after that you using
<select class="select-small" name="<?php echo $bpageid[$i]; ?>">
but no value is in $bpageid[$i] so name of this select box is blank.
It might be problem. check this and do as required.
you could try to construct a json from the options of the select element store it to a hidden field or send ajax request to php script for processing , order could be made from a "weight" value 1,2,3 etc.... sort it with php and loop to display

Reduce number of MySQL Queries and Output Data in Correct Order

My main issue is the number of times I query the database (see below). Also, I would like to check that the current product (optionsToProducts.productID) has options for the current optionName before outputting the select statement! See the final image below to see the blank select box...
I have 8 tables in total, but the 3 that matter are:
optionNames
http://www.grabb.co.uk/stack/001.png
productOptions
http://www.grabb.co.uk/stack/002.png
optionsToProducts
http://www.grabb.co.uk/stack/003.png
<?php
$i=0;
$optionsquery = "SELECT * FROM optionNames WHERE categoryID = ".$categoryID."";
$optionsresult= mysql_query($optionsquery) or die(mysql_error());
while ($optionnames = mysql_fetch_array($optionsresult)) {
$i++;
$optionname = $optionnames["optionName"];
$optionID = $optionnames["optionNamesID"];
//echo $optionname."<br />";
?>
<label for="option<?php echo $i; ?>"><?php echo $optionname; ?></label>
<select name="option<?php echo $i; ?>" id="<?php echo $i; ?>">
<?php
//$optionvalues = "SELECT * FROM (optionsToProducts,productOptions) WHERE optionsToProducts.productID = ".$productID." AND productOptions.optionNamesID = ".$optionID."";
//echo $optionvalues."<br /><br />";
$optionvalues = "SELECT * FROM optionsToProducts WHERE productID = ".$productID."";
$valuesresult= mysql_query($optionvalues) or die(mysql_error());
while ($optionvals = mysql_fetch_array($valuesresult)) {
$valueName = $optionvals["optionValue"];
$valueID = $optionvals["productOptionsID"];
//echo $valueName."<br />";
$optionfinal = "SELECT * FROM productOptions WHERE productOptionsID = ".$valueID." AND optionNamesID = ".$optionID."";
$finalresult= mysql_query($optionfinal) or die(mysql_error());
while ($optionlast = mysql_fetch_array($finalresult)) {
$optionValueName = $optionlast["optionValue"];
$optionValueID = $optionlast["productOptionsID"];
$num_rows = mysql_num_rows($finalresult);
?>
<option value="<?php echo $optionValueID; ?>"><?php echo $optionValueName; ?></option>
<?php
}
}
echo "</select>";
}
?>
final Output:
http://www.grabb.co.uk/stack/004.png
As always, your help is appreciated. Thank you.
Since you tagged this question with the join tag, you probably know you need to write a join query to get what you need.
<?php
$i=0;
$query = "SELECT options.optionName, options.optionNamesID, po.optionValue, po.productOptionsID
FROM optionNames AS options
INNER JOIN productOptions AS po ON po.optionNamesID=options.optionNamesID
INNER JOIN optionsToProducts AS otp ON otp.productOptionsID=po.productOptionsID
WHERE otp.productID=" . (int) $productID
. " AND options.categoryID=" . (int) $categoryID;
$result = mysql_query($query);
if($result) {
$rows = array();
while($row = mysql_fetch_assoc($result) ) {
$rows[] = $row;
}
$i = 0;
$optionId = null;
foreach($rows as $row) {
if($optionId != $row['optionNamesID']) {
$optionId = $row['optionNamesID'];
?>
<label for="option<?php echo $optionId; ?>"><?php echo $row['optionName']; ?></label>
<select name="option<?php echo $optionId; ?>" id="<?php echo $optionId; ?>">
<?php } ?>
<option value="<?php echo $row['productOptionsID']; ?>"><?php echo $row['optionValue']; ?></option>
<?php
//Close select element when the optionNamesID changes or on the last row
if( (isset($rows[$i + 1]) && $rows[$i + 1]['optionNamesID'] != $optionId) ||
!isset($rows[$i + 1]) ) { ?>
</select>
<?php }
$i++;
}
} else {
//Debug query, remove in production
echo mysql_error();
}
?>
I also made some small changes - I use the optionNamesID in the select and label tag names - I don't know how you knew previously which select belonged to which option.
I also assumed that categoryID and productID came from somewhere, since it's not specified in the code.
Pushing all the rows to an array at the beginning is optional, but it makes the code a bit more organized (since you can check ahead in the array to see where to close the select tags).
NOTICE - this code is untested so there could some minor typos. Please make the needed corrections if necessary.

Categories