PHP Unable to fetch the Cloumn Name from my sql Query - php

I am trying to fetch Data from my sql Query but I am getting the wrong data So can anyone tell me how to do it correctly.
Here Is my code
$result = mysql_query("select
CONCAT_WS(',',
(case when Q1 is not null then 'Q1' else '' end),
(case when Q2 is not null then 'Q2' else '' end),
(case when Q3 is not null then 'Q3' else '' end),
(case when Q4 is not null then 'Q4' else '' end),
(case when Q5 is not null then 'Q5' else '' end),
(case when Q6 is not null then 'Q6' else '' end),
(case when Q7 is not null then 'Q7' else '' end),
(case when Q8 is not null then 'Q8' else '' end),
(case when Q9 is not null then 'Q9' else '' end)
) as NonNullColumns
from $day
where `user` = '$user'") or die(mysql_error());
//echo $result;
if (mysql_num_rows($result) > 1) {
// looping through all results
// products node
$response["Q"] = array();
while ($row = mysql_fetch_assoc($result)) {
// temp user array
$qnumber = array();
$qns= array();
$qnumber["Q".$i] = $row["$Q"];
$i = $i + 1;
// push single product into final response array
array_push($response["Q"], $qnumber);
}
}
I am getting the following Output from my SQl query
NonNullColumns
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
Q1,Q2,Q3,,,,,,
I need to fetch the values Q1, Q2,Q3 from my SQl query output but I am able to fetch
{"Q":[{"Q":null},{"Q1":null},{"Q2":null},{"Q3":null},{"Q4":null},{"Q5":null}],"success":1}
So Can any one tell me how to obtain the followig output
{"Q":[{Q1},{Q2},{Q3}],"success":1}

You have only one column as you've concatenated all data.
So instead of refering to $row["$Q"] you have to explode(',', $row['NonNullColumns']) and add non-empty string to the array

Related

SQL UPDATE and SET on phpmyadmin depending on the values

Would like to know how come my SQL update case is not functioning correctly.
I already have values:
$usrcustomerid = 110;
$search = 'face';
Looking for a fix on my CASE in SET because there is no update when this SQL triggers
SQL Update code
public function UpdateUserSearch($db, $usrcustomerid, $search) {
$stmt = $db->prepare(
" UPDATE usr_customer
SET search_counter = (CASE WHEN search_counter = 1 THEN 2
WHEN search_counter = 2 THEN 3
WHEN search_counter = 3 THEN 1 END),
search1 = (CASE WHEN search_counter = 1 THEN $search END),
search2 = (CASE WHEN search_counter = 2 THEN $search END),
search3 = (CASE WHEN search_counter = 3 THEN $search END)
WHERE usrcustomerid = $usrcustomerid "
);
$stmt->bindValue(':usrcustomerid', $usrcustomerid, PDO::PARAM_INT);
$stmt->bindValue(':search', $search, PDO::PARAM_STR);
$stmt->execute();
$rowAffected = $stmt->rowCount();
return $rowAffected;
}
table usr_customer
In the picture below, the user's search_counter is set to one and the three search columns have no value inside, so the code, based on my logic in my CASE, should have my "$search" value insert in "search1" and update search_counter from 1 to 2.
PS I am aware of SQL Injection, please do not answer with a reminder because I am trying to get my code working first.
This is not a SQL issue, it is a PHP issue. The values you are replacing in your SQL Query should be prefixed with : instead of $.
" UPDATE usr_customer
SET search_counter = (CASE WHEN search_counter = 1 THEN 2
WHEN search_counter = 2 THEN 3
WHEN search_counter = 3 THEN 1 END),
search1 = (CASE WHEN search_counter = 1 THEN :search END),
search2 = (CASE WHEN search_counter = 2 THEN :search END),
search3 = (CASE WHEN search_counter = 3 THEN :search END)
WHERE usrcustomerid = :usrcustomerid "
See: PHP Documentation

MySQL Advanced multidimensional query with CONCAT, JSON and IF statement

I working on one complex listing from database and decide to do all possible requests via one query.
Here is working example:
"SELECT
`c`.`categories_id`,
`c`.`categories_status`,
IF(`c`.`categories_status` = 1, 'Active', 'Not Active') AS `categories_status_name`,
TRIM(`cd`.`categories_name`) AS `categories_name`,
TRIM(`cd`.`concert_date`) AS `concert_date`,
TRIM(`cd`.`concert_time`) AS `concert_time`,
TRIM((
SELECT
CONCAT(
'{\"total_quantity\":',
SUM(CASE WHEN `p`.`products_quantity` > 0 THEN `p`.`products_quantity` ELSE 0 END),
',\"total_price\":\"',
SUM(`p`.`products_price`),
'\"}'
)
FROM
`products_to_categories` `ptc`,
`products` `p`
WHERE
`ptc`.`section_id` = `cd`.`section_id`
AND
`p`.`products_id` = `ptc`.`products_id`
)) AS `products_available`,
TRIM((
SELECT
CONCAT(
'{\"total_quantity\":',
SUM(CASE WHEN `op`.`products_quantity` > 0 THEN `op`.`products_quantity` ELSE 0 END),
',\"total_price\":\"',
SUM(`op`.`final_price`),
'\"}'
)
FROM
`products_to_categories` `ptc`,
`orders_products` `op`
WHERE
`ptc`.`section_id` = `cd`.`section_id`
AND
`op`.`products_id` = `ptc`.`products_id`
AND
`op`.`orders_products_status` != 1
)) AS `products_sold`,
TRIM((
SELECT
CONCAT(
'{\"total_quantity\":',
SUM(CASE WHEN `op`.`products_quantity` > 0 THEN `op`.`products_quantity` ELSE 0 END),
',\"total_price\":\"',
SUM(`op`.`final_price`),
'\"}'
)
FROM
`products_to_categories` `ptc`,
`orders_products` `op`
WHERE
`ptc`.`section_id` = `cd`.`section_id`
AND
`op`.`products_id` = `ptc`.`products_id`
AND
`op`.`orders_products_status` = 1
)) AS `products_pending`
FROM
`categories` `c`,
`categories_description` `cd`
WHERE
`c`.`categories_id` = `c`.`section_id`
AND
`cd`.`categories_id` = `c`.`categories_id`
GROUP BY `c`.`categories_id`
ORDER BY `c`.`categories_status` DESC;"
This work great but my main problem is how to do check IF/ELSE or CASE WHEN for custom defined new fields: products_available, products_sold and products_pending?
Problem is that if products not exists inside table orders_products I not get my generated JSON and that's made a small conflict inside PHP.
I can do check in PHP but want to avoid that part and just print JSON like:
{"total_quantity":0,"total_price":"0.0000"}
FROM
`products_to_categories` `ptc`,
`orders_products` `op`
*
WHERE `products_id` =
(SELECT COALESCE(`products_id`,0))
*
AND
`ptc`.`section_id` = `cd`.`section_id`

Conditionally Count a MYSQL Column Rows and Output Data via PHP

Sorry i am new to this. Just trying to learn. I am trying to conditionally count the number of times a particular condition occurs in SQL, using the case and count functions. This counts the number of males/females stored in eeg table. Here is my SQL query.
SELECT COUNT(CASE WHEN `Gender` = 'Male' THEN 1 END),
COUNT(CASE WHEN `Gender` = 'Female' THEN 1 END)
FROM `eeg`
This outputs the data when i run the query on the mysql backend (phpmyadmin), but in my php file, I get an "Undefined Index" error for those 2 rows. All othjer rows are perfectly okay. I do not know how to output those particular set of data to a variable.
Here is the SQL query (in full) in the php file:
$result = mysql_query("SELECT MONTH(ScanDate), YEAR(ScanDate),
COUNT(Investigation),
COUNT(CASE WHEN `Gender` = 'Male' THEN 1 END),
COUNT(CASE WHEN `Gender` = 'Female' THEN 1 END),
SUM(InvestigationAmount), SUM(AmountDue)
FROM eeg
WHERE Investigation = '{$investigation}'
AND ScanDate BETWEEN '{$ScanDate1}'
AND '{$ScanDate2}'");
Here is the while loop (in full):
while($row=mysql_fetch_array($result)){
$month_doe=$row['MONTH(ScanDate)'];
$year_doe=$row['YEAR(ScanDate)'];
$si=$row['COUNT(Investigation)'];
$male=$row["COUNT(CASE WHEN 'Gender' = 'Male' THEN 1 END)"];
$female=$row["COUNT(CASE WHEN 'Gender' = 'Female' THEN 1 END)"];
$sum_investigation=number_format($si);
$sia=$row['SUM(InvestigationAmount)'];
$sum_investigationamount=number_format($sia);
$srd=$row['SUM(AmountDue)'];
$sum_rebatedue=number_format($srd);
}
Thank you for your help. Been literally pulling my hair out, but love to learn and improve. And yes, mysql_query is depreciated :D
screenshots below:
Code screenshot
Use an alias for the expressions and use the alias to access the results of the expressions from php:
$result = mysql_query("SELECT MONTH(ScanDate) as sdyear,
YEAR(ScanDate) as sdmonth,
COUNT(Investigation) as investigation,
COUNT(CASE WHEN `Gender` = 'Male' THEN 1 END) as MaleCount,
COUNT(CASE WHEN `Gender` = 'Female' THEN 1 END) as FemaleCount,
SUM(InvestigationAmount) as investigationamount,
SUM(AmountDue) as amountdue
FROM eeg
WHERE Investigation = '{$investigation}'
AND ScanDate BETWEEN '{$ScanDate1}'
AND '{$ScanDate2}'");
while($row=mysql_fetch_array($result)){
$month_doe=$row['sdmonth'];
$year_doe=$row['sdyear'];
$si=$row['investigation'];
$male=$row["MaleCount"];
$female=$row["FemaleCount"];
$sum_investigation=number_format($si);
$sia=$row['investigationamount'];
$sum_investigationamount=number_format($sia);
$srd=$row['amountdue)'];
$sum_rebatedue=number_format($srd);
}
I would use this approach for every field that is an expression (the other sum() fields in the above query).

Mysql only outputs last loops data

i am trying to output statistics of calls made by agents across all dialing campaigns called for the day. there are multiple campaigns, currently 3, dialed in a day. I get the campaign data from a table name that changes by campaign like so custom_16546546 and custom_1564654. I run a query to get the numeric part of the column name then pass that as a variable in to another query that outputs the users statistics. This is where it only displays data from what i can tell is the last query loops information. I have displayed the array data from the first query to confirm the table names are being stored and it looks fine.
$today = "2013-05-29";
$customquery = "SELECT distinct( entry_list_id) FROM vicidial_list where entry_list_id > 0 and last_local_call_time between '$today 00:00:00' and '$today 23:59:59';" ;
$customresult = mysql_query($customquery) or die(mysql_error());
$customrows = mysql_num_rows($customresult);
while ($customrowResult = mysql_fetch_array($customresult))
{
$customID[] = $customrowResult["entry_list_id"];
}
$z = 0;
if(!$customID){
//echo " Please Select a valid date range: ".$today. " - ".$today." is not valid" ;
}else{
while($z<$customrows)
{
$query = "SELECT
vicidial_users.user,
vicidial_users.full_name,
vicidial_log.list_id,
COUNT(CASE WHEN (vicidial_log.status = 'SALE') THEN 1 ELSE null END) as sumcountSamnt,
COUNT(CASE WHEN (vicidial_log.status = 'SALE' AND custom_$customID[$z].up_amt <> '') THEN 1 ELSE null END) as sumcountupAmnt,
COUNT(CASE WHEN (vicidial_log.status = 'SALE' AND custom_$customID[$z].cc_num <> '') THEN 1 ELSE null END) as sumccverifiedcountAmnt,
COUNT(CASE WHEN (vicidial_log.status = 'SALE' AND custom_$customID[$z].bank_act <> '') THEN 1 ELSE null END) as sumbankverifiedcountAmnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE' AND custom_$customID[$z].cc_num <> '') THEN custom_$customID[$z].s_amount ELSE null END) as sumccverifiedAmnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE' AND custom_$customID[$z].bank_act <> '') THEN custom_$customID[$z].s_amount ELSE null END) as sumbankverifiedAmnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE') THEN custom_$customID[$z].d_amt ELSE null END) as sumDamnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE') THEN custom_$customID[$z].up_amt ELSE null END) as sumUpamnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE') THEN custom_$customID[$z].md_amt ELSE null END) as sumMdamnt,
SUM(CASE WHEN (vicidial_log.status = 'SALE') THEN custom_$customID[$z].s_amount ELSE null END) as sumSamnt
FROM
vicidial_log
INNER JOIN
vicidial_users
ON
(vicidial_log.user = vicidial_users.user)
INNER JOIN
custom_$customID[$z]
ON
(vicidial_log.lead_id = custom_$customID[$z].lead_id)
WHERE
call_date
BETWEEN
'$today 00:00:00'
AND
'$today 23:59:59'
AND
vicidial_log.user != 'VDAD'
AND
vicidial_users.user_group != 'TX-Training'
GROUP BY
vicidial_log.user, vicidial_log.campaign_id
";
//This query is used to sum loop data data
$queryResult = mysql_query($query) or die(mysql_error()); //This line perfomrs query error handling
$z++;
}
here is a snippet of how the data is displayed
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_assoc($result))
{
echo "<tr>\n";
//--fullname and userID
echo "<td> ".$row["full_name"]. " - ".$row["user"]."</td>\n";
//Agent total sales amount
if ($row["sumcountSamnt"] == '0') {
echo "<td>$nosalestxt</td>\n";
} else {
echo "<td> $".$row["sumSamnt"]."</td>\n";
}
}
So i want to be able to display a sum total of data for each user from all the campaigns they dialed from.
Thanks in advance for your help
EDIT: i use &row from a while loop to output the data and yes Chris i would like to store it an array, but i guess im just missing it, thanks again
Based on the code snippets you have given it looks like you are overwriting the value of $queryResult after each execution of the loop. Perhaps you meant to execute the query and put the results into an array (or something similar) to loop over and display later.
Also I notice you reference $row[] in your output, how are you assigning a value to that variable?

problem in counting two fields in one query

guys i need to count new private messages and old one from a table
so first thing come to mind is using mysql_num_rows and easy thing to do
// check new pms
$user_id = $userinfo['user_id'];
$sql = "SELECT author_id FROM bb3privmsgs_to WHERE user_id='$user_id' AND (pm_new='1' OR pm_unread='1')";
$result = $db->sql_query($sql) ;
$new_pms = $db->sql_numrows($result);
$db->sql_freeresult($result);
// check old pms
$sql = "SELECT author_id FROM bb3privmsgs_to WHERE user_id='$user_id' AND (pm_new='0' OR pm_unread='0')";
$result = $db->sql_query($sql) ;
$old_pms = $db->sql_numrows($result);
$db->sql_freeresult($result);
but how can i count these two fields just in one statement and shorter lines ?~
Use this query instead:
SELECT SUM(CASE WHEN pm_new = '1' OR pm_unread = '1' THEN 1 ELSE 0 END) AS new_pms,
SUM(CASE WHEN pm_new = '0' OR pm_unread = '0' THEN 1 ELSE 0 END) AS old_pms
FROM bb3privmsgs_to
WHERE user_id='$user_id'
Here's a MySQL-specific version that reads more cleanly:
SELECT COUNT(IF(pm_new = '1' OR pm_unread = '1', 1, NULL)) AS new_pms,
COUNT(IF(pm_new = '0' OR pm_unread = '0', 1, NULL)) AS old_pms
FROM bb3privmsgs_to
WHERE user_id='$user_id'
MySQL will cast comparisons to 1 or 0. You can use SUM() to add up the portion of the WHERE clause you were trying to count results for.
This is a (MySQL specific) shorter alternative to the CASE WHEN examples.
SELECT
SUM(pm_new='1' OR pm_unread='1') as new_pms,
SUM(pm_new='0' OR pm_unread='0') as old_pms
FROM bb3privmsgs_to
WHERE user_id='$userid'
In SQL Server, you can do something like this:
SELECT
SUM(CASE WHEN pm_new='1' OR pm_unread='1' THEN 1 ELSE 0 END),
SUM(CASE WHEN pm_new='0' OR pm_unread='0' THEN 1 ELSE 0 END)
FROM
bb3privmsgs_to WHERE user_id='$user_id'
I'll suppose you can do about the same thing in mySql, let me get back to you on the details...
As a lazy alternative to some of the other suggestions:
SELECT SUM(newPMS) AS newPMS,
SUM(oldPMS) AS oldPMS
FROM ( SELECT COUNT(author_id) AS newPMS,
0 AS oldPMS
FROM bb3privmsgs_to
WHERE user_id='$user_id'
AND (pm_new='1' OR pm_unread='1')
UNION
SELECT 0 AS newPMS
COUNT(author_id) AS oldPMS
FROM bb3privmsgs_to
WHERE user_id='$user_id'
AND (pm_new='0' OR pm_unread='0')
)

Categories