I have a while fetch_assoc that produces and xml file for me. It works fine but now i need to add another variable to it.
Here is the working query
$sql3 = "SELECT name, class FROM tbl_user_tmp where user = '$user' order by name";
if(!$result3 = $mysqli->query($sql3)){
die('There was an error running the query [' . $mysqli->error . ']');
}
while($row2 = $result2->fetch_assoc()){
if(!isset($previousRow2) || !isset($previousRow2["category"]) || $previousRow2["category"] != $row2["category"])
{
$xml2 .= "\r\n";
$xml2 .= "<category title=\"" . $row2["category"] . "\" />\r\n";
}
$xml2 .= " <item drawable=\"";
$xml2 .= $row2["name"];
$xml2 .= "\" />";
$xml2 .= "\r\n";
$previousRow2 = $row2;
}
Now, what i need to do is take a array, and based on it,order what titles get done first.
This is how the array looks
$cat_order[]
Games,Apps,Google,Misc,System
You can order this in the query:
<?php
//Dynamic solution, build the SQL with a loop:
$cat_order = array("Games", "Apps", "Google");
$caseStr = "";
foreach($cat_order as $index => $value)
$caseStr .= sprintf("WHEN '%s' THEN %d ", $value, $index+1);
$sql3 = "
SELECT name, class
FROM tbl_user_tmp where user = '$user'
ORDER BY CASE name" . $caseStr . " END";
?>
Sorry to ask then answer but here is how i did it
$cat_name = $_POST['cat'];
foreach($cat_name as $k=>$val)
{
$cat_order[] = $val;
}
debug_to_console($cat_order);
$sql2 = "SELECT distinct category, name FROM tbl_user_tmp where user = '$user' and category is not null and category <> '' order by field (category,";
$size = count($cat_name);
foreach($cat_name as $k=>$val)
{
$sql2 .= "'$val'";
if($size > $k+1) $sql2 .=',';
}
$sql2 .= ")";
debug_to_console($sql2);
Related
table users has 14 columns - id, src link, title...
function get_atitles(){
global $db;
$st = $db->query("select * from users order by name asc");
$arr = $st->fetchAll();
$ht = '';
foreach($arr as $el){
$ht .= "<div class='atitle' data-id= " . $el['id'] . " data-src='" . $el['src'] . "... and so on for all of the 14 columns...>" . $el['title'] . "</div>\n";
}
echo $ht;
}
Is there a shorter way, like this:
foreach($arr as $el){
$ht .= "<div class='atitle'
//foreach column in users $ht .= "data-" . column_name = column_value
$ht .= ">" . $el['title'] . "</div>\n";
}
Maybe something like this:
function get_atitles(){
global $db;
$st = $db->query("select * from users order by name asc");
$arr = $st->fetchAll(PDO::FETCH_ASSOC);
$ht = '';
foreach($arr as $el){
$ht = $ht . "<div class='atitle' ";
foreach($el as $key=>$col)
if($key != 'title')
$ht .= "data-".$key.'="'.$col.'" ';
$ht.= '>'.$el['title'] . "</div>\n";
}
echo $ht;
}
I'm not sure why this SQL query is not working.
I'm new to SQL/PHP so please forgive.
mysql_query("
SELECT * FROM table WHERE name = " . "'Bob'" .
while($i < $size)
{
$i++;
echo "OR name = '";
echo $array[$i] . "'";
} .
" ORDER BY id DESC "
);
Dreamweaver gives me an error saying it is not correct but does not tell me what is wrong.
Is it possible to put a while loop into an sql command?
you can not use a while in a string
$where = "";
if ($size > 0)
{
$where .= " WHERE ";
}
while($i < $size)
{
$i++;
$where .= "OR name = '".$array[$i]."' ";
}
$query = "SELECT * FROM table WHERE name = '".Bob."'".$where." ORDER BY id DESC";
mysql_query($query);
(this code is not tested)
Woot !
You just can't write this :D
Build your OR condition before writing the query and it will be just fine:
$myCondition = " ";
while($i < $size) {
$i++;
$myCondition .= "OR name = '" . $array[$i] . "'";
}
mysql_query(
"SELECT * FROM table WHERE name = " . "'Bob'" . $myCondition . " ORDER BY id DESC ");
echo is to output the string, and it won't return the string.
Something like $str = "aaa" . echo "bbb"; won't work.
For you case, use IN will be better.
foreach ($array as &$name) {
$name = "'".mysql_real_escape_string($name)."'";
}
mysql_query("SELECT * FROM table WHERE name IN (".implode(',', $array).")");
Or use
"SELECT * FROM table WHERE name IN(".implode( ',', $array).")";
Can someone help me with the following code? The output works fine starting with the "categories" tag but the if loop only returns the last row from the db.
$strXML = "<chart> \n";
$strQuery = "select inc_type, sum(num_of_occur) as cnt from inc_detail
group by inc_type";
$query2 = mysql_query($strQuery); //call string query
$strCategories = "<categories>\n"; //create categories
while ($cat = mysql_fetch_array($query2))
{
$strCategories .= "<category label='" . $cat['inc_type'] . "' /> \n"; //display categories
};
$strCategories .= "</categories> \n";
$strQuery2 = "select agency, inc_type, sum(num_of_occur) as cnt from inc_detail group by inc_type, agency order by agency";
$query3 = mysql_query($strQuery2); //call string query
$agency = null;
while ($ds = mysql_fetch_array($query3))
{
if( $ds['agency'] != $agency )
{
$K5 = "<dataset seriesName='" . $ds['agency'] . "' /> \n"; //create dataset
$agency = $ds['agency'];
}
$K5 .= "<set value='" . $ds['cnt'] . "' /> \n"; //display value of dataset
$K5 .= "</dataset> \n";
}
$strXML .= $strCategories . $K5 . "</chart>"; //end of XML
echo $strXML;
The problem is here:
$K5 = "<dataset seriesName ...
You rewrite the $K5 every cycle of the iteration.
Suggested solution:
$K5 = "";
while ( ...
...
$K5 .= "<dataset seriesName ...
I finally got it working. For anyone interested, this is a fusionchart php file grabbing mysql data for a multiseries bar chart. Below is my new code:
$strXML = "<chart labelDisplay='Rotate' slantLabels='1' caption='Test' subCaption='By Quantity' decimalPrecision='0' showValues='0' showNames='1' numberSuffix=' Incidents' formatNumberScale='10'>";
$strQuery = "select inc_type, sum(num_of_occur) as cnt from inc_detail
group by inc_type";
$query2 = mysql_query($strQuery); //call string query
$strCategories = "<categories>"; //create categories
while ($cat = mysql_fetch_array($query2))
{
$strCategories .= "<category label='" . $cat['inc_type'] . "' />"; //display categories
}
$strCategories .= "</categories>";
$strQuery2 = "select agency, inc_type, sum(num_of_occur) as cnt from inc_detail group by inc_type, agency order by agency";
$query2 = mysql_query($strQuery2); //call string query
$K5 = $blank;
while ($ds2 = mysql_fetch_array($query2))
{
$K5 .= "<dataset seriesName='" . $ds2['agency'] . "' />"; //create dataset
//create dataset values
$strQuery4 = "select inc_type, sum(num_of_occur) as cnt from inc_detail where agency = '$ds2[agency]' group by inc_type";
$query4 = mysql_query($strQuery4);
while ($ds4 = mysql_fetch_array($query4))
{
$K5 .= "<set value='" . $ds4['cnt'] . "' />"; //display value of dataset
}
$K5 .= "</dataset>";
}
$strXML .= $strCategories . $K5 . "</chart>"; //end of XML
echo renderChart("fc/MSColumn3D.swf", "", $strXML, "productSales", 900, 600);
I looked through the stack questions and answers, but didn't see anything I could directly apply here. Maybe I'm just missing something.
The code below works fine, except when I include my where statement which refers to the value of the $wp_user_id variable.
I've checked that the variable IS actually being populated with a $user_id when the script is loaded. It appears that the value of this variable is lost right after the call to the conManager function, but I don't understand why. There doesn't appear to be anything within the ConnectionManager.php file (which defines the conManager function) which would touch this variable, so I'm at a loss.
I'm a PHP hack, so go easy on me, but what is causing me to lose the value of my variable, and how do I address it? Here's the code:
<?php
include_once("/home/evaluate/public_html/admin/php/ConnectionManager.php");
header('Content-type:text/javascript;charset=UTF-8');
$wp_user_id = $_GET["user"];
$json1=json_decode(stripslashes($_POST["_gt_json"]));
$pageNo = $json1->{'pageInfo'}->{'pageNum'};
$pageSize = $json1->{'pageInfo'}->{'pageSize'};
if(isset($json1->{'sortInfo'}[0]->{'columnId'})){
$sortField = $json1->{'sortInfo'}[0]->{'columnId'};
}
else{
$sortField = "miles_on_oil";
}
if(isset($json1->{'sortInfo'}[0]->{'sortOrder'})){
$sortOrder = $json1->{'sortInfo'}[0]->{'sortOrder'};
}
else{
$sortOrder = "ASC";
}
if($json1->{'sortInfo'}[0]->{'sortOrder'} == "defaultsort"){
$sortField = "miles_on_oil";
$sortOrder = "ASC";
}
if($json1->{'filterInfo'}[0]->{'value'} != "") {
for ($i = 0; $i < count($json1->{'filterInfo'}); $i++) {
if($json1->{'filterInfo'}[$i]->{'logic'} == "equal"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "notEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "!='" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "less"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "lessEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . "<=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "great"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "greatEqual"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . ">=" . $json1->{'filterInfo'}[$i]->{'value'} . " ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "like"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "startWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '" . $json1->{'filterInfo'}[$i]->{'value'} . "%' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == "endWith"){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}elseif($json1->{'filterInfo'}[$i]->{'logic'} == ""){
$filter .= $json1->{'filterInfo'}[$i]->{'columnId'} . " LIKE '%" . $json1->{'filterInfo'}[$i]->{'value'} . "' ";
}
$filter .= " AND ";
}
}
else {
$filter = '';
}
//print_r ($json1);
//die;
// Temp TEsting Values
// End Temp Testing Values
$conManager = new ConManager();
$conManager->getConnection();
if($json1->{'action'} == 'load'){
//to get how many records totally.
$sql = "select count(*) as cnt from oil_analysis_data where $filter user_id = '".$wp_user_id."'";
$handle = mysql_query($sql);
$row = mysql_fetch_object($handle);
$totalRec = $row->cnt;
$sql2 = "select * from oil_analysis_data where $filter user_id = '".$wp_user_id."' ORDER BY " . $sortField . " " . $sortOrder . " limit " . ($pageNo - 1)*$pageSize . ", " . $pageSize;
$handle2 = mysql_query($sql2);
$retArray2 = array();
while($row2 = mysql_fetch_assoc($handle2)) {
// Grab Vehicle Make, Model & Year "Names" from their respective tables & insert into the array
$year = "select Name from vehicle_data_years where ID = {$row2['list1']}";
$year1 = mysql_query($year);
$year2 = mysql_fetch_assoc($year1);
$year3 = $year2['Name'];
$make = "select Name from vehicle_data_makes where ID = {$row2['list2']}";
$make1 = mysql_query($make);
$make2 = mysql_fetch_assoc($make1);
$make3 = $make2['Name'];
$model = "select Name from vehicle_data_all where ID = {$row2['list3']}";
$model1 = mysql_query($model);
$model2 = mysql_fetch_assoc($model1);
$model3 = $model2['Name'];
$row2['list1'] = $year3;
$row2['list2'] = $make3;
$row2['list3'] = $model3;
// Grab Motor oil Viscosity, Brand & Product "Names" from their respective tables & insert into the array
$visc = "select name from viscosity where id = {$row2['viscosity']}";
$visc1 = mysql_query($visc);
$visc2 = mysql_fetch_assoc($visc1);
$visc3 = $visc2['name'];
$brand = "select brandname from oil_brand where brandid = {$row2['brand']}";
$brand1 = mysql_query($brand);
$brand2 = mysql_fetch_assoc($brand1);
$brand3 = $brand2['brandname'];
$product = "select product_name from oil_data where id = {$row2['product']}";
$product1 = mysql_query($product);
$product2 = mysql_fetch_assoc($product1);
$product3 = $product2['product_name'];
$row2['viscosity'] = $visc3;
$row2['brand'] = $brand3;
$row2['product'] = $product3;
if($row2['bypass_filtration'] == 1) {
$row2['bypass_filtration'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['bypass_filtration'] = "";
}
if($row2['oil_change'] == 1) {
$row2['oil_change'] = "<img src='http://themotoroilevaluator.com/admin/php/crud/images/checkmark.png' style='border: 0px;'>";
}
else {$row2['oil_change'] = "";
}
$retArray[] = $row2;
}
$analysis_data = json_encode($retArray);
$ret = "{data:" . $analysis_data .",\n";
$ret .= "pageInfo:{totalRowNum:" . $totalRec . "},\n";
$ret .= "recordType : 'object'}";
echo $ret;
}
?>
I'm curious, why do you add a semi colon after the $wp_user_id; ? I've noticed you doing this in more than one place. This may be the culprit.
$filter user_id = '".$wp_user_id;."'";
Nevermind. It would appear that my problem actually resulted from a change in my code that I had forgotten about. I changed $_REQUEST['user'] to $_GET['user'], thinking that, in this case, since the value was being passed as a URL query string, that wouldn't be a problem.
To be honest, I'm still not entirely sure why that made a difference - although I can research that on my own. But, at any rate, changing that back corrected my problem entirely.
Thanks to those who responded, though. Even if not solutions to my actual problem, the information from both turned out to be very useful.
Any hacker can severely screw up or delete your database because of the way you use direct user provided data to build up your SQL query. Please instead read up on SQL Injection, and the use of PHP prepared statements.
Relevant
I'm attempting the modify this Modx Snippet so that it will accept multiple values being returned from the db instead of the default one.
tvTags, by default, was only meant to be set to one variable. I modified it a bit so that it's exploded into a list of variables. I'd like to query the database for each of these variables and return the tags associated with each. However, I'm having difficulty as I'm fairly new to SQL and PHP.
I plugged in $region and it works, but I'm not really sure how to add in more WHERE clauses for the $countries variable.
Thanks for your help!
if (!function_exists('getTags')) {
function getTags($cIDs, $tvTags, $days) {
global $modx, $parent;
$docTags = array ();
$baspath= $modx->config["base_path"] . "manager/includes";
include_once $baspath . "/tmplvars.format.inc.php";
include_once $baspath . "/tmplvars.commands.inc.php";
if ($days > 0) {
$pub_date = mktime() - $days*24*60*60;
} else {
$pub_date = 0;
}
list($region, $countries) = explode(",", $tvTags);
$tb1 = $modx->getFullTableName("site_tmplvar_contentvalues");
$tb2 = $modx->getFullTableName("site_tmplvars");
$tb_content = $modx->getFullTableName("site_content");
$query = "SELECT stv.name,stc.tmplvarid,stc.contentid,stv.type,stv.display,stv.display_params,stc.value";
$query .= " FROM ".$tb1." stc LEFT JOIN ".$tb2." stv ON stv.id=stc.tmplvarid ";
$query .= " LEFT JOIN $tb_content tb_content ON stc.contentid=tb_content.id ";
$query .= " WHERE stv.name='".$region."' AND stc.contentid IN (".implode($cIDs,",").") ";
$query .= " AND tb_content.pub_date >= '$pub_date' ";
$query .= " AND tb_content.published = 1 ";
$query .= " ORDER BY stc.contentid ASC;";
$rs = $modx->db->query($query);
$tot = $modx->db->getRecordCount($rs);
$resourceArray = array();
for($i=0;$i<$tot;$i++) {
$row = #$modx->fetchRow($rs);
$docTags[$row['contentid']]['tags'] = getTVDisplayFormat($row['name'], $row['value'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
}
if ($tot != count($cIDs)) {
$query = "SELECT name,type,display,display_params,default_text";
$query .= " FROM $tb2";
$query .= " WHERE name='".$region."' LIMIT 1";
$rs = $modx->db->query($query);
$row = #$modx->fetchRow($rs);
$defaultOutput = getTVDisplayFormat($row['name'], $row['default_text'], $row['display'], $row['display_params'], $row['type'],$row['contentid']);
foreach ($cIDs as $id) {
if (!isset($docTags[$id]['tags'])) {
$docTags[$id]['tags'] = $defaultOutput;
}
}
}
return $docTags;
}
}
You don't add in more WHERE clauses, you use ANDs and ORs in the already existing where clause. I would say after the line $query .= " WHERE stv.name = '".$region... you put in
foreach ($countries as $country)
{
$query .= "OR stv.name = '{$country}', ";
}
but I don't know how you want the query to work.