I have a problem with an mysql query, I need to extract all data from my table and use him as another sql query.
This is the code I am using:
<?php
function toateMhz() {
require ('SQL.php');
$sql = "SELECT DISTINCT(performanta_cpu) FROM modele ORDER BY CAST(performanta_cpu AS UNSIGNED) DESC";
foreach ($dbh->query($sql) as $linie)
{
$mhz[] = $linie['performanta_cpu'];
}
if(isset($mhz['1']))
{
$mhz1 = "$mhz[0] OR ";
}
else $mhz['0'];
if(isset($mhz['2']))
{
$mhz2 = "$mhz[1] OR ";
}
else $mhz['1'];
if(isset($mhz['3']))
{
$mhz3 = "$mhz[2] OR ";
}
else $mhz['2'];
if(isset($mhz['4']))
{
$mhz4 = "$mhz[3] OR ";
}
else $mhz['3'];
if(isset($mhz['5']))
{
$mhz5 = "$mhz[4] OR ";
}
else $mhz['4'];
if(isset($mhz['6']))
{
$mhz6 = "$mhz[5] OR ";
}
else $mhz['5'];
if(isset($mhz['7']))
{
$mhz7 = "$mhz[6] OR ";
}
else $mhz['6'];
if(isset($mhz['8']))
{
$mhz8 = "$mhz[7] OR ";
}
else $mhz['7'];
if(isset($mhz['9']))
{
$mhz9 = "$mhz[8] OR ";
}
else $mhz['8'];
if(isset($mhz['10']))
{
$mhz10 = "$mhz[9] OR ";
}
else $mhz['9'];
if(isset($mhz['11']))
{
$mhz11 = "$mhz[10] OR ";
}
else $mhz['10'];
if(isset($mhz['12']))
{
$mhz12 = "$mhz[11] OR ";
}
else $mhz['11'];
if(isset($mhz['13']))
{
$mhz13 = "$mhz[12] OR ";
}
else $mhz['12'];
if(isset($mhz['14']))
{
$mhz14 = "$mhz[13] OR ";
}
else $mhz['13'];
if(isset($mhz['15']))
{
$mhz14 = "$mhz[14] OR ";
}
else $mhz['14'];
$frecvente = "$mhz1 $mhz2 $mhz3 $mhz4 $mhz5 $mhz6 $mhz7 $mhz8 $mhz9 $mhz10 $mhz11 $mhz12 $mhz13 $mhz14";
return $frecvente;
}
echo toateMhz();
?>
And this is the result from code:
2000 OR 1600 OR 1500 OR 1400 OR 1000 OR 800 OR
But the correct result is 2000 OR 1600 OR 1500 OR 1400 OR 1000 OR 800 OR 200
Last word must not be OR
Not quite sure but this might do the trick
foreach ($dbh->query($sql) as $linie) {
// append value of this record to the array $mhz
$mhz[] = $linie['performanta_cpu'];
}
// return the concatenation of all elements in $mhz with ' OR ' as "glue" between elements
return join(' OR ', $mhz);
join($s, $arr) is an alias of implode($s, $arr) which concatenates all (string) elements of the given array $arr and putting $s "between" the elements. E.g.
$x = array('a','b', 'c');
echo join(' - ', $x);
prints a - b - c
Use implode to join your array values into a string :
function toateMhz() {
require ('SQL.php');
$sql = "SELECT DISTINCT(performanta_cpu) FROM modele ORDER BY CAST(performanta_cpu AS UNSIGNED) DESC";
foreach ($dbh->query($sql) as $linie)
{
$mhz[] = $linie['performanta_cpu'];
}
return implode(" OR ", $mzh);
}
echo toateMhz();
Related
I am working with mysql and Rest Api in php,I want to use "orderby" according to condition (if "filterId"==3 or 4). In other words:
If I pass filterId='3' then query should be like SELECT ......ORDER by p.sp ASC/DESC
If I pass filterId='4' then query should be like SELECT ......ORDER by m.merchantName ASC/DESC
If I pass both parameters,filterId='3' and filterId='4' then query should be like SELECT ......ORDER by m.merchantName,p.sp ASC/DESC
If not pass filterId='3' or filterId='4' then orderby not apply/append
How can I do this? Here is my current code:
if(isset($_GET["Filter"]))
{
$filter=trim($_GET['Filter']);
$data=json_decode($filter);
// echo "<pre>";print_R($data);
foreach($data as $dt)
{
foreach($dt as $d)
{
//echo $d->filter_id;
if($d->filter_id=="1")
{
}
if($d->filter_id=="3")
{
}
}
}
Try this.
$query = "Select * from .... ORDER BY";
if(isset($_GET["Filter"]))
{
$filter=trim($_GET['Filter']);
$data=json_decode($filter);
// echo "<pre>";print_R($data);
foreach($data as $dt)
{
foreach($dt as $d)
{
//echo $d->filter_id;
if($d->filter_id=="1")
{
$query .='ORDER BY p.asp';
}
else if($d->filter_id=="3")
{
$query .='ORDER BY m.merchantName';
}
else
{
break;
}
}
}
For your third condition, you might have to use in_array_all() as below:
function in_array_all($lookfor, $mainarray) {
return empty(array_diff($lookfor, $mainarray));
}
//Try this
$query = 'select * from ...';
$order_by_clause = '';
if(isset($_GET["Filter"]))
{
$filter=trim($_GET['Filter']);
$data=json_decode($filter);
foreach($data as $dt)
{
foreach($dt as $d)
{
//echo $d->filter_id;
if($d->filter_id=="3")
{
$order_by_clause = 'ORDER BY p.sp ASC';
}
else if($d->filter_id=="4")
{
$order_by_clause = 'ORDER BY m.merchantName';
}
else if(($d->filter_id=="3") && if($d->filter_id=="4"))
{
$order_by_clause = 'ORDER BY m.merchantName,p.sp';
}
else if(!(($d->filter_id!="3") || if($d->filter_id!="4"))
{
$order_by_clause = '';
}
}
}
}
$query .= $order_by_clause;
I need two print the same rows which retrieved from the db, in two different locations in same php file.
I know it is better to have a function. It tried, It doesn't work properly.
I am using the below code print the said rows/
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
I need to print exactly the same code twice in two different location in a php file.
I think it is not a good idea to retrieve data twice from the server by pasting the above code twice.
Is there any way to recall or reprint the retrieved data in second place which I need to print.
Edit : Or else, if someone can help me to convert this to a function?
I converted this into a function. It prints only first row.
Edit 2 : Following is my function
unction getGroup($dbconn)
{
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($dbconn ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$groupData = "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
return $groupData;
You can store the records coming from the DB in array and use a custom function to render the element
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
$options = []; //store in an array
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$options[$groups['profile_gid']] = $groups['profile_gname'];
}
}
Now you can use the $options array many times in your page
echo renderElement($options);
function renderElement($ops){
$html = '';
foreach($ops as $k => $v){
$html .= "<option value={$k}>{$v}</option>";
}
return $html;
}
If the data is same for both places, put the entire string into variable, then echo it on those two places.
instead of
echo "here\n";
echo "there\n";
do
$output = "here\n";
$output .= "there\n";
then somewhere
echo $output
on two places....
Values are being stored in groups array, hence you can use a foreach loop elsewhere to get values from the array:
$groups = array();
$get_g = "SELECT * FROM profile_groups";
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
echo "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
echo '<option value="">Empty - No Groups!!</option>';
}
// use here
foreach($groups as $group)
{
echo $group['profile_gid'] . " ". $group['profile_gname'] . "<br/>";
}
class ProfileGroups
{
public $profile_groups_options;
public static function get_profile_groups_options($condb) {
$get_g = "SELECT * FROM profile_groups";
if( isset( $this->profile_groups_options ) && $this->profile_groups_options != '') {
return $this->profile_groups_options;
}
$get_gr = mysqli_query($condb ,$get_g);
if(mysqli_num_rows($get_gr) > 0)
{
while($groups = mysqli_fetch_array($get_gr))
{
$this->profile_groups_options .= "<option value='".$groups['profile_gid']."'>".$groups['profile_gname']."</option>";
}
}
else
{
$this->profile_groups_options .= '<option value="">Empty - No Groups!!</option>';
}
return $this->profile_groups_options;
}
}
ProfileGroups::get_profile_groups_options($condb);
Is here any possible to write single return for both $strValues and $strThumbImages i need to return $strValues for every time but returning $strThumbImages is just when it is available..
function doSelectBranchRecords($objArray,$ImageId = NULL)
{
global $global_config;
$strWhereClause = '';
if ($objArray['frmNameSearch']) {
$strWhereClause.= " AND A.branch_ident = '".$objArray['frmNameSearch']."' ";
}
if ($objArray['frmLoanSearch']) {
$strWhereClause.= " AND A.loan_ident = '".$objArray['frmLoanSearch']."' ";
}
if ($objArray['frmBeneficiarySearch']) {
$strWhereClause.= " AND A.beneficiary_idents = '".$objArray['frmBeneficiarySearch']."' ";
}
if ($objArray['frmDateSearch']) {
$strDate = explode("-", $objArray['frmDateSearch']);
$strAccountstarted = $strDate[2].'-'.$strDate[1].'-'.$strDate[0];
$strWhereClause.= " AND A.account_started = '".$strAccountstarted."' ";
/*printArray($strWhereClause); exit;*/
}
if ($ImageId) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
return $strThumbImages;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
return $strValues;
}
A php function can't return more than one variable. You could get both results from the function by returning an array with either one or two keys in it, then do a check in your calling code to see what has been set. So the end of your function becomes:
...
}
$output = array();
if ($ImageId) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
$output['thumbImages'] = $strThumbImages;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
$output['strValues'] = $strValues;
return $output;
}
#Simon and #Suchit are right in that you cannot return more than one variable. But in php it is very straightforwarded to return a list with multiple items like so:
function getXYZ(){
return array(4,5,6);
}
list($x,$y,$z) = getXYZ();
So in your case this could look like so:
$strThumbImages = null;
if ($ImageId) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
return array($strValues, $strThumbImages);
As above #Simon Brahan said you can not return more than one variable.
so you can use array with different keys.but you should also check if $ImageId is set and not null.
if (isset($ImageId) && !is_null($ImageId)) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
$output['thumbImages'] = $strThumbImages;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
$output['strValues'] = $strValues;
return $output;
I have a database with lots of courses in for example, breakfast_cereal, breakfast_toast, lunch_salad, lunch_main etc etc
Im using this to put the data they enter into a variable containing there results, for example:
breakfast_toast = Wholemeal;Brown;50/50;
and
breakfast_hotdrinks = Tea;Coffee;Milk;
This is the script im using to gather that information:
if(!empty($_POST['toast_selection'])) {
foreach($_POST['toast_selection'] as $toast) {
$toast = trim($toast);
if(!empty($toast)) {
$toastchoices .= "$toast;";
}
}
}
This works absolutely fine, But i have about a lot of entries to collect and if they add more to the database i want them to automatically gather.
I had a go at trying to think of a way but i just can't figure it out, This is what i tried:
All the inputs are called the same as the $course_menuname, for example breakfast_cereal[]
$query = "SELECT * FROM course";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$course_menuname = $row['course_menuname']; #E.G breakfast_cereal, breakfast_toast, lunch_main
$course_item = $row['course_jsname']; #E.G cereal, toast, jacketpotato
$postResults = $_POST[''.$course_menuname .''];
if(!empty($postResults)) {
echo $postResults."<br />";
foreach($postResults as $course_item) {
$course_item = trim($course_item);
if(!empty($course_item)) {
$course_item1 .= "$course_item;";
}
}
}
echo $course_item1."<br />";
}
This is what the end result should look for
if(!empty($_POST['toast'])) {
foreach($_POST['toast'] as $toast) {
$toast = trim($toast);
if(!empty($toast)) {
$toastchoices .= "$toast;";
}
}
}
if(!empty($_POST['toastextra_selection'])) {
#Gather Toast EXTRAs Choices
foreach($_POST['toastextra_selection'] as $toastextra) {
$toastextra = trim($toastextra);
if(!empty($toastextra)) {
$toastextrachoices .= "$toastextra;";
}
}
}
if(!empty($_POST['toastextra_selection'])) {
#Gather Cold Drinks Choices
foreach($_POST['colddrinks_selection'] as $colddrinks) {
$colddrinks = trim($colddrinks);
if(!empty($colddrinks)) {
$colddrinkschoices .= "$colddrinks;";
}
}
}
if(!empty($_POST['hotdrinks_selection'])) {
#Gather Hot Drinks Choices
foreach($_POST['hotdrinks_selection'] as $hotdrinks) {
$hotdrinks = trim($hotdrinks);
if(!empty($hotdrinks)) {
$hotdrinkschoices .= "$hotdrinks;";
}
}
}
First of all you should not use the mysql_* functions anymore. These functions are marked as deprecated. Alternativly you can use PDO or the mysqli_* functions.
I guess group change is what you need. Let 's start with a simple example.
try {
$data = array();
$pdo = new PDO(...);
foreach ($pdo->query("SELECT * FROM course") as $row) {
if (!isset($data[$row['course_menuname'])) {
$data[$row['course_menuname']] = array();
}
if (!empty($row['course_item'] && in_array($row['course_item'], $_POST[$row['course_menuname'])) {
$data[$row['course_menuname'][] = $row['course_item'];
}
}
} catch (PDOException $e) {
// error handling
}
// Output all choices by menuname
foreach ($data as $key => $value) {
echo "Choices for " . $key . "\n";
echo implode(";", $value) . "\n";
}
Problem:
I am trying to delete all sublevels of a category by using a class. Currently I can only make it delete two sublevels, not three.
The database table:
CREATE TABLE betyg_category (
CID int(11) NOT NULL AUTO_INCREMENT,
Item varchar(100) NOT NULL,
Parent int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (CID)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
The PHP class:
<?php
class ItemTree
{
var $itemlist = array();
function ItemTree($query)
{
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
while ($row = mysql_fetch_assoc($result))
{
$this->itemlist[$row['CID']] = array(
'name' => $row['Name'],
'parent' => $row['Parent']
);
}
}
function get_tree($parent, $with_parent=0)
{
$item_tree = array();
if ($with_parent == 1 && $parent != 0)
{
$item_tree[$parent]['name'] = $this->itemlist[$parent]['name'];
$item_tree[$parent]['parent'] = $this->itemlist[$parent]['parent'];
$item_tree[$parent]['child'] = $this->get_tree($parent);
return $item_tree;
}
foreach ($this->itemlist as $key => $val)
{
if ($val['parent'] == $parent)
{
$item_tree[$key]['name'] = $val['name'];
$item_tree[$key]['parent'] = $val['parent'];
$item_tree[$key]['child'] = $this->get_tree($key);
}
}
return $item_tree;
}
function make_optionlist ($id, $class='', $delimiter='/')
{
$option_list = '';
$item_tree = $this->get_tree(0);
$options = $this->make_options($item_tree, '', $delimiter);
if (!is_array($id))
{
$id = array($id);
}
foreach($options as $row)
{
list($index, $text) = $row;
$selected = in_array($index, $id) ? ' selected="selected"' : '';
$option_list .= "<option value=\"$index\" class=\"$class\"$selected>$text</option>\n";
}
return $option_list;
}
function make_options ($item_tree, $before, $delimiter='/')
{
$before .= empty($before) ? '' : $delimiter;
$options = array();
foreach ($item_tree as $key => $val)
{
$options[] = array($key, '- '.$before.$val['name']);
if (!empty($val['child'])) {
$options = array_merge($options, $this->make_options($val['child'], $before.$val['name'], $delimiter));
}
}
return $options;
}
function get_navlinks ($navid, $tpl, $startlink='', $delimiter=' ยป ')
{
// $tpl typ: {name}
$search = array('{id}', '{name}');
$navlink = array();
while (isset($this->itemlist[$navid]))
{
$replace = array($navid, $this->itemlist[$navid]['name']);
$navlink[] = str_replace($search, $replace, $tpl);
$navid = $this->itemlist[$navid]['parent'];
}
if (!empty($startlink))
{
$navlink[] = str_replace($search, array(0, $startlink), $tpl);
}
$navlink = array_reverse($navlink);
return implode($delimiter, $navlink);
}
function show_tree ($parent=0, $tpl='%s', $ul_class='', $li_class='')
{
$item_tree = $this->get_tree($parent);
return $this->get_node($item_tree, $parent, $tpl, $ul_class, $li_class);
}
function get_node ($item_tree, $parent, $tpl, $ul_class, $li_class)
{
// $tpl typ: {name}
$search = array('{id}', '{name}');
$output = "\n<ul class=\"$ul_class\">\n";
foreach ($item_tree as $id => $item)
{
$replace = array($id, $item['name']);
$output .= "<li class=\"$li_class\">".str_replace($search, $replace, $tpl);
$output .= !empty($item['child']) ? "<br />".$this->get_node ($item['child'], $id, $tpl, $ul_class, $li_class) : '';
$output .= "</li>\n";
}
return $output . "</ul>\n";
}
function get_id_in_node ($id)
{
$id_list = array($id);
if (isset($this->itemlist[$id]))
{
foreach ($this->itemlist as $key => $row)
{
if ($row['parent'] == $id)
{
if (!empty($row['child']))
{
$id_list = array_merge($id_list, get_id_in_node($key));
} else
{
$id_list[] = $key;
}
}
}
}
return $id_list;
}
function get_parent ($id)
{
return isset($this->itemlist[$id]) ? $this->itemlist[$id]['parent'] : false;
}
function get_item_name ($id)
{
return isset($this->itemlist[$id]) ? $this->itemlist[$id]['name'] : false;
}
}
?>
Scenario:
Say you have the following structure in a :
Literature
-- Integration of sources
---- Test 1
It will result in the following in the database table:
When I try to delete this sublevel, it will leave the last sublevel in the database while it should delete it. The result will be:
The PHP code:
//Check if delete button is set
if (isset($_POST['submit-deletecategory']))
{
//Get $_POST variables for category id
$CategoryParent = intval($_POST['CategoryList']);
//Check if category is selected
if ($CategoryParent != "#")
{
//Get parent category and subsequent child categories
$query = "SELECT CID, Item AS Name, Parent FROM " . TB_CATEGORY . " ORDER BY Name";
$items = new ItemTree($query);
if ($items->get_item_name($_POST['CategoryList']) !== false)
{
//Build up erase list
$CategoryErase = $items->get_id_in_node($CategoryParent);
$CategoryEraseList = implode(", ", $CategoryErase);
}
else
{
$CategoryEraseList = 0;
}
//Remove categories from database
$query = "DELETE FROM " . TB_CATEGORY . " WHERE CID IN ($CategoryEraseList)";
$result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());
//Return a confirmation notice
header("Location: settings.php");
exit;
}
}
Thank you in advance for any guidance I can get to solve the issue.
Here is a way to do it : use a recursive function, which will first look for the leaf item (the deepest in your tree). You remove children first, then the parent. And for each child, you remove child's children first, etc...
deleteSub(1);
function deleteSub($cat_id) {
$request = "SELECT * FROM ". TB_CATEGORY ." WHERE Parent = ".$cat_id;
$results = mysql_query($request);
while($child = mysql_fetch_array($results))
{
deleteSub($child["CID"]);
}
$request = "DELETE FROM ". TB_CATEGORY ." WHERE CID = ".$cat_id;
return mysql_query($request);
}
A better way could be use this kind of recursive function to store CIDs in an array, then make a single DELETE request, but I think you'll be able to adapt this code.
I'm not going to read or try to understand the entire code, but it seems to me you need some sort of recursion function. What I basicly would do is create a function that goes up in the hierachy and one that goes down.
Note: It has been a while since i've written anything in procedural mysql, so please check if the mysql_num_rows(),mysql_fetch_array and so on is written in the correct manner
EDIT: I've just noticed you only wanted a downwards deletion and therefore zessx's answer is more valid
<?php
function recursiveParent($id) {
$sql = 'SELECT parent FROM betyg_category WHERE CID=' . $id;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result,MYSQLI_ASSOC)) {
recursiveParent($r['parent']);
}
}
$sql = 'DELETE FROM betyg_category WHERE CID=' . $id;
mysql_query($sql);
}
function recursiveChild($parent) {
$sql = 'SELECT CID FROM betyg_category WHERE parent=' . $parent;
$result = mysql_query($sql);
if(mysql_num_rows($result) > 0) {
while($r = mysql_fetch_array($result,MYSQLI_ASSOC)) {
recursiveChild($r['CID']);
}
}
$sql = 'DELETE FROM betyg_category WHERE parent=' . $parent;
mysql_query($sql);
}
function delete($id) {
recursiveParent($id);
recursiveChild($id);
}
?>
This is my way to do. instead of recursive the query to run, i get all the child's id first then only run query. here the code refer:-
First, defined a variable called $delete_node_list as array. (to store all node id that need to be delete)
function delete_child_nodes($node_id)
{
$childs_node = $this->edirectory_model->get_child_nodes($node_id);
if(!empty($childs_node))
{
foreach($childs_node as $node)
{
$this->delete_child_nodes($node['id']);
}
}
$this->delete_node_list[] = $node_id;
}
in mysql..
$sql = 'DELETE FROM betyg_category WHERE CID IN '.$this->delete_node_list;
mysql_query($sql);