Unexpected output when comparing database column to variable - php

I have code which retrieves information about players from a MySQL database. I want to apply a special case to the HTML output if their ranking changes. I want it to look like this: http://i27.tinypic.com/f406tz.png
But i cant get it to be like i want, instead it prints the rank on every row:
$old_rank = '';
while ($g = mysql_fetch_object($q)) {
if ($g->rankname != $old_rank) {
echo "<tr><td>$g->rankname</td>\n";
$old_rank = "<tr><td> </td>\n";
}
echo " <td>$g->name</td></tr>\n";
}
What I want:
<tr>
<td>One</td>
<td>Kraven the Hunter</td>
</tr>
<tr>
<td> </td>
<td>Kull the Conqueror</td>
</tr>
<tr>
<td> </td>
<td>Zazi The Beast</td>
</tr>
<tr>
<td>Vice-leader</td>
<td>Igos du Ikana</td>
</tr>
<tr>
<td> </td>
<td>Saint Sinner</td>
</tr>
<tr>
<td> </td>
<td>Midvalley the Hornfreak</td>
</tr>.......................
What I get:
<tr><td>One</td>
<td>Tester</td></tr>
<tr><td>One</td>
<td>Kraven the Hunter</td></tr>
<tr><td>One</td>
<td>Kull the Conqueror</td></tr>
<tr><td>One</td>
<td>Zazi The Beast</td></tr>
<tr><td>Vice-Leader</td>
<td>Midvalley the Hornfreak</td></tr>
<tr><td>Vice-Leader</td>
<td>Saint Sinner
</td></tr>
<tr><td>Vice-Leader</td>
<td>Igos du Ikana</td></tr>

$old_rank is never equal to $g->rankname because the way you are setting $old_rank, it will contain HTML tags, and the $g->rankname that you get from the DB will never have HTML tags.
Try changing your if statement to something like this:
if ($g->rankname != $old_rank) {
echo "<tr><td>$g->rankname</td>\n";
$old_rank = $g->rankname;
} else {
echo "<tr><td> </td>\n";
}
It prints the rank name if it's a new rank name, else it prints empty space.

The following (notwithstanding typos) separates out the display logic from the database loop. This has the advantages:
- You don't need to depend on the order of the results returned
- You don't need to maintain dodgy logic (like 'old_rank')
- You can display them more nicely (with a rowspan for repeated ranks
I believe the total code is more compact too.
// fill ranks array
$ranks = array();
while ( $g = mysql_fetch_object($q) ) {
if ( !in_array($g->rankname, $ranks) ) {
$ranks[htmlentities($g->rankname)] = array();
}
$ranks[$g->rankname][] = htmlentities($g->name);
}
// do other program logic here
// end of program
?>
<!-- display the page -->
<table>
<tr>
<th>Rank</th><th>Users</th>
</tr>
<?php foreach($ranks as $rankName => $userList): ?>
<tr>
<td rowspan="<?php echo (string)sizeof($userList); ?>">
<?php echo $rankName; ?>
</td>
<td> <?php echo implode('</td></tr><tr><td>', $userList); ?> </td>
</tr>
<?php endforeach; ?>
</table>

I prefer breaking things up a bit more than that. Keeping things separate makes it easier to modify. This should work.
$old_rank = '';
while ($g = mysql_fetch_object($q)) {
echo '<tr>' . "\n";
echo '<td>';
if ($g->rankname != $old_rank) {
$old_rank = $g->rankname;
echo $old_rank;
} else {
echo ' ';
}
echo '</td>';
echo '<td>' . $g->name . '</td>' . "\n";
echo '</tr>' . "\n";
}

Related

Quantity of every product outputs like 123. How can i put this in a table row table data

I am having a problem to convert my $quantity_total which is as example (113) from 3 different products.
I want it to be in a table like below.
I have been trying to use chunk_split and explode but if i was able to succeed in that. I wouldn't be able to make it dynamic.
<table>
<tr>
<th>Quantity</th>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>1</td>
</tr>
<tr>
<td>3</td>
</tr>
</table>
$total=0;
$item_count=0;
$arr = array();
$quantity_all = '';
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$arr[] = $row;
$_SESSION['cart-checkout'] = $arr;
$quantity=$_SESSION['cart'][$id]['quantity'];
$quantity_all .=$quantity;
$sub_total=$price*$quantity;
echo "<div class='cart-row'>";
echo "<div class='col-md-8'>";
echo "<div class='product-name m-b-10px'><h4>{$name}</h4></div>";
echo $quantity>1 ? "<div>{$quantity} items</div>" : "<div>{$quantity} item</div>";
echo "</div>";
echo "<div class='col-md-4'>";
echo "<h4>$" . number_format($price, 2, '.', ',') . "</h4>";
echo "</div>";
echo "</div>";
$item_count += $quantity;
$total+=$sub_total;
$_SESSION['total'] = $total;
$_SESSION['item-count'] = $item_count;
}
$_SESSION['quantity-all'] = $quantity_all;
Is this possible? And i need it to be dynamic. So if it were 10 different quantities. It would make 10 table rows.
I hope someone can help me, would really appreciate it a lot! It's the last thing to finish my e-commerce webshop.
As mentioned in my comment, I don't think this is good solution... but the function you're looking for is str_split. https://stackoverflow.com/a/9814389/296555
http://sandbox.onlinephpfunctions.com/code/0bbee53cafafc0d5e8954e07d0abc2c86c6c89a8
<?php
$rows = '156165165489465131';
echo '<table>';
echo '<tr><th>Quantity</th></tr>';
foreach (str_split($rows) as $row) {
echo "<tr><td>$row</td></tr>";
}
echo '</table>';
I dont know if this Is what you want, but you can try something like:
<table>
<tr>
<td>Quantity</td>
</tr>
<?php
$characters = str_split( (string) $quantity_total);
foreach($characters as $char){
echo "
<tr>
<td> $char </td>
</tr>
";
}
?>
</table>

How to echo a table in two piece separated code in PHP?

Now I wish to construct a list of tables under nested while loop and if-else condition with PHP, the format of the code is as below:
while(){
if (){
..... // extract the data
while(){
construct a table using the data extracted above
}
}
elseif (){
..... // extract the data
while(){
construct a table using the data extracted above
}
}
}
Specifically, in the inner while loop the code is:
while ( $chat = mysqli_fetch_assoc($chatQ))
{
echo
"<table class='table table-hover' >"
."<td>"
.$conver['sender_name']."\t".$chat['sender']."\t".$chat['send_time']."\t".$chat['content']
."</td>"
."<td>"
."<form id='join' action='group_chat.php' method ='POST' accept-charset='UTF-8'>"
// post the group id
."<input type='hidden' name='group_id' id='group_id' value=".$conver['sender_id']."/>"
."<button class='btn btn-default' type='submit'>Enter</button>"
."</form>"
."</td>"
."</table>";
}
But the result is very ugly:
The problem is that the Enter button is associated with each message. But what I want is that after displaying all the messages, there is a Enter button which can direct to the specific group. But I don't know how to separate the code. Could you please do me a favor? Thanks in advance!
You can do something like this:
<?php
$counter = 0;
echo '
<form>
<table>';
while ( $chat = mysqli_fetch_assoc($chatQ)){
$counter++;
echo '
<tr>
<td>
group_id_'.$counter.'
</td>
<td>
<input name="group_id_'.$counter.'" value="'.$conver['sender_id'].'">
</td>
</tr>';
}
echo '
<tr>
<td colspan="2">
<button type="submit">Enter</button>
</td>
</tr>
</table>
</form>';
?>
Also you dont have to limit yourself to echo everything in order by setting variables. See example below:
<?php
$counter = 0;
$data = NULL;
while ( $chat = mysqli_fetch_assoc($chatQ)){
$counter++;
$data .='
<tr>
<td>
group_id_'.$counter.'
</td>
<td>
<input name="group_id_'.$counter.'" value="'.$conver['sender_id'].'">
</td>
</tr>';
}
echo '
<form>
<table>'.$data.'
<tr>
<td colspan="2">
<button type="submit">Enter</button>
</td>
</tr>
</table>
</form>';
?>

Print rows in html table with for loop [duplicate]

This question already has answers here:
How to float 3 divs side by side using CSS?
(16 answers)
Closed 6 years ago.
My table has rows that's looped in a non-specific length because the values in the cells may be added or removed anytime. Anyway, here's the code:
<?php
$i = 1;
foreach($items as $item => $itemValue) {
if ($itemValue['item_id'] == $parentItemValue['id']) {
if (fmod($i,7)) echo '<tr>';
echo '<td class="inner-td"><input type="checkbox" id="itemId">'.$itemValue['item'].'</td>';
if (!fmod($i,7)) echo '</tr>';
$i++;
}
?>
The above code displays this:
I also tried if (!fmod($i,7)) echo '<tr>' and if (!fmod($i,8)) echo '</tr>' and gives me this:
Also, if (!fmod($i,10)) echo '<tr>' and if (!fmod($i,11)) echo '</tr>' and gives me this:
I want my table to look like this:
Is there a way that the cells will fill in the entire row before making a new one?
You can try this. Just change the $maxcol value for how many columns you want.
<?php
$tmp = array('test1','test2','test3','test4');
echo '<table border="1">';
$x = 0;
$maxcol = 2; // Max column
foreach($tmp as $i=>$v)
{
echo $x === 0 ? '<tr>' : '';
echo '<td>'.$v.'</td>';
echo $x === ($maxcol-1) ? '</tr>' : '';
$x++;
$x = $x == $maxcol ? 0 : $x;
}
echo '</table>';
?>
Try to follow this structure.
Note that all fields and rows are made up by myself.
<tbody>
<?php
require_once ('connectionWithDB.php');
$table = "members";
$array = $admin_query->viewTableData($table);
foreach ($array as $row){
print_r($array);
?>
<tr>
<td> <?php $row[member_id] ?> </td>
<td> <?php $row[member_password] ?> </td>
<td> <?php $row[member_first_name] ?> </td>
<td> <?php $row[member_last_name] ?> </td>
<td> <?php $row[member_DOB] ?> </td>
<td> <?php $row[member_address] ?> </td>
<td> <?php $row[member_email] ?> </td>
<td> <?php $row[member_phone] ?> </td>
<td> <?php $row[member_gender] ?> </td>
</tr>
</tbody>

How do I display a query in PHP table

My code
<?php
include('ConnectToDb.php');
$query = "SELECT * FROM News WHERE NewsFlag = 1 ORDER BY PostDate DESC";
$arrCount = -1;
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$ID=$row['ID'];
$PostDate = $row['PostDate'];
$NewsHeader = stripslashes($row['NewsHeader'])
;
$NewsStart = stripslashes($row['NewsStart'])
;
echo "<hr>";
echo "<div>". date('j F Y',strtotime($PostDate)). "</div>";
echo "<p>";
$news_id = strval(sprintf("%1$04d",$ID));
$array = scanImageFolder("newsImages/newsThumbs",$news_id);
if(count($array)>0) {
echo "<img src='". $array[0]. "' alt='' />";
}
echo "<h2 style='text-align:center'><u><a href='latestnews_full.php?ID=$ID'>". $NewsHeader. "</a></u></h2>";
echo "<div style='text-align:left'><h3>";
echo $NewsStart. " ......<a href='latestnews_full.php?ID=$ID'>(more)</a><br />";
echo "<div style='text-align:center'>";
echo "</div>";
echo "</h3></div>";
}
?>
displays my data nicely on four lines with date at the top, then a picture, title and then description.
However, I want to display the data as a table like this
<table style="width: 100%">
<tr>
<td colspan="2">postDate here</td>
</tr>
<tr>
<td rowspan="2">picture here</td>
<td>newsHeader here</td>
</tr>
<tr>
<td>newsStart here</td>
</tr>
</table>
I'm not sure how to echo the table cells correctly and all of my attempts so far have resulted in a white page. Could anyone please enlighten me?
I'd suggest you to make your logic separated from your presentable part. Close the PHP tag once you are ready fetching the results, assigning var's etc, then:
<table style="width: 100%">
<?php
//yourcode
//...
//...
$NewsStart = stripslashes($row['NewsStart']);
$news_id = strval(sprintf("%1$04d",$ID));
$array = scanImageFolder("newsImages/newsThumbs",$news_id);
?>
<tr>
<td colspan="2"><?= date('j F Y',strtotime($PostDate)) ?></td>
</tr>
<tr>
<?php
if(count($array)>0) {
?>
<td rowspan="2"><img src='<?= $array[0] ?>' alt='' /></td>
<?php } ?>
<td><?= $NewsHeader ?></td>
</tr>
<tr>
<td><?= $NewsStart ?> </td>
</tr>
<?php } ?>
</table>
However, it's again not so clear, and I would suggest using a template engine. If you want I can post a code with assigning vars to Smarty and output your presentation in Smarty template

Sorting a HTML table with PHP after input from database

I'm creating a HTML table with data-rows from a MySQL database and some calculated values, like this:
<?php
$connection = mysql_connect('localhost','root','') or die('Connection failed!');
mysql_select_db('MyDB', $connection);
$result = mysql_query('SELECT * FROM DB_TABLE');
?>
<table>
<tr>
<th scope="col">Heading 1</th>
<th scope="col">Tariefplan</th>
<th scope="col">Abonnementskost</th>
<th scope="col">Maandelijkse korting</th>
<th scope="col">Contractduur</th>
<th scope="col">Inbegrepen in bundel</th>
<th scope="col">Tarieven buiten bundel</th>
<th scope="col"></th>
<th scope="col">Bereken minuten</th>
<th scope="col">Bereken SMS'en</th>
<th scope="col">Bereken MB's</th>
<th scope="col"></th>
<th scope="col">Totale prijs normaal</th>
<th scope="col">Totale prijs promotie</th>
<th scope="col">Totale prijs contract</th>
</tr>
<?php
while ($data = mysql_fetch_assoc($result)) {
?>
<tr>
<th scope="row"><?php echo $data['provider']; ?></th>
<td><?php echo $data['planname']; ?></td>
<td>€ <?php echo $data['price_normal']; ?> per maand<br />
<sub>gedurende <?php echo ($data['contract_duration']-$data['promo_duration']); ?> maanden</sub></td>
<td>- € <?php echo $data['promo_discount']; ?> per maand<br />
<sub>gedurende <?php echo $data['promo_duration']; ?> maanden</sub><br />
<sub>promotie geldig tot <?php echo $data['promo_valid']; ?></sub></td>
<td><?php echo $data['contract_duration']; ?> maanden</td>
<td>
<ul>
<li><?php echo $data['included_min']; ?> minuten</li>
<li><?php echo $data['included_sms']; ?> SMS'en</li>
<li><?php echo $data['included_mb']; ?> MB's</li>
<li>€ <?php echo $data['included_value']; ?> belwaarde</li>
</ul>
</td>
<td>
<ul>
<li>€ <?php echo $data['price_min']; ?> per minuut</li>
<li>€ <?php echo $data['price_sms']; ?> per SMS</li>
<li>€ <?php echo $data['price_mb']; ?> per MB</li>
</ul>
</td>
<td></td>
<td>
<?php
if ($_POST['used_min'] <= $data['included_min']) {
$calc_min = 0;
}
else {
$calc_min = ($_POST['used_min'] - $data['included_min']) * $data['price_min'];
}
echo '€ ' . $calc_min;
?>
</td>
<td>
<?php
if ($_POST['used_sms'] <= $data['included_sms']) {
$calc_sms = 0;
}
else {
$calc_sms = ($_POST['used_sms'] - $data['included_sms']) * $data['price_sms'];
}
echo '€ ' . $calc_sms;
?>
</td>
<td>
<?php
if ($_POST['used_mb'] <= $data['included_mb']) {
$calc_mb = 0;
}
else {
$calc_mb = ($_POST['used_mb'] - $data['included_mb']) * $data['price_mb'];
}
echo '€ ' . $calc_mb;
?>
</td>
<td></td>
<td>
<?php
$used_total = ($calc_min + $calc_sms + $calc_mb);
if ($data['included_value'] > $used_total) {
$total_price_normal = $data['price_normal'];
}
else {
$total_price_normal = ($data['price_normal'] + $used_total);
}
echo '€ ' . $total_price_normal . ' per maand';
?>
</td>
<td>
<?php
$total_price_discount = ($total_price_normal - $data['promo_discount']);
echo '€ ' . $total_price_discount . ' per maand';
?>
</td>
<td>
<?php
$total_price_contract = ($total_price_normal * ($data['contract_duration']-$data['promo_duration'])) + ($total_price_discount * $data['promo_duration']);
echo '€ ' . $total_price_contract . ' per maand ' . $data['contract_duration'] . ' na maanden';
?>
</td>
</tr>
<?php } ?>
</table>
The last column in the table is a variable value witch calculates a total amount. This is NOT listed in the database.
I want to output this table to an browserpage and let is be sort on that last column.
With PHP sort() or asort() function that doesn't work fine.
Does someone have a solution?
Do the calculation in the SQL query, and let the database handle the sorting
You have calculate the values first and then create the table. Or use some javascript. So you have to go trough $result and put calculated values in array and after that you may sort and print to table with values, sorted by that last value.
I think it would be better if you first iterate through your results, do your calculations and put everything into an array. Then you can sort the array like you want with any PHP function and output it. The best thing with this approach is, you will have a cleaner output of the table because do all calculations and stuff away from the HTML output ;)
The other idea is, that you do it like you do above and then use a tablesorter in i.e. Javascript/jQuery to sort your rows afterwards.
It is possible but it might be tricky to do this using PHP. For a quick fix you could try this jquery solution which does what you want and get you up and running very quickly.
http://tablesorter.com/docs/#Demo
With PHP sort() or asort() function that doesn't work fine.
if you meant it sort like this 1, 10, 12, 2 you can use natsort();.

Categories