Way to make row count be 0 if no date match and second,third,etc while loop row counts - mysql

<?php
if($result = $db->query("SELECT * FROM table")) {
if($count = $result->num_rows) {
echo '<p class="lead">Number of callbacks for today is: ', $count, '</p>';
while($row = $result->fetch_assoc()) {
if ( $row['field'] == date("Y-m-d") ) {
echo $row['otherfield'], '<br>';
}else{
echo "Nothing", '' , '<br>';
}
}
}
}
?>
I have a simple field date verses server date test used in conjunction with a while loop to bring up any callbacks each day if they are due. My issue is that the row will show a nothing for every row so I'll have twenty(example) rows of the text 'nothing' display. I know I could simply place everything in a function and then use the if/else statement outside of the function to display callbacks or not display callbacks....but is there a way to reset the loop counter to zero if the first if/else test fails? I tried placing the $count = 0; in the second else clause but this did not work.

Related

How to echo specific mysql data in specific places using php?

If the 'SELECT' statement is used to select data from a database then how do we echo specific rows to specific places on a page using php?
To explain this better - I am trying to SELECT * ALL FROM a table but to echo multiple rows to particular places on the html page using php.
So, imagine that my entire mark up and css has 20 thumbnails on a page and each thumbnail has data and an image that is unique to each thumbnail....do I have to replicate the below 20 times?
I am thinking that the best way to do this (which is probably completely wrong) is to use this statement
SELECT * FROM name_of_table WHERE ID = 4 >>> i.e. where I'd like that specific data echoed....
So, if I have 20 thumbnails do I do this 20 times?
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID = 4;")
or die(mysql_error());
Print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Name:</th> <td>".$info['name'] . "</td> ";
Print "<th>Product:</th> <td>".$info['product_name'] . " </td></tr>";
}
Print "</table>";
?>
And, rinse and repeat but I change the below statement each time for each thumbnail (each thumbnail has unique data that comes from each row on the MySQL)
SELECT * FROM name_of_table WHERE ID = 4;
What is the best way of doing this?
Thanks!
Simple example.. First get the data with wanted ID:s. Create function for data request.
<?php
// Connects to your Database
mysql_connect("localhost", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());
$data = mysql_query("SELECT * FROM name_of_table WHERE ID IN (2,3,4,5,6);")
or die(mysql_error());
// This holds all data rows
$data_array = array();
while($info = mysql_fetch_array( $data ))
$data_array[] = $data;
// Function for rendering data to html
function getItemHtml($id) {
$html = "";
foreach($data_array as $row) {
if ($row['ID'] == $id) {
$html = "<td>" . $row['title'] . "</td>";
// etc.. create item html here
break;
}
}
return $html;
}
// To create one item just call this with item id.
echo getItemHtml(4);
?>

Save SQL result to variable

Is it possible to save SQL result in variable and then use that to echo data anywhere on my site.
for example
$result=mysqli_query("SELECT * FROM table");
and then use that variable to show that data anywhere else on site and even repeat it in some loop
$show=mysqli_fetch_assoc($result)
I tried that in for while loop and it echo my result only once.
my full code
$result=mysqli_query("SELECT * FROM table");
$r=mysqli_query("SELECT * FROM table2");
while($x=mysqli_fetch_assoc($r))
{
echo $x["ID"];
while( $show=mysqli_fetch_assoc($result))
{echo $show["ID"];}
}
Make a $table1_array and a $table2_array and instead of echo $x use $table1_array[] = $x. Since the table2 - select needs nothing from table1 you should read it only once. Make no inner loop, make two separate loops.
EDIT:
to clarify:
$result=mysqli_query("SELECT * FROM table");
$table_array = array();
while( $show=mysqli_fetch_assoc($result)){
$table_array[] = $show;
}
$r=mysqli_query("SELECT * FROM table2");
while($x=mysqli_fetch_assoc($r))
{
echo $x["ID"];
foreach($table_array as $show){
echo $show["ID"];
}
}

Show missing dates inside loop even if they don't exist inside MYSQL

I have following mysql query
SELECT count(order_id), date FROM tbl_order WHERE campaign_status = 'In Progress' or campaign_status = 'Pending' GROUP BY DATE_FORMAT(date,'%d %b %y')
and then following loop
<?php do { ?>
['<?php echo $row_chartData['date']; ?>', <?php echo $row_chartData['count(order_id)']; ?>],
<?php } while ($row_chartData = mysql_fetch_assoc($chartData)) ?>
this loop is used to create data for my chart. Now the problem is that there are certain days that users dont make orders in my store so those dates are not stored inside database, so when I loop trough those dates are not showed in above results and inside the chart.
The question I have, is there any way to show those missing dates in loop above even if they dont exist inside mysql database.
Thanks for help.
Well, in this case, create a temporary array based on the date range, e.g. if you want to show the graph from May 1, to May 31.
Loop from 1 to 30,
set $data[i] = 0;
Now loop through the db records and set
$data['date'] = $row['count']
Yes.
Firstly make $row_chartData as array instead of a mysql_result.
1) find the min date in the range or whichever date you want to start with
function _getDate($row) {
return $row['date'];
}
$dates = array_map('_getDate', $row_chartData);
$minDate = min($dates);
2) find the max date in the range or whichever date you want to end with
$maxDate = min($dates);
$dateRangeArray = array();
$date = $minDate;
while($date < $maxDate) {
$dateRangeArray[] = $date;
$date = date('Y-m-d', strtotime($date . ' +1 day'));
}
3) make the key of each element in your $row_chartdata array be the value of the date index
foreach($row_chartData as $key => $row) {
$row_chartData[$row['date']] = $row;
unset($row_chartData[$key]);
}
4) iterate over each of the days in the range and match that date to the index in your $row_chartdata array
foreach($dateRangeArray as $date) {
if(isset($row_chartData[$date])) {
//do whatever
}
}

nested while loop mysql_fetch_array

I have a set of nested while loops to compare to mysql queries to each other. Here is the code:
while($row = mysql_fetch_array($resultbat))
{
$drafted = 0;
while($crossedRow = mysql_fetch_array($crossedAnswer))
{
if($row['NAME'] == $crossedRow['name'])
{
$drafted = 1;
}
else
{
$drafted = 0;
}
}
if ($drafted == 1)
{
echo "<tr class='drafted' id='" . $row['NAME'] . "'>";
}
else if($n&1)
{
echo "<tr id='" . $row['NAME'] . "'>";
}else
{
echo "<tr class='alt' id='" . $row['NAME'] . "'>";
}
...}
In the $resultbat is a list of all players, and in the $crossedAnswer is a list of a few players that should be marked. For each player I want to see if they are in the $crossedAnswer list of players. If they are I want to mark the class of that html element to drafted.
Thanks in advance.
I think you'll either need to:
open the cursor on $crossedAnswer for each row from $resultbat (open it at the beginning of each loop through, and close it at the end, which effectively runs that query for each for in resultbat), or
fetch all of the rows from the $crossedAnswer resultset into a structure, and look through that structure for each row from $resultbat, (to avoid running the same query multiple times against the database), or
ensure that both $resultbat and $crossedAnswer are ordered by key value, and do just a single loop; open both cursors, fetch a row from each, and then compare the key values to determine which resultset is "behind", and which one to fetch from (this is more efficient, but is more complicated code to write and test), or
if these resultsets are from the same MySQL server, rewrite this as a single query, and let MySQL do the work of joining the rows together, and process just a single resultset.
Personally, I would opt for the last. I would let MySQL do the join, get a single resultset back, and a single loop.
The query to get the resultset would be of the form:
SELECT b.*
, IF(a.name IS NOT NULL,1,0) AS drafted
FROM (
query_for_$resultbat
) b
LEFT
JOIN (
query_for_$crossedAnswer
) a
ON b.name = a.name
Note that if a matching row is found in a, then the drafted column will return a 1, otherwise, it will return a 0.
The code to handle this resultset, based on the original code could be something like this:
while($row = mysql_fetch_array($result))
{
$class = "";
if($row['drafted'] == 1
{
$class = "class='drafted' ";
}
else if($n&1)
{
$class = "";
}
else
{
$class = "class='alt' ";
}
echo "<tr " . $class . " id='" . $row['NAME'] . "'>";
...
}

PHP/ARRAY/HTML TABLE -- How come this repeats the same thing across the whole <td>?

Im trying to turn an array of friends names: $friends['name'] from the Facebook Graph API into a table with 4 columns across with one persons name in each box.
The problem:
I have it making a table and putting peoples names in the cells of the table, however, it repeats each persons name across all 4 in a row instead of putting a unique name in each box. However the next row starts with a new name.
I would greatly appreaciate anybody who can help point out where Ive gone wrong and help me correct it:
<?
$friends_url = "https://graph.facebook.com/".$user_id."/friends?access_token=".$access_token;
$friends_json = file_get_contents($friends_url);
$friends_data = json_decode($friends_json, true);
$friends_total = count($friends_data['data']);
$cols = 4;
for ($i = 0; $i < $friends_total; $i++)
{
$friends = $friends_data['data'][$i];
echo "<tr>";
for ($c=0; $c<$cols; $c++)
{
$n = $i+$c;
if ( $n < $friends_total)
{
echo "<td>".$friends['name']."</td>";
}
else
{
echo "<td></td>";
}
}
echo "</tr>";
$i += ($c-1);
}
?>
Because you're looping 4 times for each friend and your loop counter for 'columns' is inside that loop, try something more like this:
$cols = 4;
$current_col = 0;
echo "<tr>";
foreach ($friends_data['data'] as $friend)
{
echo "<td>".$friend['name']."</td>";
if (($current_col++)%$cols == 0){
echo "</tr><tr>";
}
}
while (($current_col++)%$col !=0){
echo "<td> </td>";
}
echo "</tr>";
This loops through all the friends, keeping a counter of how many have been printed. After 4 (/or whatever $cols is set to) it spits out a new row
When the friends are all printed out, it starts a new loop to fill in the end of the last row with empty cells, then ends the row