Yo!
I have this code. Basically it should return a list of avaiable jobs based on the location and what position user looked for...
I am trying to figure out how to shorten the execution time for this...
$cities = $this->getChildren($location->city_id);
foreach ($cities as $child) {
$grandChildren = $this->getGrandChildren($child, false);
foreach ($grandChildren as $grandChild) {
$cities[] = $grandChild;
}
}
$menu = $this->getPositionChildren($postion);
$menu[] = $postion->menu_id;
// var_dump($cities);
foreach ($cities as $city) {
$city_id = (!empty($city) ? "AND FIND_IN_SET('{$city}', town)" : '');
foreach ($menu as $key) {
$menu_id = (!empty($key) ? " AND FIND_IN_SET('{$key}', category_id)" : '');
$queries[] = "SELECT ponuka_id as id FROM " . TABLE_PREFIX . "ponuky WHERE 1 {$city_id} {$menu_id} AND `published` = '1' ORDER BY `date` DESC";
foreach ($queries as $query) {
$result = mysql_query($query);
if (!$result) {
return false;
}
while ($row = mysql_fetch_object($result)) {
if (!in_array($row->id, $this->_joblist, true)) {
$this->_joblist[] = $row->id;
}
}
}
}
The code above can easily run over 1000 queries and as you can imagine, this takes time... Long time... any tips on how to improve this?
The code now looks like this and by taking the query out of the loop it runs a lot faster...
$cities = $this->getChildren($location->city_id);
foreach ($cities as $child) {
$grandChildren = $this->getGrandChildren($child, false);
foreach ($grandChildren as $grandChild) {
$cities[] = $grandChild;
}
}
// $cities = $this->getCityInfoFromArray($cities);
$menu = $this->getPositionChildren($postion);
$menu[] = $postion->menu_id;
var_dump($cities);
foreach ($cities as $city) {
$city_id = (!empty($city) ? "AND FIND_IN_SET('{$city}', town)" : '');
foreach ($menu as $key) {
$menu_id = (!empty($key) ? " AND FIND_IN_SET('{$key}', category_id)" : '');
$queries[] = "SELECT ponuka_id as id FROM " . TABLE_PREFIX . "ponuky WHERE 1 {$city_id} {$menu_id} AND `published` = '1' ORDER BY `date` DESC";
}
}
foreach ($queries as $query) {
$result = mysql_query($query);
if (!$result) {
return false;
}
while ($row = mysql_fetch_object($result)) {
if (!in_array($row->id, $this->_joblist, true)) {
$this->_joblist[] = $row->id;
}
}
}
You can try it like this. Check if this works for you.
$city_id = ""; $city_id = "";
foreach ($cities as $city) {
$city_id .= (!empty($city) ? " AND FIND_IN_SET('{$city}', town)" : '');
foreach ($menu as $key) {
$menu_id .= (!empty($key) ? " AND FIND_IN_SET('{$key}', category_id)" : '');
}
}
$result = mysql_query("SELECT ponuka_id as id FROM " . TABLE_PREFIX . "ponuky WHERE 1 {$city_id} {$menu_id} AND `published` = '1' ORDER BY `date` DESC");
Related
I need to output the response from the database in XML. So far I have gotten it to output this:
The outermost tag needs to match the name of the action query, it'll either be <courses> or <students>.
Here is my code:
<?php
require_once('./database.php');
if (isset($_GET['format'])) {
$format = filter_var($_GET['format']);
}
if (isset($_GET['action'])) {
$action = filter_var($_GET['action'], FILTER_SANITIZE_STRING);
$tableName = "sk_$action";
}
$query = "SELECT * FROM $tableName";
if (isset($_GET['course'])) {
$course = filter_input(INPUT_GET, 'course');
$query .= " WHERE courseID = :course";
}
function arrayToXml($arr, $i = 1, $flag = false)
{
$sp = "";
for ($j = 0; $j <= $i; $j++) {
$sp .= " ";
}
foreach ($arr as $key => $val) {
echo "$sp<" . $key . ">";
if ($i == 1) echo "\n";
if (is_array($val)) {
if (!$flag) {
echo "\n";
}
arrayToXml($val, $i + 5);
echo "$sp</" . $key . ">\n";
} else {
echo "$val" . "</" . $key . ">\n";
}
}
}
$statement = $db->prepare($query);
$statement->bindValue(':course', $course);
$statement->execute();
$response = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
if ($format == 'json') {
echo json_encode($response);
}
if ($format == 'xml') {
arrayToXml($response, 1, true);
}
I'm pretty new to PHP and have never worked with XML. All help is appreciated. Thanks.
function arrayToXml($arr, $collectionTag, $singleTag) {
$collection = new SimpleXMLElement("<$collectionTag/>");
foreach ($arr as $row) {
$element = $root->addChild($singleTag);
foreach ($row as $tag => $value) {
$element->addChild($tag, $value);
}
}
return $collection;
}
$courses = arrayToXml($response, 'courses', 'course');
echo $courses->asXML();
Tested with PHP 7.1.23. Output:
<?xml version="1.0"?>
<courses>
<course><courseID>cs601</courseID><courseName>Web Application Development</courseName></course>
<course><courseId>cs602</courseId><courseName>Server-Side Application Development</courseName></course>
<course><courseId>cs701</courseId><courseName>Rich Internet Application Development</courseName></course>
</courses>
(I added newlines because by default it doesn't add any.)
I want to transform this PHP function.. that should return JSON data.
<?php
$query = 'SELECT * FROM `' . mix_player::table() . '` a';
if (isset($_GET['cat']) || isset($_GET['order']))
if (isset($_GET['cat'])) {
$query .= ' INNER JOIN `' . mix_player::table_cat_rel() . '` b '
. "ON (a.`id` = b.`idtrack`) WHERE `idcat` = '" . $wpdb->escape($_GET['cat']) . "'";
$random = $wpdb->get_var('SELECT `random`, `order` FROM `' . mix_player::table_categories() . "` WHERE `id` = '"
. $wpdb->escape($_GET['cat']) . "'");
if (!$random)
$order = $wpdb->get_var(NULL, 1);
}
if (isset($_GET['order']))
$order = $_GET['order'];
if ($order != '') {
if (isset($_GET['cat']))
$query .= ' AND ';
else
$query .= ' WHERE ';
$tracks = mix_player::order_list($query, $order);
}
} else {
$random = '0';
}
$query .= ' ORDER BY `id` ASC';
if (isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A))) {
// option "shuffle = true" not always working into mix. Do it our own way...
if ($random == 1) { // shuffle tracks?
list($usec, $sec) = explode(' ', microtime());
mt_srand((float) $sec + ((float) $usec * 100000));
$nrows = count($tracks);
for ($i = 0; $i < $nrows; $i++) {
$j = mt_rand(0, $nrows - 1); // pick j at random
$row = $tracks[$i]; // swap i, j
$tracks[$i] = $tracks[$j];
$tracks[$j] = $row;
}
}
foreach ($tracks as $row) {
$artist = (mix_player::entities($row['artist']));
echo ($artist);
$title = (mix_player::entities($row['title']));
echo ($title);
$url =(xspf_player::entities($row['url']));
echo ($url);
}
}
?>
to display like this json file :
{"title":"title", "artist":"artist","media":"url media.mp3","color":"#56B0E8" },
Can you help me?
Thanks in advance.
You can simply create an array and populate it with your desired values, then return it as JSON:
function tracks2json( $tracks )
{
$retval = array();
foreach( $tracks as $row )
{
$array = array();
$array['artist'] = mix_player::entities($row['artist']);
$array['title'] = mix_player::entities($row['title']);
$array['media'] = 'url '.xspf_player::entities($row['url']);
$array['color'] = '#56B0E8';
$retval[] = $array;
}
return json_encode( $retval );
}
if( isset($tracks) || ($tracks = $wpdb->get_results($query, ARRAY_A)) )
{
// Your MySQL routine here
$json = tracks2json( $tracks );
}
echo json_encode(array("title"=>$title,"artist"=>$artist,"url"=>$url));
I am hoping to convert some of my basic settings like my navigation, mysql settings (host, username, password) to SQLite but it seems from something I read this morning there is no equivalent for the command PDO::FETCH_ASSOC. Is there another way for me to do this query that would be compatible with SQLite?
<?
$sql = "SELECT * FROM menu_items WHERE status = 'ACTIVE' ORDER BY menu_parent_id ASC, sortorder ASC, menu_item_name ASC";
$query = $db->query($sql);
$menu_items = array();
while($data = $query->fetch(PDO::FETCH_ASSOC)) {
if($data['menu_parent_id'] == 0) {
$menu_items[$data['menu_item_id']] = array();
$menu_items[$data['menu_item_id']]['menu_item_id'] = $data['menu_item_id'];
$menu_items[$data['menu_item_id']]['name'] = $data['menu_item_name'];
$menu_items[$data['menu_item_id']]['url'] = $data['menu_url'];
$menu_items[$data['menu_item_id']]['fontawesome'] = $data['fontawesome'];
$menu_items[$data['menu_item_id']]['children'] = array();
} else if($data['menu_parent_id'] != 0) {
$tmp = array();
$tmp['menu_item_id'] = $data['menu_item_id'];
$tmp['name'] = $data['menu_item_name'];
$tmp['url'] = $data['menu_url'];
$tmp['fontawesome'] = $data['fontawesome'];
array_push($menu_items[$data['menu_parent_id']]['children'],$tmp);
unset($tmp);
}
}
function create_list($arr)
{
$html = "";
foreach($arr as $key => $value) {
//Here the menu item has children
if(count($value['children']) > 0) {
$html .= '<!-- PARENT --> <li class="mm-dropdown"> <i class="menu-icon fa '. $value['fontawesome']. '"></i><span class="mm-text">'.$value['name'].'</span>
<ul>';
// Here it is the child
foreach($value['children'] AS $child) {
$html .= '
<!-- child --><li><i class="menu-icon fa '. $child['fontawesome']. '"></i>'.$child['name'].'</li>';
}
$html .= ' </ul>
';
} else{
$html .= ' <a class="menu-icon fa '.$value['fontawesome'].'" id="'.$value['menu_item_id'].'" >'.$value['name'].'</a>';
}
}
return $html;
}
?>
So your $query is SQLite3Result ??
try this way then:
while($data = $query->fetchArray(SQLITE3_ASSOC)) {
I have a problem with building multi level select box. I have category table with structure: id, parent_id, name. If parent_id = 0 it is top level. i don't know level depth, so it could be 2,3-5 levels.
How i can build it with on query "SELECT * FROM cats"
Result suppose to look like
<select>
<option>cat_name</option>
<option>--cat_name_l1</option>
<option>--cat_name_l1</option>
<option>----cat_name_l2</option>
<option>----cat_name_l2</option>
<option>cat_name</option>
</select>
Can You help me?
function _buildTree($data, $idParent, $indentSymbol, $level)
{
$cat = array();
foreach($data as $row){
if($row['parent_id'] == $idParent){
if($indentSymbol AND $level > 0){
$symbols = array_fill(0, $level, $indentSymbol);
$cat[$row['id']] = implode('', $symbols) . $row['name'];
}else{
$cat[$row['id']] = $row['name'];
}
$cat = $cat + _buildTree($data, $row['id'], $indentSymbol, $level++);
}
}
return $cat;
}
$result = mysql_query("SELECT * FROM cats");
$data = array();
while($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
$select = '<select>';
foreach(_buildTree($data, 0, '-', 0) as $key=>$option){
$select .= '<option value=' . $key . '>' . $option . '</option>';
}
$select .= '</select>';
Try this for generating the required dropdown:
$result=mysql_query("SELECT * FROM cats");
$opt='<select>';
while($row=mysql_fetch_array($result))
{
$cat[$row['id']][0]=$row['parent_id'];
$cat[$row['id']][1]=$row['name'];
}
foreach($cat as $ct)
{
$level=0;
$temp=$ct;
while($temp[0]!=0)
{
$temp=$cat[$temp[0]];
$level++;
}
$opt.="<option>";
for($i=0;$i<$level;$i++)
{
$opt.="--";
}
$opt.=$ct[1];
$opt.="</option>";
}
$opt.="</select>";
Then, you can use this as:
echo $opt;
I have a function which performs a foreach loop on an array from a database.
see foreach ($teamarray AS $key => $value){$teamgo .= $value[1]." ".$value[2]."<br/>";
Problem is, sometimes there may be no data set, which throws an error when the loop hits that field.
How can i catch/suppress this error?
function GetUnsubmitted($coach){
$push .= "<div id=unsubmitted><h2>Check which event/teams you want to process and click submit</h2>";
$push .= "<form action=\"submit.php\" method=POST>";
$result = mysql_query("SELECT * FROM `ptable` WHERE coach = '$_SESSION[username]' AND status = '1' ORDER BY status ASC") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$teampre = $row['team'];
$eventpre = $row['event'];
$statuspre = $row['status'];
$eventarray = DecodeEvent($eventpre);
$event = $eventarray[0];
$cat = $eventarray[1];
$subcat = $eventarray[2];
$division = $eventarray[3];
$type = $eventarray[4];
$teamarray = DecodeTeam($teampre);
$price = GetPrice($type, "nat");
$teamcount = count($teamarray);
$total = $price * $teamcount;
$teamgo = "";
foreach ($teamarray AS $key => $value){
$teamgo .= $value[1]." ".$value[2]."<br/>";
if($statuspre == "1"){
$statuscolor = "#FFCC99";
$statusmsg = "unsubmitted <a href=delsub.php?id=$id onClick=\"return confirm('Are you sure you want to delete this submission?');\"><img src=images/del.png border=0 />";
} elseif($statuspre == "2"){
$statuscolor = "#FFCC66";
$statusmsg = "awaiting confirmation";
} elseif($statuspre == "3"){
$statuscolor = "#66CC66";
$statusmsg = "confirmed";
}
}
$push .= "<div id=submission><div id=event style=\"background-color:$statuscolor;\"><h1>$event</h1><span id=status>$statusmsg</span></div><div id=subinfo><span id=dropdown><img src=images/expand.png border=0></span><h2>$cat >> $subcat >> $division >> $type</h2> <div id=team style=\"display:none;\">$teamgo<br />$price - $total<div id=controls></div></div></div></div>";
$pid .= $id;
$rtotal .= "$total,";
}
$stotal = explode(",", $rtotal);
$gtotal = array_sum($stotal);
$push .= "<div style=\"text-align:right;\"><div id=total>Total - <em>$gtotal</em></div><br><input type=image src=images/paynow.png alt=\"Pay Now\"></form> <a href=submit2.php?$pid&$pidarray><img src=images/mailfax.png width=138px height=41px border=0></a></div></div>";
return $push;
}
If possible id like it to say "no team selected" and stop.
You can write so:
foreach ((array)$teamarray as $key => $value) {
$teamgo .= $value[1] . " " . $value[2] . "<br/>";
//...
}
foreach expects array. So the really correct way is to ensure that you deal with array before try to iterate, like this:
if (is_array($teamarray) && count($teamarray)) {
foreach ((array)$teamarray as $key => $value) {
$teamgo .= $value[1] . " " . $value[2] . "<br/>";
//...
}
}
You also can check is_iterable since PHP 7.1.
if ($array) {
foreach ($array as $k => $v) {
...
}
} else {
echo 'No team selected';
// exit from loop
}
Your exit from loop will be a "return", or a "break n" (n is the levels to break for) or continue... it depends on your logic.
if ($value !== null && count($value) >= 3) {
$teamgo .= $value[1] . $value[2]
}
<insert puzzled smiley here>
foreach($row AS $key => $value) {
if ($value) {
$row[$key] = stripslashes($value);
}
}
And:
foreach ($teamarray AS $key => $value){
if ($value && sizeof($value) > 2) {
$teamgo .= $value[1] . $value[2]
}
}
Is this it?
Just do a test if $teamarray actually is an array:
if (is_array($teamarray)) {
foreach ($teamarray as $key => $value) {
// …
}
}
Or you could do:
$teamarray = isset($teamarray) ? $teamarray : array();
Just prior to the loop in a nice tidy line, and it would ensure that you have the variable set to an empty array which would cause it to skip the foreach().