I'm so tired of finding out why the code is not loop with foreach in place. 1st loop is fetching the person name from db I use while loop as usual and it works. 2nd loop I test the total action each one of them doing in a month so I use a foreach loop for each month. But the problem is here. I can't make it loop again because of no clue.
Here's my codes:
error_reporting(E_ALL);
$thisYear=intval(date("Y"));
for($i=1;$i<13;$i++){
$i=sprintf("%02d",$i);
$monArr[]=$i;
}
//select all team members
$sql_sTeam=mysqli_query($con,"select * from TEAMNAMES order by fname asc");
$result=array();
while($rec_sTeam=mysqli_fetch_array($sql_sTeam)){
$rows['name']=$rec_sTeam['sale_fname'];//sale name
foreach($monArr as $key=>$val){
//$rows['data'][]=(int)$key;
$mon=intval($val);
//n action each member\
$sql_mLog=mysqli_query($con,"select * from mail_log where mlog_sid='$rec_sTeam[imap_sid]' and year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
$num_mLog=mysqli_num_rows($sql_mLog);
$rows['data'][] =(int)$num_mLog;//(int) will remove double qoutes around numbers
}//foreach
array_push($result,$rows);
}//while
echo json_encode($result);
There're 4 people in TEAMNAMES but this is the only result from json_encode:
[{"name":"Ar-eshah","data":[0,0,0,0,0,0,6,0,0,0,0,0]}]
Please point me out of here coz I'm stuck for several hours.
Regards,
Here the solution that you are looking for:
error_reporting(E_ALL);
$thisYear = intval(date("Y"));
for($i = 1; $i < 13; $i++){
$i = sprintf("%02d",$i);
$monArr[] = $i;
}
//select all team members
$sql_sTeam = mysqli_query($con,"select * from TEAMNAMES order by fname asc");
$result=array();
while($rec_sTeam=mysqli_fetch_array($sql_sTeam)){
$row = array();
$row['name']=$rec_sTeam['sale_fname'];//sale name
$row['data'] = array();
foreach($monArr as $key=>$val){
$mon=intval($val);
//n action each member\
$sql_mLog=mysqli_query($con,"select * from mail_log where mlog_sid='$rec_sTeam[imap_sid]' and year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
$num_mLog=mysqli_num_rows($sql_mLog);
$row['data'][] =(int)$num_mLog;//(int) will remove double qoutes around numbers
}//foreach
$result[] = $row;
}//while
echo json_encode($result)
Any MySQL errors? In this line:
$sql_mLog=mysqli_query($con,"select * from mail_log
where mlog_sid='$rec_sTeam[imap_sid]' and
year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
You need to brake the string in order to add an array value or use curly braces... like this:
$sql_mLog=mysqli_query($con,"select * from mail_log
where mlog_sid='".$rec_sTeam[imap_sid]."' and
year(mlog_dtime)='$thisYear' and month(mlog_dtime)='$mon'");
OR
$sql_mLog=mysqli_query($con,"select * from mail_log
where mlog_sid='{$rec_sTeam[imap_sid]}' and
year(mlog_dtime)='{$thisYear}' and month(mlog_dtime)='{$mon}' ");
An example:
$a = array("name"=>"predte4a");
echo "My name is: $a['name']";
// will echo My name is array()['name']
echo "My name is: {$a['name']}";
//will echo My name is predte4a
And do not forget the quotes in your associative array keys
Related
<?php
$q = "SELECT `Code` FROM `productspecs` GROUP BY `Code` HAVING COUNT(1) > 1";
$r = mysqli_query($conn, $q);
$a = 0;
while ($row = mysqli_fetch_array($r))
{
echo $row['Code'];
$q2 = "SELECT * FROM `productspecs` WHERE `Code`='" . $row['Code'] . "'";
$r2 = mysqli_query($conn, $q2);
$i = 0;
while ($row2 = mysqli_fetch_array($r2))
{
$Mod = $row2['ModificationDate'];
$ModDates[] = DateTime::createFromFormat('d/m/Y', $Mod); // === $ModDates[$i]
$ModDates[$i]['SpecID']=$row2['SpecID'];
$i++;
}
usort($ModDates); // <<< ??
$DeleteIDs[] = $ModDates[0]['SpecID'];
foreach ($ModDates as $ModDate)
{
echo $ModDate->format('d-m-Y');}
unset($ModDates); // unset the array for the next code
echo '</br>';
echo 'Delete: ' . $DeleteIDs[$a];
$a++;
}
?>
Hi I'm trying to Delete specifications from the product database (or at least get a list of ones to delete) where we have duplicates and we want to delete the oldest one.
So here I've 1) found a list of duplicate codes 2) Assigned spec id to each mod date 3) Sorted the mod dates to find the oldest*NOTE 4) Found a list of ids to delete by finding the id assigned to the first of the sorted array. 5) unsets the moddate array for the next set of duplicates
NOTE: I think solving this problem might have something to do with sorting the multidimensional array - this is the part that I'm fairly sure is wrong. If this wasn't a multidimensional array we would at least see the modification dates in order. At this point I COULD just do a search for product code and oldest (first in array) mod date which thinking about it now - would achieve the same result? Does it matter that the primary key will be lost - after all - all I need is to get rid of the product code with the older modification date.. it doesn't matter that we don't have the primary key?
P.S. I did see a post about sorting multi-dimensional arrays Here but I felt I should show you what I was doing in case somebody had a better suggestion?
<?php
$q = "SELECT `Code` FROM `productspecs` GROUP BY `Code` HAVING COUNT(1) > 1";
$r = mysqli_query($conn, $q);
$a = 0;
That $a variable seems useless.
while ($row = mysqli_fetch_array($r)) {
echo $row['Code'];
$q2 = "SELECT * FROM `productspecs` WHERE `Code`='" . $row['Code'] . "'";
$r2 = mysqli_query($conn, $q2);
$i = 0;
while ($row2 = mysqli_fetch_array($r2)) {
$Mod = $row2['ModificationDate'];
$ModDates[] = DateTime::createFromFormat('d/m/Y', $Mod); // === $ModDates[$i]
$ModDates[$i]['SpecID'] = $row2['SpecID'];
$i++;
If $ModDates[] === $ModDates[$i], as you say, then write $ModDates[$i] in both assignments. $ModDates[] === $ModDates[$i]can be wrong, $ModDates[$i] === $ModDates[$i] cannot.
Moreover :
$ModDates[] = ...
$ModDates[$i]['SpecID'] = $row2['SpecID'];
Now, whatever has been assigned to $ModDates[$i] in the first line is gone, it's now an array with only one key : 'SpecId'.
}
usort($ModDates); // <<< ??
What does that comment mean ?
$DeleteIDs[] = $ModDates[0]['SpecID'];
You put only one value from the array into $DeleteIDs. Why ?
foreach ($ModDates as $ModDate) {
echo $ModDate->format('d-m-Y');}
unset($ModDates); // unset the array for the next code
That foreach will iterate only once because the line right above unsets the array it's iterating over.
In case it's a mistake and you in fact wanted to unset $ModDate :
- That will teach you to use variables with names you can differenciate
- That wouldn't want anyway because $ModDate is a copy of an entry of $ModDates, not that entry itself. Unseting it changes nothing in $ModDates.
echo '</br>';
echo 'Delete: ' . $DeleteIDs[$a];
$a++;
}
}
I added the two last curly brackets, I don't know if you pasted wrongly or if you simply forgot to put them in your code.
I am trying to run a query off multiple array variables and display the results in a table.
The user selects 1 or more records, which includes BOL and CONTAINER. These selections are put in their own arrays and they are always an equal amount.
<?php
$bolArray = explode(',', $_POST['BOL']);
$containerArray = explode(',', $_POST['CONTAINER']);
$count = count($bolArray); // to get the total amount in the arrays
I use a FOR loop to separate each value from the 2 arrays:
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
}
Here is the part where I'm stuck and probably where I am messing up.
I need to take each variable from the FOR loop and run query using both variables.
First, I'll start the table:
echo "<table><thead><tr><th>BOL</th><th>Container</th></thead><tbody>";
Here is where I tried a FOREACH loop:
foreach($containerArray as $container) // I am not sure if I am using this FOREACH correctly
{
And now, the query. Please take note of the variables from the first FOR loop:
$preQuery = "SELECT * FROM mainTable WHERE CONTAINER = '".$container."' AND BOL = '".$bol."'";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
I use a WHILE loop with a mysql_fetch_assoc:
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>'
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '<td>'.$preRow[ANOTHER_COLUMN].'</td>';
echo '</tr>'
}
}
echo '</tbody></table>';
?>
The query actually works. Problem is, it only returns 1 record, and it's always the last record. The user could select 4 records, but only the last record is returned in the table.
I tried to use the same query and paste it inside the first FOR loop. I echoed out the query and it displayed the same amount of times as the number of array values, but will only return data for the last record.
I do not understand what I am doing wrong. I just want to display data for each value from the array.
Edit
Here is what the code looks like when I throw the query in the first FOR loop:
echo "<table class='table table-bordered'><thead><tr><th>BOL</th><th>Container</th></tr></thead><tbody>";
for($i = 0; $i < $count; $i++)
{
$bol = $bolArray[$i];
$container = $containerArray[$i];
$preQuery = "SELECT BOL_NUMBER, CONTAINER_NUMBER FROM `intermodal_main_view` WHERE BOL_NUMBER = '". $bol ."' AND CONTAINER_NUMBER = '".$container."'";
$preRes = mysql_query($preQuery) or die();
$preNum = mysql_num_rows($preRes);
while($preRow = mysql_fetch_assoc($preRes))
{
echo '<tr>';
echo '<td>'.$preRow[BOL_NUMBER].'</td>';
echo '<td>'.$preRow[CONTAINER_NUMBER].'</td>';
echo '</tr>';
}
}
echo "</tbody></table>";
I think you can use "IN" if your POST vars are comma separated.
$preQuery = "
SELECT * FROM mainTable
WHERE CONTAINER IN ($_POST['CONTAINER'])
AND BOL IN ($_POST['BOL'])
";
$preRes = mysql_query($preQuery) or die(mysql_error());
$preNum = mysql_num_rows($preRes);
Then go to your while loop....
This would omit the need for creating an array and looping it.
Also, you need to switch to PDO for your query, and switch to parameter binding. It will take all of an hour to learn.
Edit : I need it to do only in Array Sort, As i am using procedure and sending it into json,
Here is my Table Structure,
SQL Fiddle
I want to display as
alpha london
alpha newyork
beta delhi
beta sydney
I mean, the second coloumn (name) should be in Ascending Order and the third coloumn (place) should be in Descending Order.
How i want is
alpha london
alpha newyowk
beta delhi
beta sydney
The Name should be in Asc Order and then to the right, the Place should be in Desc Order
What i have tried so far is
How can i do this ??
<?php
include ('conn.php');
$sql="SELECT * FROM test";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
while($rows=mysql_fetch_array($result))
{
foreach($result as $k=>$v)
{
echo $k;
}
}
?>
It displays the result as Invalid argument supplied to for each. What is the mistake i am doing and how can achieve my output
To fix the sorting, just add ORDER BY name, place
Then there's several more issues preventing this from working:
You shouldn't call mysql_fetch_array outside the loop (this would discard the first row, alpha london in your example).
You need to iterate over $rows, not $result (this is where the "invalid argument" error is coming from).
You're not echoing the value; only the key. So you wouldn't be displaying the name and place at all; only the words "name" and "place".
You might want to do something like this to fix these:
<?php
include('conn.php');
$sql = "SELECT * FROM test ORDER BY name, place";
$result = mysql_query($sql);
while ($rows = mysql_fetch_array($result)) {
foreach ($rows as $k => $v) {
echo "$k is $v. ";
}
echo "<br/>";
}
?>
So why don't you do an order in your query itself like
SELECT * FROM test order by name;
You can do this only modifying query.
Use this query:
SELECT * FROM test ORDER BY name ASC, place DESC
For your error, you are using wrong variable as foreach.
Replace this -
foreach($result as $k=>$v)
{
echo $k;
}
with this -
foreach($rows as $k=>$v)
{
echo $k;
}
Buy why are using foreach inside while loop. You can get your values like -
while($rows = mysql_fetch_array($result)) {
echo $rows['name'].' '.$rows['place'].'<br/>';
}
and don't use mysql_* function. Use instead mysqli_*
And for your expected output, try using following query -
SELECT * FROM `test` order by name asc, place desc
This is the kind of thing you can fix using array_multisort.
Try the below example (which I have not tested yet, but ought to work)
<?php
include ('conn.php');
$sql="SELECT * FROM test";
$result=mysql_query($sql);
$totals = array();
$row = array();
$places = array();
while($row=mysql_fetch_array($result)){
$totals[] = $row
$names[] = $row['name'];
$places[] = $row['place'];
}
array_multisort( $names, SORT_ASC, $places, SORT_DESC, $totals );
// now you can use $totals, which is sorted as you want
print_r( $totals );
I need to print a wine list from a database.
I need to print at first a categorie and after all the items that are inside. Thats the order. And i have multiple categorie. So at the end the result will be categorie1, many items, categorie2 many items...
This is the code that i write from now: I think that my problem is to print items according to the id of the alcool_categorie !!
$q_vine = "SELECT * FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
$q_bouteille = "SELECT * FROM alcool_item where ALCNID = '$alid'";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
for($i = 0; $i < $n_vine; $i++){
echo mysql_result($r_vine,$i,'named').'<br/><br/>';
for($z = 0; $k < $n_bouteille; $k++){
echo mysql_result($r_bouteille,$k,'name').'<br/>';
}
}
I think it's best to use a "JOIN" in your query and then order the rows in the way you want them to be ordered, then you'll only need one loop. While running the loop you compare the category name with the previous category name and if it changes display the category name.
Example
$sql = "SELECT categoryName, bottleName FROM category INNER JOIN bottle ON category.categoryId = bottle.categoryId ORDER BY category.categoryId";
$result = mysql_query($sql,$connection);
$categoryName = ''; //just to make sure the first time the Category is named
while ($row = mysql_fetch_assoc($result)) {
if($categoryName != row['categoryName']){
$categoryName = row['categoryName'];
echo '<h1>'.$categoryName.'</h1>';
}
echo row['bottleName'].'<br/>';
}
Try this after correctly giving the category id field name in the query and inside the first while loop.
$q_vine = "SELECT id, named FROM alcool_categorie ";
$r_vine = mysql_query($q_vine,$connection);
$n_vine = mysql_num_rows($r_vine);
while ($row = mysql_fetch_assoc($r_vine)) {
$categories[$row['id']] = $row;
}
$q_bouteille = "SELECT name, ALCNID FROM alcool_item ";
$r_bouteille = mysql_query($q_bouteille,$connection);
$n_bouteille = mysql_num_rows($r_bouteille);
while ($row = mysql_fetch_assoc($r_bouteille)) {
$items[$row['ALCNID']] = $row;
}
foreach ($categories as $category_id=>$category) {
echo "<ul><li>{$category['named']}<ul>";
foreach ($items[$category_id] as $item) {
echo "<li>{$item['name']}</li>";
}
echo "</ul></li></ul>";
}
You will want to look into PHP's foreach construct. Foreach loops through an entire array of results, for each element inside the array, it extracts its value and optionally also its key. This will not require the use of mysql_num_rows.
Instead of calling mysql_result, you could use mysql_fetch_assoc to get a row's value from your mysql_query. The row's To get all values, you can incorporate this into a loop even. If you do the latter, you can create your own array of key/value pairs and use this inside a foreach construct.
Also note that the use of mysql is outdated, you will want to use mysqli now, which is very similar to mysql.
I need to fill a multidimensional array and here is my code I have so far for it.
while($num > $i)
{
$default[$i]=0;
$defaultcounter=0;
$default2[$i]=0;
$default3[$i]=0;
$query="Select * from `issues` WHERE `app`='" . $applist[$i] . "'" . "AND `startmonth`='". $month ."' ORDER BY `id` ASC";
$result=mysql_query($query);
while($row = mysql_fetch_array($result))
{
$downtime[$i]+=$row['duration'];
$default2[$i]++; //Number of Incidents Variable
$defaultcouinter++;
$times[$i] = array();
$times[$i][$defaultcounter[$i]]=$row['startday'].$row['starttime'];
}
$appavail[$i]=100 -(ceil($downtime[$i] * 100 / $totaltime));
$default[$i] = (ceil($downtime[$i] / $defaultcounter));
$i++;
}
Apparently I am not doing the array assignment correct. I need to to have my number of rows counted with the $i variable outside of my while then inside the while the defaultcounter will be keeping up with the column. I tried just doing a $time[$i][defaultcounter] and it didn't like it. Whats the proper syntax for assigning a multidimensional array?
Thanks
$times[$i] = array() should be out (before) the while loop unless you want it redefining $times as an empty array in each iteration (reseting values). Apart from that, you're assigning the values correct, although it looks a bit odd (not sure what you want to achieve there). This are the general formulas, should give you an idea:
$array[] = $subarray;
$array[$subarray] = $value;
$array[$subarray][] = $value;
$array[$subarray][$i] = $value;