Query with GROUP_CONCAT not working with PHP - php

I am trying to display certain values through GROUP_CONCAT, and GROUP BY, yet only the groups are showing when I test it out, and the other values don't.
function events_calendar() {
global $connection;
mysqli_select_db($connection);
$query = ("SELECT month, GROUP_CONCAT(start_date) as data FROM events GROUP BY month");
$result = $connection->query($query);
$str = "";
while ($row = $result->fetch_assoc()) {
echo $row['month'];
echo $row['start_date'];
}
return $str;
}
The month values show up, but the start_date values don't.

The problem is the PHP. Try replacing:
echo $row['start_date'];
with:
echo $row['data'];
You need to use the column alias that you assigned in the SELECT.

Related

Mysqli count not working properly

$sql = "SELECT count(id),soft_name from table_name GROUP BY soft_name";
$d = mysqli_fetch_assoc(mysqli_query($db_name, $sql));
$c = array_shift($d);
The result is always 2, but the database contains more than 3000 items. What could be the problem?
Records are not pulled the way you are pulling for that you have to use similar to following code:
if($result = mysqli_query($db_name, $sql)){
while($d = mysqli_fetch_assoc($result){
echo $d['count'];
}
}
More reference here.

PHP while loops and if statement issues when pulling from multiple tables

I have 2 tables with a unique ID. I have a table with one of the columns being a date field. I am attempting to filter the field by today's date (which it works) from all the rows with "todays" date I want to get the cell info for #key. Once I have that ID, I want to match it with #headkey. So $headkey == $key. Once I filter that, I want to see if any of the fields match = Delivery for the ItemID column. For some reason I have an infinite loop. I played around with the logic but can't seem to get it to work. Any ideas?
$TransactionSql = "SELECT * FROM apcshead WHERE DateInvoiced > 0 ORDER BY DateInvoiced DESC";
$ItemsSql = "SELECT * FROM apcsitem";
$rs=odbc_exec($conn,$TransactionSql);
while($row = odbc_fetch_array($rs))
{
//Grabbing Transaction info
$DateInvoiced = odbc_result($rs,"DateInvoiced");
$ApcsheadKey = odbc_result($rs,"Key");
$DateInvoiced = new DateTime($DateInvoiced);
$DateInvoiced_date = $DateInvoiced->format('m-d-Y');
//$TimeStamp_time = $TimeStamp->format('h:i:s');
if ($DateInvoiced_date == $today)
{
$ItemsRs=odbc_exec($conn,$ItemsSql);
while($row = odbc_fetch_array($ItemsRs))
{
$HeadKey = odbc_result($ItemsRs,"HeadKey");
$ItemID = odbc_result($ItemsRs,"ItemID");
if ($ItemID == 'Delivery')
{
echo 'Delivery';
echo '<br />';
}
}
}
}
*UPDATE:*I modified the code again. Now what if does is it spits out 1 row with the date and then like 100 echo Delivery and then goes back and spits out another date and the same thing. Still not sure what is going on.
$TransactionSql = "SELECT * FROM apcshead WHERE DateInvoiced > 0 ORDER BY DateInvoiced DESC";
$ItemsSql = "SELECT * FROM apcsitem";
$rs=odbc_exec($conn,$TransactionSql);
while($row = odbc_fetch_array($rs))
{
$DateInvoiced = odbc_result($rs,"DateInvoiced");
$DateInvoiced = new DateTime($DateInvoiced);
$DateInvoiced_date = $DateInvoiced->format('m-d-Y');
echo $DateInvoiced_date;
echo '<br />';
if ($DateInvoiced_date == $Today)
{
echo $DateInvoiced_date;
echo '<br />';
$ItemsRs=odbc_exec($conn,$ItemsSql);
while($row = odbc_fetch_array($ItemsRs))
{
$ItemID = odbc_result($ItemsRs,"ItemID");
if ($ItemID == 'Delivery')
{
echo 'Delivery';
}
}
}
}
I solved the issue using the INNER JOIN command. It is great because I don't have to do nested loops :)
Learned how to do it from W3Schools. http://www.w3schools.com/sql/sql_join_inner.asp
This is my current SQL Statement:
$TransactionSql = "SELECT apcshead.Key, apcshead.DateInvoiced, apcshead.InvNum, apcsitem.Headkey, apcsitem.ItemID FROM apcshead INNER JOIN apcsitem ON apcshead.Key=apcsitem.Headkey";

While loop within a while loop

I have one table which contains events and dates, and another which contains the guestlist for each of these nights. I can print the nights like so:
$day = date("l");
$date = getFullDateString($day);
$result = mysql_query("SELECT * FROM nights WHERE day = '$day' AND promoter = 'blah'") or die(mysql_error);
while ($row = mysql_fetch_array($result)) {
echo "<h2>";
echo $row[name];
echo " (";
echo getFullDateString($row[day]);
echo ")</h2>";
}
The problem is that for each of these events I want the guestlist to be printed below it. I've tried putting another while loop inside, but even the test echo doesn't work.
$result2 = mysql_query("SELECT DISTINCT guest FROM guestlists WHERE night = '$row[name]' AND date = 'getFullDateString($row[day])'") or die(mysql_error ());
while($row2 = mysql_fetch_array($result2)) {
echo $row2[0];
echo "test";
echo "<br />";
}
Essentially I want the following:
Event 1
Name 1
Name 2
Name 3
Event 2
Name 1
Name 2
Name 3
You have a method inside the query string which won't be run.
Try:
$sql = "SELECT DISTINCT guest FROM guestlists WHERE night = '".$row['name']."' AND `date` = '".getFullDateString($row['day'])."'"
Also, date is a reserved word in MySQL and should be encapsulated within backticks or changed to something else.
Additionally, the mysql_ functions are being deprecated and it is recommended to replace them with PDO or MySQLi.
Take a look at Complex (curly) syntax for string parsing to learn the proper way to embed your variables in the string.
Try this...
$result = mysql_query("SELECT * FROM nights WHERE day = '".$day."' AND promoter = 'blah'") or die(mysql_error);
while ($row = mysql_fetch_array($result)) {
echo "<h2>".$row[cname]."</h2>";
$result2 = mysql_query("SELECT DISTINCT guest FROM guestlists WHERE night = '$row[name]' AND date = '".getFullDateString($row[day])."'") or die(mysql_error);
while ($row2 = mysql_fetch_array($result2))
{
echo $row2[cname];
}
}

Get total number of records for a given day in Highcharts and PHP

I'm trying to get my highcharts chart working and I'm almost there.. I just have one little problem: I need that the value will be the total count of the records at the same day but I'm kinda confused with my code now and the chart is totally messed up..
Here is the code that pulls the data:
<?php
header("Content-type: text/json");
include('../includes/config.php');
$tablename = "analytics";
$result = mysql_query("SELECT COUNT(*) AS count FROM $tablename");
$row = mysql_fetch_array($result,MYSQL_ASSOC);
$sql = "SELECT id, date FROM $tablename ORDER BY date";
$result = mysql_query( $sql ) or die("Couldn't execute query.".mysql_error());
$i=0;
while($row = mysql_fetch_array($result,MYSQL_ASSOC)) {
$row['id'] = (int) $row['id'];
$rows[$i] = array(strtotime($row['date'])*1000, $row['id']);
$i++;
}
echo json_encode($rows);
?>
If it will help here is my database values:
insert into `analytics`(`id`,`user`,`item`,`ip`,`country`,`date`) values
(10,1,1,'127.0.0.1','','2011-12-17 06:41:51'),
(11,1,1,'127.0.0.1','','2011-12-17 06:42:23'),
(12,1,1,'127.0.0.1','','2011-12-17 06:43:07'),
(13,1,1,'127.0.0.1','','2011-12-17 06:44:19'),
(14,1,1,'127.0.0.1','','2011-12-17 06:44:21'),
(15,1,1,'127.0.0.1','','2011-12-17 06:44:22'),
(16,1,1,'127.0.0.1','','2011-12-17 06:44:49'),
(17,1,1,'127.0.0.1','','2011-12-17 06:46:59'),
(18,1,1,'127.0.0.1','','2011-12-17 06:47:20'),
(19,1,1,'127.0.0.1','','2011-12-17 06:47:35'),
(20,1,1,'127.0.0.1','','2011-12-17 06:47:42'),
(21,1,1,'127.0.0.1','','2011-12-17 06:48:07'),
(22,1,1,'127.0.0.1','','2011-12-17 06:48:14'),
(23,1,1,'127.0.0.1','','2011-12-17 06:48:29'),
(24,1,1,'127.0.0.1','','2011-12-18 06:49:10'),
(25,1,1,'127.0.0.1','','2011-12-19 07:05:45'),
(26,1,1,'127.0.0.1','','2011-12-20 08:11:32'),
(27,1,1,'127.0.0.1','','2011-12-21 08:26:45'),
(28,1,1,'127.0.0.1','','2011-12-17 08:44:34');
And here is the final result:
I totally lost my self here, can someone help?
EDIT: did what #ajreal said and here is the output:
This is the query to get count for each date
SELECT date, COUNT(*) AS count
FROM $tablename
GROUP BY date;
You can use this query to replace your first query.
And to a loop (like your second query), set $total += $row["count"] to get a grand total like your original first query does

Pulling data and printing it in an HTML table

From a MySQL table called "submission" containing the fields "loginid, submissionid, title, url, datesubmitted, displayurl", I would like to print an HTML table thats contains all "title" and corresponding "datesubmitted" where "loginid" equals "$profile." The code I am trying to use is below. It isn't working. Any ideas why it isn't working?
Thanks in advance,
John
$profile = $_GET['profile'];
$sqlStr = "SELECT loginid, submissionid, title, url, datesubmitted, displayurl
FROM submission
WHERE loginid = $profile
ORDER BY datesubmitted DESC";
$result = mysql_query($sqlStr);
$arr = array();
echo "<table class=\"samplesrec\">";
while ($row = mysql_fetch_array($result)) {
echo '<tr>';
echo '<td class="sitename1">'.$row["title"].'</td>';
echo '</tr>';
echo '<tr>';
echo '<td class="sitename2">'.$row["datesubmitted"].'</a></td>';
echo '</tr>';
}
echo "</table>";
Your query is probably failing.
Try echoing the return from mysql_error(); after trying the query to see what the issue might be.
You should also protect your input against injection. If loginID is a username, you need to surround a string in a mySQL query with quotes - if loginID is a username. If it's an integer you may be okay.
There are more robust ways to do this but simply:
$profile = mysql_real_escape_string($_GET['profile']);
$sqlStr = "SELECT loginid, submissionid, title, url, datesubmitted, displayurl
FROM submission
WHERE loginid = '$profile'
ORDER BY datesubmitted DESC";
$result = mysql_query($sqlStr);
if($result) {
// Handle output
}
else {
echo 'query failed';
// don't leave this here in production!
echo mysql_error();
}
One problem I can see is you are not checking in the return value of mysql_query()
mysql_query() returns false if it fails to execute the query. So you need to do a check, something like:
$result = mysql_query($sqlStr);
if(! $result) {
//....error occured...prepare $message
die($message);
}
your question regards to debugging, the most important programming art. Noone can find an error for you, you have to do it yourself. With help of little tricks.
change $profile = $_GET['profile']; to $profile = intval($_GET['profile'];)
change $result = mysql_query($sqlStr); to
$result = mysql_query($sqlStr) or trigger_error(mysql_error()." in ".$sqlStr);
andd following 2 lines at the top of your code, run it again and see what it say. if still nothing, you don't have matching records in your table.
ini_set('display_errors',1);
error_reporting(E_ALL);

Categories