Populate select with database entries the oo way - php

My database table
TABLE `dog_types` (
`dog_type_id` int(11)
`dog_type_name` varchar(64)
I would like to make the dog_type_name entries available in a select menu.
My attempt
Class Sell {
public static function getAllDogTypes()
{
$database = DatabaseFactory::getFactory()->getConnection();
$sql = "SELECT dog_type_name FROM dog_types";
$query = $database->prepare($sql);
$query->execute(array());
// fetchAll() is the PDO method that gets all result rows
return $query->fetchAll();
}
public static function viewSelect($name = "select") {
$html = "<select name='$name'>\n";
foreach ($query as $key => $val) {
$html .= "<option value='$key'>$val</option>\n";
}
$html .= "</select>\n";
return $html;
}
}
<?php echo Sell::viewSelect(); ?>
My output
<select>
Notice: Undefined variable: query
Warning: Invalid argument supplied for foreach()
</select>
The two functions work on their own. I just cannot figure out how to put them together.
As you already guessed I am super new to all of this and would highly appreciate any kind of help!
With noob's suggestions my code looks like this:
public static function getAllDogTypes()
{
$database = DatabaseFactory::getFactory()->getConnection();
$sql = "SELECT * FROM dog_types";
$query = $database->prepare($sql);
$query->execute(array());
// fetchAll() is the PDO method that gets all result rows
return $query->fetchAll();
}
public static function viewSelect($name = "select") {
$query=Sell::getAllDogTypes();
$html = "<select name='$name'>\n";
foreach ($query as $key => $val) {
$html .= "<option value='$key'>$val</option>\n";
}
$html .= "</select>\n";
return $html;
}
<?php echo Sell::viewSelect(); ?>
var_dump on query shows the database entries:
Dog_type: array(8) { [0]=> object(stdClass)#8 (2) { ["dog_type_id"]=> string(1) "1" ["dog_type_name"]=> string(13) "Affenpinscher" } [1]=> object(stdClass)#9 (2) { ["dog_type_id"]=> string(1) "2" ["dog_type_name"]=> string(12) "Afghan Hound" } [2]=> object(stdClass)#10 (2) { ["dog_type_id"]=> string(1) "3" ["dog_type_name"]=> string(4) "Aidi" } [3]=> object(stdClass)#11 (2) { ["dog_type_id"]=> string(1) "4" ["dog_type_name"]=> string(16) "Airedale Terrier" } [4]=> object(stdClass)#12 (2) { ["dog_type_id"]=> string(1) "5" ["dog_type_name"]=> string(6) "Akbash" } [5]=> object(stdClass)#13 (2) { ["dog_type_id"]=> string(1) "6" ["dog_type_name"]=> string(5) "Akita" } [6]=> object(stdClass)#14 (2) { ["dog_type_id"]=> string(1) "7" ["dog_type_name"]=> string(13) "Alano Espanol" } [7]=> object(stdClass)#15 (2) { ["dog_type_id"]=> string(1) "8" ["dog_type_name"]=> string(16) "Alaskan Klee Kai" } }
The error messages
Notice: Undefined variable: query
Catchable fatal error: Object of class stdClass could not be converted to string

add this line to at the beginning of second function:
$query=Sell::getAllDogTypes(); //get the value of $query from getAlldogTypes function which is present in this class.
$query returns array of objects, so you need a nested foreach loop
$html = "<select name='$name'>\n";
foreach ($query as $obj) {
foreach ($obj as $key=>$val)
$html .= "<option value='$key'>$val</option>\n";
}
}
$html .= "</select>\n";
return $html;
}

first of all change
public static function viewSelect($name = "select",$query="") {
$sql = "SELECT dog_type_id,dog_type_name FROM dog_types";
Because you should pass dog_type_id in options values.
First Call this
<?php $query=Self::getAllDogTypes(); ?>
Then call
<?php echo Self::viewSelect($query); ?>

Related

PHP Problem Array to string conversion using FetchAll

I have recently started studying PHP and I'm using Zend Framework v1.12.
I can't print the elements obtained by using FetchAll().
$stmt = $db->query('SELECT * FROM team');
$obj = $stmt->fetchAll();
foreach ($obj as $value) {
echo $value;
}
This is the notice (repeated x7):
Notice: Array to string conversion
Using var_dump I have this:
array(7) {
[0]=> array(2) {["id_team"]=> string(1) "1" ["nameteam"]=> string(10) "Ac Picchia" }
[1]=> array(2) { ["id_team"]=> string(1) "2" ["nameteam"]=> string(4) "test" }
[2]=> array(2) { ["id_team"]=> string(1) "3" ["nameteam"]=> string(4) "ciao" }
[3]=> array(2) { ["id_team"]=> string(1) "4" ["nameteam"]=> string(2) "oi" }
[4]=> array(2) { ["id_team"]=> string(1) "5" ["nameteam"]=> string(3) "xtz" }
[5]=> array(2) { ["id_team"]=> string(1) "6" ["nameteam"]=> string(3) "123" }
[6]=> array(2) { ["id_team"]=> string(1) "7" ["nameteam"]=> string(1) "x" } }
Teh object returned by the FetchAll is a Array of Arrays. So when you do the foreach and try to print every object in the array you got that error.
To fix it you should do something like:
$stmt = $db->query('SELECT * FROM team');
//I renamed this variable to make the code more readable.
$teams = $stmt->fetchAll();
foreach ($teams as $team) {
print_r($team); //This will print the array
}
I found the solution, even if it was a trivial problem, I write my solution to the problem maybe it will help someone.
$stmt = $db->query('SELECT * FROM team');
$obj = $stmt->fetchAll();
foreach ($obj as $value) {
echo $value['id_team'] , $value['nometeam'];
}
use loop like this :
$stmt = $db->query('SELECT * FROM team');
$obj = $stmt->fetchAll();
foreach ($obj as $key => $value) {
echo $value['id_team'].','. $value['nometeam'];
}

Unable to iterate an array in a PHP foreach loop

My request PHP file elaborates some Ajax POST data:
POST data
data[0][id]:359
data[0][position]:1
data[1][id]:321
data[1][position]:2
data[2][id]:354
data[2][position]:3
Request.php
if(isset($_POST['data'])) {
if(isset($_SESSION['username']) && isset($_SESSION['password'])) {
$verify = $loggedIn->verify();
if($verify['username']) {
$Profile = new Profile();
$Profile->db = $db;
//Call my function
$messages = $Profile->setOrder($_POST['data']);
}
}
}
Profile.php
function setOrder($post) {
var_dump($post);
foreach($post as $item)
{
return "Area ID ".$item["id"]." and person located ".$item["position"]."<br />";
}
}
My function returns nothing and the dump of $post is as below
array(3) {
[0]=>
array(2) {
["id"]=>
string(3) "359"
["position"]=>
string(1) "1"
}
[1]=>
array(2) {
["id"]=>
string(3) "321"
["position"]=>
string(1) "2"
}
[2]=>
array(2) {
["id"]=>
string(3) "354"
["position"]=>
string(1) "3"
}
}
Inside my function I can dump correctly something like var_dump($post[0]["id"]); so why my foreach loop is empty?
It is because you are using return inside loop. It will terminate the loop after first iteration. You need to do something like this.
$return = null;
foreach($data as $item)
{
$return .= "Area ID ".$item["id"]." and person located ".$item["position"]."<br />";
}
return $return;

PHP - get unique values in while loop

I have the following code:-
if( $featured_query->have_posts() ): $property_increment = 0;
while( $featured_query->have_posts() ) : $featured_query->the_post();
$town = get_field('house_town');
$a = array($town);
$b = array_unique($a);
sort($b);
var_dump($b);
$property_increment++; endwhile; ?>
<?php endif; wp_reset_query();
var_dump(b) shows:-
array(1) { [0]=> string(10) "Nottingham" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(11) "Mountsorrel" } array(1) { [0]=> string(12) "Loughborough" } array(1) { [0]=> string(12) "Loughborough" }
var_dump($town) shows:-
string(10) "Nottingham" string(9) "Leicester" string(9) "Leicester" string(11) "Mountsorrel" string(12) "Loughborough" string(12) "Loughborough"
var_dump($a) shows:-
array(1) { [0]=> string(10) "Nottingham" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(9) "Leicester" } array(1) { [0]=> string(11) "Mountsorrel" } array(1) { [0]=> string(12) "Loughborough" } array(1) { [0]=> string(12) "Loughborough" }
What I want to do is get the unique vales of $town and output them into a select option:-
<select>
<option value="Leicester">Leicester</option>';
<option value="Loughborough">Loughborough</option>';
<option value="Mountsorrel">Mountsorrel</option>';
</select>';
In alpha as above, any help would be much appreciated.
#collect all get_field('house_town') in while
$collect[] = get_field('house_town');
#then do the work
$html = implode('',
array_map(
function($a){
return "<option value='{$a}'>{$a}</option>";
},
array_unique($collect)
)
);
Your array needs to be un-nested with array_column before you sort it and make it unique. So after you initialised $a, continue like this:
$b = array_unique(array_column($a, 0));
sort($b);
and then make the HTML:
$html = "";
foreach($b as $town) {
$html .= "<option value='$town'>$town</option>";
}
echo "<select>$html</select>";
If you don't have array_column, then you can use this replacement:
function array_column($arr, $column) {
$res = array();
foreach ($arr as $el) {
$res[] = $el[$column];
}
return $res;
}
Here's a summary of Chris G's comment and trincot's code snippet for generating the HTML code.
Note: for testing purposes I have created the $town array manually here. Replace it by your statement $town = get_field('house_town');
<?php
$town = array(
"Nottingham",
"Leicester",
"Leicester",
"Mountsorrel",
"Loughborough",
"Loughborough"
);
// $town = get_field('house_town');
$html = "";
$town = array_unique($town);
sort($town);
foreach($town as $xtown) {
$html .= "<option value='$xtown'>$xtown</option>";
}
echo "<select>$html</select>";
?>
Basic/ General unique usage in while/ foreach loop
// refer to
$a = array($town); // $a in while/ foreach loop
if(current($a) != next($a)) {
// do your query here // get required unique here
}
// Note: caring and sharing

I got Undefined index: reading recursively an array

I'm going to be crazy, I can't understand what is the problem.
I have this array:
array(2) {
[0]=>
array(4) {
["id"]=>
string(1) "1"
["parent_id"]=>
NULL
["name"]=>
string(7) "Events"
["children"]=>
array(2) {
[0]=>
array(3) {
["id"]=>
string(1) "2"
["parent_id"]=>
string(1) "1"
["name"]=>
string(9) "Concerts"
}
}
}
[1]=>
array(4) {
["id"]=>
string(1) "4"
["parent_id"]=>
NULL
["name"]=>
string(7) "Music"
["children"]=>
array(3) {
[0]=>
array(3) {
["id"]=>
string(1) "5"
["parent_id"]=>
string(1) "4"
["name"]=>
string(4) "Rock"
}
}
}
}
and I try to print with this recursive function:
public function printTree($tree) {
$result = "";
if(!is_null($tree) && count($tree) > 0) {
$result .= '<ul>';
foreach($tree as $node) {
$result .= '<li>Cat: '.$node['name'];
$subtree = array($node['children']);
$this->printTree($subtree);
$result .= '</li>';
}
$result .= '</ul>';
}
return $result;
}
I get an "Undefined index: name" error.
Do I need to declare name? how?
Is the array with incorrect syntax?
If I comment the recursive call
$subtree = array($node['children']);
$this->printTree($subtree);,
then $node['name'] isn't undefined and the code works, but of course with only with one level of depth.
SOLVED: (Thanks all guys!)
public function printTree($tree) {
$result = "";
if(is_array($tree) && count($tree) > 0) {
$result .= '<ul>';
foreach($tree as $node) {
$result .= '<li>Cat: '.$node['name'];
if (isset($node['children'])) {
$result .= $this->printTree($node['children']);
}
$result .= '</li>';
}
$result .= '</ul>';
}
return $result;
}
You are pushing $node['children'] into an additional array. That way you are not dealing with the subarray of this node (which has a name later on), but you have another layer of array.
Skip this array layer, remove it.
Also note that !is_null() isn't really a nice check if you then want to use that variable as an array. Check for is_array() instead, because strings and other scalar values will return count>0 as well - they return 1. Only NULL returns count=0.
You will have to append the results returned by the consecutive calls to printTree() for child nodes to the $result.
$result .= $this->printTree($node['children']);
:)
First of all, you want to enclose the $subtree-stuff into an if-condition checking for the existence of the key 'children', because as it is now, you have created an infinite loop of recursive calls to printTree(), but you only want to do this, if the key 'children' exists.
Second, I guess you want to add $result .= in front of $this->printTree($subtree);, otherwise the return value will simply be discarded.
Third, don't do $subtree = array($node['children']);. $node['children'] already is an array, so this adds another level to the array, which makes the recursion break.
So, the final function should look something like this:
public function printTree($tree) {
$result = '';
if(!is_null($tree) && count($tree) > 0) {
$result .= '<ul>';
foreach($tree as $node) {
$result .= '<li>Cat: '.$node['name'];
if (isset($node['children'])) {
$subtree = $node['children'];
$result .= $this->printTree($subtree);
}
$result .= '</li>';
}
$result .= '</ul>';
}
return $result;
}
Edit: Whoops, was too slow there, the others also found the three problems here :)

create php array using simpleXMLobject

I'm trying to get this array ($resdata) with object(SimpleXMLElement) into a php array:
$resdata =
array(59) {
[0]=> ...
[10]=> object(SimpleXMLElement)#294 (28) {
["reservation_id"]=> string(7) "8210614"
["event_id"]=> string(6) "279215"
["space_reservation"]=> array(2) {
[0]=> object(SimpleXMLElement)#344 (9) {
["space_id"]=> string(4) "3760"
["space_name"]=> string(9) "205"
["formal_name"]=> string(33) "Center" }
[1]=> object(SimpleXMLElement)#350 (9) {
["space_id"]=> string(4) "3769"
["space_name"]=> string(9) "207"
["formal_name"]=> string(32) "Right" } } }
}
I've tried:
$res = (array)$resdata;
$reservation = $res['reservation'];
$result = array();
foreach ($reservation as $key => $value){
$res = array($value);
$spid = $res[0]->space_reservation->space_id;
echo $value->event_id."<br />";
echo $spid."<br />";
}
This only outputs the first space_id and I need to get all the space_ids within "space_reservation" array. Not all records will have multiple space_ids. Any help pointing me in the right direction is appreciated. Not sure if I should use xpath but I need to re-write my foreach statement regardless.
I was hoping to be able to literally convert all references to "object(SimpleXMLElement)#_ (#)" to "array(#)"
[10]=> array (28) {
["reservation_id"]=> string(7) "8210614"
["event_id"]=> string(6) "279215"
["space_reservation"]=> array(2) {
[0]=> array (9) {
["space_id"]=> string(4) "3760"
["space_name"]=> string(9) "205"
["formal_name"]=> string(33) "Center" }
[1]=> array (9) {
["space_id"]=> string(4) "3769"
["space_name"]=> string(9) "207"
["formal_name"]=> string(32) "Right" } } }
}
the function in my cakephp 1.3 controller is this:
$xml = simplexml_load_string($string);
$this->data['events']= $xml->children();
$resdata = $this->data['events'];
$this->set('resdata',$resdata);
I think this should do what you are looking for:
foreach ($resdata as $res) {
echo $res->event_id . '<br />';
foreach ($res->space_reservation as $reservation) {
echo $reservation->space_id . '<br />';
}
}
Googled it and found a general solution for any SimpleXMLElement to array conversion:
function xml2array($xml) {
$arr = array();
foreach ($xml as $element) {
$tag = $element->getName();
$e = get_object_vars($element);
if (!empty($e)) {
$arr[$tag] = $element instanceof SimpleXMLElement ? xml2array($element) : $e;
}
else {
$arr[$tag] = trim($element);
}
}
return $arr;
}

Categories