SELECT and list children and parent - alternative [duplicate] - mysql

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
SELECT and list children and parent
I received this answer from xception:
https://stackoverflow.com/a/12770593/445820
Unfortunately, GROUP_CONCAT isn't the solution for me and the other question is too extended, therefore I am re-asking this question.
I need an alternative to that query with subqueries. Since I'm not good enough with queries, this task is beyond my abilities too.
Help please.
Here is the code:
// Prepare query
$columns = "c.rule_id, c.rule_title, GROUP_CONCAT(r.rule_description ORDER BY r.rule_position ASC SEPARATOR '~sep~') AS rule_desc, ";
$columns .= "GROUP_CONCAT(r.parse_bbcode ORDER BY r.rule_position ASC SEPARATOR '~sep~') AS bbcode, ";
$columns .= "GROUP_CONCAT(r.parse_links ORDER BY r.rule_position ASC SEPARATOR '~sep~') AS links, ";
$columns .= "GROUP_CONCAT(r.parse_smilies ORDER BY r.rule_position ASC SEPARATOR '~sep~') AS smilies";
$sql_array = array(
'SELECT' => $columns,
'FROM' => array(RULES_TABLE => 'c'),
'LEFT_JOIN' => array(
array(
'FROM' => array(RULES_TABLE => 'r'),
'ON' => 'r.parent_id = c.rule_id',
),
),
'WHERE' => 'c.parent_id = 0 AND r.public = 1',
'GROUP_BY' => 'c.rule_id',
'ORDER_BY' => 'c.cat_position',
);
$sql = $db->sql_build_query('SELECT', $sql_array);
$result = $db->sql_query($sql);
$cat_count = 1;
$alpha_count = 'abcdefghijklmnopqrstuvwxyz';
while ($row = $db->sql_fetchrow($result))
{
$template->assign_block_vars('rules', array(
'RULE_CATEGORY' => $row['rule_title'],
'ROW_COUNT' => $cat_count,
));
$rules_ary = explode('~sep~', $row['rule_desc']);
$parse_bbcode = explode('~sep~', $row['bbcode']);
$parse_links = explode('~sep~', $row['links']);
$parse_smilies = explode('~sep~', $row['smilies']);
$counter = 0;
foreach ($rules_ary as $key => $rule)
{
$uid = $bitfield = $options = '';
generate_text_for_storage($rule, $uid, $bitfield, $options, $parse_bbcode[$key], $parse_links[$key], $parse_smilies[$key]);
$template->assign_block_vars('rules.rule', array(
'RULE_DESC' => generate_text_for_display($rule, $uid, $bitfield, $options),
'ALPHA_COUNT' => $alpha_count{$counter},
));
$counter++;
}
$cat_count++;
}
$db->sql_freeresult($result);
Some of the functions might be unknown to you. FYI this is phpBB related code.
Sorry for not adding the code in the first time.

// Prepare query
$columns = "c.rule_id, c.rule_title, r.rule_description AS rule_desc, ";
$columns .= "r.parse_bbcode AS bbcode, ";
$columns .= "r.parse_links AS links, ";
$columns .= "r.parse_smilies AS smilies";
$sql_array = array(
'SELECT' => $columns,
'FROM' => array(RULES_TABLE => 'c'),
'LEFT_JOIN' => array(
array(
'FROM' => array(RULES_TABLE => 'r'),
'ON' => 'r.parent_id = c.rule_id',
),
),
'WHERE' => 'c.parent_id = 0 AND r.public = 1',
'ORDER_BY' => 'c.cat_position',
);
$sql = $db->sql_build_query('SELECT', $sql_array);
$result = $db->sql_query($sql);
$cat_count = 0;
$alpha_count = 'abcdefghijklmnopqrstuvwxyz';
$prev_rule_id = 0;
$r_rule_titles = array();
$rule_id = null;
while ($row = $db->sql_fetchrow($result))
{
if( $rule_id != $row['rule_id'] ) {
$rule_id = $row['rule_id'];
$cat_count++;
$counter = 0;
$template->assign_block_vars('rules', array(
'RULE_CATEGORY' => $row['rule_title'],
'ROW_COUNT' => $cat_count,
));
}
$uid = $bitfield = $options = '';
generate_text_for_storage($row['rule_desc'], $uid, $bitfield, $options, $row['bbcode'], $row['links'], $row['smilies']);
$template->assign_block_vars('rules.rule', array(
'RULE_DESC' => generate_text_for_display($row['rule_desc'], $uid, $bitfield, $options),
'ALPHA_COUNT' => $alpha_count{$counter},
));
$counter++;
}
$db->sql_freeresult($result);

Related

how to update table in silex (PHP micro-framework)?

I have used $sql to insert data into table using below code in model
$sql = "INSERT into $database";
$sql .= ( ;
foreach($data as $key => $value)
{
$sql .= "$key, ";
}
$sql = substr($sql, 0);
$sql .= ) VALUES ( ;
foreach($data as $key => $value)
{
$sql .= "'$value', ";
}
$sql = substr($sql, 0);
$sql .=);
my problem is how to update sametable using silex
according to silex documentation you should use doctrine ORM provider:
$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
'db.options' => array(
'driver' => 'pdo_sqlite',
'path' => __DIR__.'/app.db',
),
));
$app['db']->insert('tablename', array(
'key1' => 'val1',
'key2' => 'val2',
'key3' => 'val3'));

How to Escaping Single Quotes With mysqli_real_escape_string?

My code is like this :
My array of city (echo '<pre>';print_r($city);echo '</pre>';die();) :
Array
(
[0] => Array
(
[CityCode] => 14879
[CityName] => Soldeu
)
[1] => Array
(
[CityCode] => 14881
[CityName] => Ari'nsal
)
[2] => Array
(
[CityCode] => 14882
[CityName] => El Tarter
)
[3] => Array
(
[CityCode] => 14883
[CityName] => Grau Roig
)
[4] => Array
(
[CityCode] => 175198
[CityName] => Llorts
)
)
In city code : 14881, city name : Ari'nsal
It's single quote in string.
I try code like this :
$date = date('Y-m-d H:i:s');
$sql = "INSERT INTO hotel_search_city (nation_code, city_code, city_name, created_at, updated_at) values ";
$valuesArr = array();
foreach($city as $row){
$nation_code = $value->nation_code;
$city_code = $row['CityCode'];
$city_name = mysqli_real_escape_string($row['CityName']);
$created_at = $date;
$updated_at = $date;
$valuesArr[] = "('$nation_code', '$city_code', '$city_name', '$created_at', '$updated_at')";
}
$sql .= implode(',', $valuesArr);
$query = $sql;
$this->db->query($query);
There exist error like this : Message: mysqli_real_escape_string() expects exactly 2 parameters, 1 given....
Any solution to solve my problem?
Thank you very much
$date = date('Y-m-d H:i:s');
$sql = "INSERT INTO hotel_search_city (nation_code, city_code, city_name, created_at, updated_at) values (?, ?, ?, ?, ?)";
foreach ($city as $row) {
$nation_code = $value->nation_code;
$city_code = $row['CityCode'];
$city_name = $row['CityName'];
$created_at = $date;
$updated_at = $date;
$fields = array($nation_code, $city_code, $city_name, $created_at, $updated_at);
$this->db->query($query, $fields);
}
or
$date = date('Y-m-d H:i:s');
foreach ($city as $row) {
$fields = array(
'nation_code' => $value->nation_code,
'city_code' => $row['CityCode'],
'city_name' => $row['CityName'],
'created_at' = $date,
'updated_at' = $date
);
$this->db->insert('hotel_search_city', $fields);
}

JSON data array query

i am using jsonTable to parse the data in to the Google table and it is working fine. now i have a problem to add multiple queries at the same time and display the data only in two columns of array which is already defined. here is my code:
$data = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table = array();
$table['cols'] = array(
array('label' => 'Vehicle', 'type' => 'number'),
array('label' => 'Distance Left', 'type' => 'number')
);
$rows = array();
while ($nt = mysql_fetch_array($data))
{
$temp = array();
$temp[] = array('v' => 'Nextoilchange');
$temp[] = array('v' =>$nt['Nextoilchange']);
// insert the temp array into $rows
$rows[]['c'] = $temp;
}
$table['rows'] = $rows;
$jsonTable = json_encode($table);
my first problem is this i want to add multiple queries in $data and each query gives one result. and my next problem is i want to display the data of multiple queries in above column defined as Distance left. and in vehicle column i want to add static data like above in $temp(1st row). i have searched a lot and i am confused how to do this. Please help me i want to display the table like this:
Vehicle Distance Left
nextoilchange 500
nextfilter 300
nextcheckup 400
I'm not tested this . If not not work try something like this .
<?php
$data[1] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$data[2] = mysql_query("SELECT reg.`oilchange`-SUM(gs.`Distance`) AS Nextoilchange FROM gs INNER JOIN reg ON (gs.`DeviceId`=25) AND (reg.`DeviceId`=25) INNER JOIN LOG ON TIME BETWEEN DATE(log.`lastoilchange`) AND CURDATE()")
or die(mysql_error());
$table[1]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
$table[2]['cols'] = array(array('label' => 'Vehicle', 'type' => 'number'),array('label' => 'Distance Left', 'type' => 'number'));
foreach($table as $key=>$eachtable)
{
$cols = $eachtable['cols'];
while ($nt = mysql_fetch_array($newdata))
{
foreach($cols as $key1=>$each_col)
{
if($each_col['label'] == $nt) //you have match the conditions
{
$row[$key1] = $nt['yourvalue'];
}
else
{
$row[$key1] = $nt['yourvalue1'];
}
$rows[] = $row;
}
}
$table[$key]['rows'] = $rows;
}
$jsonTable = json_encode($table);

Trying to load data from a php file to the jQuery.Gantt

I'm starting in jquery, and I am trying to load the data from a php file to the jQuery.Gantt (http://taitems.github.io/jQuery.Gantt/). But the chart does load.
The script:
$(".gantt").gantt({
source: 'gantt_data_json.php',
navigate: "scroll",
scale: "weeks",
maxScale: "months",
minScale: "days",
itemsPerPage: 10,
....
});
The gantt_data_json.php:
require_once('libs/common.php');
$query ="SELECT * from gantt_table";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$gantt[] = array(
'name' =>$row['name'],
'desc' => $row['desc'],
'values' => array(
'to' => '/Date('.strtotime($row['to']).')/',
'from' => '/Date('.strtotime($row['from']).')/',
'desc' =>$row['desc2'],
'label' => $row['label'],
'customClass' => 'ganttRed'
)
);
}
echo json_encode($gantt);
Please could you help me to solve this issue?
Try this:
$query = "SELECT * from gantt_table";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
$gantt = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$data[] = array(
'name' => $row['name'],
'desc' => $row['desc'],
'values' => array(
array(
'from' => '/Date(' . $row['from'] . ')/',
'to' => '/Date(' . $row['to'] . ')/',
'desc' => $row['desc2'],
'label' => $row['label'],
'customClass' => 'ganttRed',
),
)
);
$gantt[] = $data;
}
echo json_encode($gantt);
its workfine
$json = Array();
while ($rs = mysqli_fetch_array($rsPedidos))
{
$data[] = array(
'name' => $rs['projeto'],
'desc' => $rs["site"],
$valor[] = array(
'from' => '/Date(' . strtotime($rs["data_inicio_ti"]) . '000)/',
'to' => '/Date(' . strtotime($rs["data_fim_ti"]) . '000)/',
'desc' => $rs["funcionario"].' / PO:'.$rs["numero_po"].' / R$:'.$rs["valor_po"],//12658580,//1320192000000 1497582000
'label' => $rs["servico"],
'customClass' => 'ganttRed',
),
'values' =>$valor,
);
$json = $data;
}
print json_encode($json);

wordpress query 2 sets of meta keys

I am trying to do a custom sql query to get 2 lots of post_meta keys and there values. Here is my code:
<?php
$queried_post = get_post($post_id);
$title = $term->name ;
$userid = $current_user->user_email;
$result = mysql_query("SELECT * FROM wp_postmeta WHERE meta_key='user_programme_name' AND meta_value='".$title."' AND meta_key='user_email' AND meta_value='".$userid."' ");
$num_rows = mysql_num_rows($result);
if ($num_rows > 0 ) {
?>
<p style="width:430px;">You have already requested a place on this course</p>
<?php } ?>
The first part of the query works when i jsut query the first set of keys and values:
meta_key='user_programme_name' AND meta_value='".$title."'
But as soon as i add the second lot:
AND meta_key='user_email' AND meta_value='".$userid."'
It doesn't work. Is there something I'm doing wrong?
Any help would be greatly appreciated.
Cheers, Dan
Use something like this :
$args = array( 'post_type' => 'myposttype',
'posts_per_page' => …,
'offset' => …,
'meta_query'=>array(
'relation' => 'AND',
array(
'key'=>'_first_key',
'value'=> youvalue,
'type' => 'DATE', // etc.
'compare' => '='
),
array(
'key'=>'_second_key',
'value'=> youvalue,
'type' => 'DATE', // etc.
'compare' => '='
)
)
);
$yourloop = new WP_Query( $args );
Fix your SQL syntax for selecting multiple values on the same column:
<?php
$result = mysql_query("SELECT * FROM wp_postmeta WHERE meta_key IN ('user_programme_name', 'user_email') AND meta_value IN ('.$title.', '.$userid.') ");
?>