i want to create HTML element with PHP functions. in this section i have select function to create select tag. for values i want to check if array is simple my function create simple select otherwise create optgroup for options.
my create select method :
$tag->select( 'myselect',
array(
'0'=>'please choose','1'=>'111','2'=>'222','3'=>'333'
) ,
'2',
array(
'class'=>'myClass','style'=>'width:10%;'
)
);
other use:
$tag->select( 'myselect',
array( 'one'=>
array('0'=>'please choose','1'=>'111','2'=>'222','3'=>'333'),
'two'=>
array('0'=>'please choose','1'=>'111','2'=>'222','3'=>'333')
) ,
'2',
array(
'class'=>'myClass','style'=>'width:10%;'
)
) ;
now in below function i want to check if array into array exist function must be create select group;
public function select( $name, $values, $default='0', $attributs=[]){
$options = [];
$selected = '';
echo count($values);
if ( count($values) == 1){
foreach ($values as $value => $title) {
if ( $value === $default ) $selected="selected='selected'";
$options[] = "<option value = '$value' $selected>" . $title . '</option>'.PHP_EOL ;
$selected = '';
}
}
else{
foreach ($values as $key => $value) {
$options[] = "<optgroup label='$key'>";
foreach ($value as $selectValue => $title) {
$options[] = "<option value = '$selectValue'>" . $title . '</option>'.PHP_EOL ;
}
$options[] = "</optgroup>";
}
}
$selectTag = '<select ' . $this->setAttribute($attributs) . '>'.PHP_EOL;
return $selectTag . implode($options, ' ') . '</select>';
}
this function is not correct. how to resolve that? thanks.
Try this (hopefully helps you)
public function select( $name, $values, $default='0', $attributs=[]){
$options = [];
$selected = '';
echo count($values);
foreach ($values as $key => $value) {
if (!is_array($value)) {
if ( $key === $default ) $selected="selected='selected'";
$options[] = "<option value = '$key' $selected>" . $value . '</option>'.PHP_EOL ;
$selected = '';
}
else {
$options[] = "<optgroup label='$key'>";
foreach ($value as $selectValue => $title) {
$options[] = "<option value = '$selectValue'>" . $title . '</option>'.PHP_EOL ;
}
$options[] = "</optgroup>";
}
}
$selectTag = '<select ' . $this->setAttribute($attributs) . '>'.PHP_EOL;
return $selectTag . implode($options, ' ') . '</select>';
}
Related
How can i remove "dato" from $this->v ? And still have it in the $sql string.
OUTPUT (var_dump($this->v)):
array (size=4)
':kategori' => string 'Youstube' (length=8)
':link' => string 'http://urls' (length=11)
':navn' => string 'Rss feeds' (length=9)
':dato' => string 'NOW()' (length=5)
OUTPUT (echo $sql)
UPDATE rss_kategori SET kategori = :kategori, link = :link, navn = :navn, dato = NOW()
CODE:
$classVars = get_class_vars(get_class($this));
$sql .= "UPDATE {$this->table} SET ";
foreach ($classVars as $key => $value) {
if ($key == 'v' || $key == 'db' || $key == 'id' || $key == 'table' || $key ==
'table_id') {
continue;
}
$keys = "";
$values = "";
$keys .= $key;
if ($this->$key == 'NOW()') {
$values .= $this->$key . ",";
} else {
$values .= ":" . $key . ",";
}
$this->v[":" . $key] = $this->$key;
$sql .= "{$keys} = " . $values . " ";
}
$sql = substr($sql, 0, -2) . " WHERE {$this->table_id} = '{$this->id}'";
Please try this:
$key = ':dato';
$arr = $this->v;
if (array_key_exists($key, $this->v) {
unset($arr[$key]);
$this->v = $arr;
}
Try using unset() function.
unset($this->v['dato']);
I am trying to build a search query based on the input from users, but I am having problems with the AND and WHERE keywords. Here is the code:
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array();
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
$where[] = $key . ' = ' . $value;
}
}
}
The output looks like this:
Array
(
[0] => gender = masculine
[1] => level = low
[2] => status = future
)
If no option is selected, it defaults to 'all' and it is excluded from the $where[].
I need to achieve this, or anything similar:
Array
(
[0] => WHERE gender = masculine
[1] => AND level = low
[2] => AND status = future
)
The WHERE must be appended only if one or more options have been selected and the AND must be appended only if two or more options have been selected.
In the code I am using I have 9 search inputs. To keep it clear I only displayed three in the snippet. Can you please help me figure this out?
Try this:I think you need the whereClause in string not in array,here you can choose any one from two and remove the other one.
<?php
$where=array();$flag=0;// use flag to identify the where/and
$whereClause="";
$criteria = array('gender' => "masculine", 'level' => "low", 'status' => "future");
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($flag == 0){
$where[] = " WHERE " .$key . ' = ' . $value;//if you need array
$whereClause='WHERE '.$key . ' = "' . $value.'"';//if you need string
}else{
$where[] = " AND " .$key . ' = ' . $value;
$whereClause .=' AND '.$key . ' = "' . $value.'"';
}
$flag++;
}
}
echo "<pre>";
print_r($where);
echo "</pre>";
echo $whereClause;
?>
You can do this :
$query = 'SELECT * FROM candidate ';
$where='';
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($where=='')
$where='WHERE '.$key . ' = ' . $value;
else
$where.=' AND '.$key . ' = ' . $value;
}
}
$query.=$where; //final query
You can use simple switch statement too
<?
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array();
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value)
{
if ($value !== 'all')
{
switch ($key)
{
case 1:
{
$query = " WHERE " .$key . ' = ' . $value;
break;
}
case 2:
{
$query = " AND " .$key . ' = ' . $value;
break;
}
case 3:
{
$query = " AND " .$key . ' = ' . $value;
break;
}
}
$where[] = $query;
}
}
}
You need to put one incrementer ($inc) and then put the conditions as:
$inc=1;
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
if($inc==1){
$where[] = 'Where '.$key . ' = ' . $value.'';
}else{
$where[] = 'AND '.$key . ' = ' . $value.'';
}
$inc++;
}
}
In My view there is one more clean way of achiving this:
if (isset($_POST['submitBtn'])) {
$gender = $_POST['gender'];
$level = $_POST['level'];
$status = $_POST['status'];
$query = 'SELECT * FROM candidate ';
$where = array("Where 1=1");
$criteria = array('gender' => $gender, 'level' => $level, 'status' => $status);
foreach ($criteria as $key => $value) {
if ($value !== 'all') {
$where[] = 'AND '.$key . ' = ' . $value.' ';
}
}
}
I am new at php, so please be kind.
I am building a script that gets the number of facebook likes from facebook pages.
Then it sorts them, I have found a way to add the page's profile picture using css, however the only class I am able to add is a url. how can I give each thumbnail it's own class, which I can then apply the css to?
here is my code:
function array_sort($array, $on, $order=SORT_ASC)
{
$new_array = array();
$sortable_array = array();
if (count($array) > 0) {
foreach ($array as $k => $v) {
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
if ($k2 == $on) {
$sortable_array[$k] = $v2;
}
}
} else {
$sortable_array[$k] = $v;
}
}
switch ($order) {
case SORT_ASC:
asort($sortable_array);
break;
case SORT_DESC:
arsort($sortable_array);
break;
}
foreach ($sortable_array as $k => $v) {
$new_array[$k] = $array[$k];
}
}
return $new_array;
}
function getLikes($arr){
$urls = "";
// Add urls to check for likes
for($i = 0;$i < count($arr);$i++) {
if($urls != "") $urls .= ",https://www.facebook.com/";
$urls .= $arr[$i];
}
// Retreive info from Facebook
$xml = simplexml_load_file("http://api.facebook.com/restserver.php?method=links.getStats&urls=https://www.facebook.com/" . $urls);
$likes = array();
// Loop through the result and populate an array with the likes
for ($i = 0;$i < count($arr);$i++) {
$url = $xml->link_stat[$i]->url;
$counts = (int)$xml->link_stat[$i]->like_count;
$likes[] = array('likes' => $counts,'url' => $url);number_format(1000, 0, '.', ',');
}
return $likes;
}
$array = array("kylieminogue","SiaMusic","iggyazalea");
$likes = getLikes($array);
$likes = array_sort($likes, 'likes', SORT_DESC);
foreach ($likes as $key => $val) {
$final = number_format($val['likes'], 0, '.', ',');
echo "<li class='facebook'><div class='fb-page'><div class='rank'>" . $key . "</div>" . "<div class='thumb " . $val['url'] . "'><div class='link'>" . $val['url'] . "</div></div>" . "<div class='likes'>" . $final . "</div></div></li><br />";
}
If you do this in getLikes(), inside the second loop:
$likes[] = array(
'likes' => $counts,
'url' => $url,
// create a hopefully unique class name
'class' => strtolower($arr[$i]) . '-' . $i
);
// After this you call number_format without receiving its value, why?
Then in the HTML you change
"<div class='thumb " . $val['url'] . "
for
"<div class='thumb " . $val['class'] . "
Is this what you mean?
i have this function for print categories in dropdown menu.
function Cat_Parent(){
$result = mysql_query("SELECT id, name, parent FROM cats ORDER BY name");
$items = array();
while($row = mysql_fetch_array($result))
{ $items[] = array('id' => $row['id'], 'label' => $row['name'], 'parent' => $row['parent']);
}
// Loop using references to build a tree
$childs = array();
foreach($items as &$item)
{
$childs[$item['parent']][] = &$item;
}
unset($item);
foreach($items as &$item)
{
if(isset($childs[$item['id']]))
{
$item['children'] = $childs[$item['id']];
}
}
// We now have a tree with 'children' key set on each node that has children
$tree = $childs[0];
// Prepare a template and recursive closure (note reference on &$print)
$tpl = '<option name="parent[]" value="%s">%s %s</option>';
$print = function($item, $indent = '') use (&$print, $tpl)
{
echo sprintf($tpl, $item['id'], $indent, $item['label']) . "\n";
if(isset($item['children']))
{
foreach($item['children'] as $child)
{
$print($child, $indent . '|--');
}
}
};
echo '<select name="parent"><option name="parent[]" value="0">------</option>';
// Call the function for each top-level node
foreach($tree as $row)
{
$print($row);
}
echo '</select>';
}
this worked but i need to selected value/id when$_GET['id'] = value Like This:
<select>
<option value="1">cat1</option>
<option selected value="2">cat2</option> <-- THIS Print Selected
<option value="3">subcat2</option>
<option value="4">cat3</option>
<option value="5">cat4</option>
</select>
in example $_GET['id'] = 2 , so selected option with value 2. how to select this?
Try this code in your script. Defines a variable with "selected" value if the value from GET is the same as the option value.
Notice the $sel variable.
// Prepare a template and recursive closure (note reference on &$print)
$tpl = '<option name="parent[]"%s value="%s">%s %s</option>';
$print = function($item, $indent = '') use (&$print, $tpl)
{
$sel = (isset($_GET['id']) && $_GET['id'] == $item['id']) ? 'selected' : ' ';
echo sprintf($tpl, $sel, $item['id'], $indent, $item['label']) . "\n";
if(isset($item['children']))
{
foreach($item['children'] as $child)
{
$print($child, $indent . '|--');
}
}
};
You're going to want to compare your values in the template like so:
$tpl = '<option name="parent[]" %s value="%s">%s %s</option>';
$print = function($item, $indent = '') use (&$print, $tpl)
{
echo sprintf($tpl, $item['id'] == 2 ? 'selected="selected"' : '', $item['id'], $indent, $item['label']) . "\n";
if(isset($item['children']))
{
foreach($item['children'] as $child)
{
$print($child, $indent . '|--');
}
}
};
$resultUpdate = Nemesis::select("*", $table, "id = '{$id}'");
if (!$resultUpdate) {
self::show_error(QUERY_ERROR);
} elseif ($resultUpdate->num_rows > 0) {
$out .= '<div class="form-desc">' . $formDesc . '</div>';
} else {
self::show_error(QUERY_EMPTY);
}
$array = array_values($array);
print_r($array);
$out .= '<form action="' . $_SERVER['PHP_SELF'] . '?id=' . $id . '&table=' . $table . '" method="post" class="form-horizontal" ' . $formAppend . '>';
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
$out .= generateInputField($fieldname, $value);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
$out .= generateTextarea($fieldname, $value, $cke);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
$out .= generateImgField($fieldname, $value);
}
}
}
$arr = array("last_modified"=>"input", "published"=>"input", "content"=>"textarea");
echo $automate->createArrayForm('projects', 'update', 'Some form desc', '178514825', $arr, true);
Right now all fields are outputting in every foreach when only inputs should output in the generateInputField section for example. I know this is because I need to check if the fieldtype (input, textarea) key matches with one of the values marked as input or textarea for values of the $fieldname. But I am not sure how.
I am pretty sure I have to filter the array so only values with input go into a separate array like arrayInput in which I can use as the second argument in in_array.
If I understand you and your code correctly...
This code
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $array)) {
will always return true for all your rows thats why you are getting your current output.
Instead you should be doing this:
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if ($fieldname == 'input') {
$out .= generateInputField($fieldname, $value);
} elseif($fieldname == 'textarea') {
$out .= generateTextarea($fieldname, $value, $cke);
} elseif ($fieldname == 'img') {
$out .= generateImgField($fieldname, $value);
}
else{ $out = $out;}
}
}
With alot of help from stackers...
/**
* Create Form With Array
*
* Creates a form based on an array. If $do == update, we match fieldnames with values
*
* #param string $table name of database table
* #param string $do whether the form is an insert or update
* #param string $formDesc form description to be echoed
* #param array $array associative array of type (keys), and fieldnames (values)
* #param bool $markFields whether or not to add headers for inputs, textareas .etc during insert
* #param bool $formBrackets whether or not to prepend and append form brackets
* #return $out html form
*
*/
public function createArrayForm($table, $do, $formDesc = '', $id, $array, $markFields = false, $formBrackets = true) {
if (!isset($table) && !isset($do)) {
self::show_error('One or more parameters are missing in ' . __FUNCTION__);
} elseif ($table == 'update' && !isset($id)) {
self::show_error('For this form to be built, and ID must be set. Missing parameter `ID` in ' . __FUNCTION__);
}
if (!is_array($array)) {
self::show_error('For this form to be built, an array must be given. Missing parameter `array` in ' . __FUNCTION__);
}
$result = array();
// create two dimensional array to preserve keys that
// otherwise would be lost with array_flip
foreach($array as $k => $v) {
if (array_key_exists($v, $result)) {
$result[$v][] = $k;
} else {
$result[$v] = array($k);
}
}
// make sure we do not have any duplicates
$result = super_unique($result);
// we just need the array_values for matching with in_array
// however we do not want to run array_values on null
// so we check to see if the $result is a valid array first
// if not, we just output a blank array so in_array doesn't complain
$arrayInput = is_array($result['input']) ? array_values($result['input']) : array();
$arrayTextarea = is_array($result['textarea']) ? array_values($result['textarea']) : array();
$arrayImages = is_array($result['images']) ? array_values($result['images']) : array();
$out = $formBrackets == true ? '<form action="' . $_SERVER['PHP_SELF'] . '?id=' . $id . '&table=' . $table . '" method="post" class="form-horizontal" ' . $formAppend . '>' : NULL;
if($do == 'insert') {
$out .= isset($formDesc) ? '<div class="form-desc">' . $formDesc . '</div>' : NULL;
$out .= $markFields && in_array('input', $array) ? '<h3>Input Fields</h3>' : NULL;
foreach ($arrayInput as $fieldname) {
$out .= generateInputField($fieldname);
}
$out .= $markFields && in_array('textarea', $array) ? '<h3>Content Fields</h3>' : NULL;
foreach ($arrayTextarea as $fieldname) {
$out .= generateTextarea($fieldname, $cke);
}
$out .= $markFields && in_array('image', $array) ? '<h3>Images Fields</h3>' : NULL;
foreach ($arrayImages as $fieldname) {
$out .= generateImgField($fieldname);
}
} elseif ($do == 'update') {
$resultUpdate = Nemesis::select("*", $table, "id = '{$id}'");
if (!$resultUpdate) {
self::show_error(QUERY_ERROR);
} elseif ($resultUpdate->num_rows > 0) {
$out .= isset($formDesc) ? '<div class="form-desc">' . $formDesc . '</div>' : NULL;
} else {
self::show_error(QUERY_EMPTY);
}
while ($row = $resultUpdate->fetch_assoc()) {
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $arrayInput)) {
$out .= generateInputField($fieldname, $value);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $arrayTextarea)) {
$out .= generateTextarea($fieldname, $value, $cke);
}
}
foreach ($row as $fieldname => $value) {
if (in_array($fieldname, $arrayImages)) {
$out .= generateImgField($fieldname, $value);
}
}
}
} else {
self::show_error('Missing array or `do` argument in function ' . __FUNCTION__);
}
$out .= form_hidden('user_data', '1');
$out .= form_hidden('id', $do == 'update' ? $id : self::generateID());
$out .= $formBrackets == true ? form_close() : NULL;
return $out;
}
Usage:
$arr = array("last_modified"=>"input", "published"=>"input", "project_content"=>"textarea", "project_content"=>"textarea");
echo $automate->createArrayForm('projects', 'insert', 'Some form desc', '123', $arr, true);
echo $automate->createArrayForm('projects', 'update', 'Some form desc', '178514825', $arr, true);