PHP while loop dynamic rowspan - php

Consider a table for example
using these table I just wanted to print a table like these by adding rowspan to item id 1002.
Here is my PHP code
$temp_val = '';
$counter = 1;
$sql_sel = mysqli_query($con,"select * from item_table");
while($res_sel = mysqli_fetch_array($sql_sel)){
if($temp_val == $res_sel['item_id']){
$counter++;
echo "<tr></tr>";
}
else{
echo "<tr><td rowspan='".$counter."'>".$res_sel['item_id']."</td></tr>";
}
$temp_val = $res_sel['item_id'];
}
echo "</table>";
it's not correct, it's adding rowspan to item id 1003

You can't do like this because when you create the first row then you have to decide how much will this column can span so you have to get the count of the similar ids first to achieve it. I am just giving you and idea how it can work with and array like you database provides.
<?php
// Array comming from database
$databaseValues = [
[
'item_id'=>'1001',
'item_color'=>'black',
],
[
'item_id'=>'1002',
'item_color'=>'blue',
],
[
'item_id'=>'1002',
'item_color'=>'green',
],
[
'item_id'=>'1003',
'item_color'=>'red',
]
];
// Creating an array as per the need for the table
$arrayForTable = [];
foreach ($databaseValues as $databaseValue) {
$temp = [];
$temp['item_color'] = $databaseValue['item_color'];
if(!isset($arrayForTable[$databaseValue['item_id']])){
$arrayForTable[$databaseValue['item_id']] = [];
}
$arrayForTable[$databaseValue['item_id']][] = $temp;
}
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<table border="1">
<?php foreach ($arrayForTable as $id=>$values) :
foreach ($values as $key=>$value) :?>
<tr>
<?php if($key == 0) :?>
<td rowspan="<?= count($values)?>"><?= $id?></td>
<?php endif;?>
<td><?= $value['item_color']?></td>
</tr>
<?php endforeach;
endforeach; ?>
</table>
</body>
</html>
Hope this will be helpfull for you

You should switch the code inside else and if statement

Related

Need help in creating simple ledger from mysql debt & credit tables?

How to create below customer ledger using above tables. Ledger should be ORDER by Date as i did in below in Ms word below. Please help(Using PHP) i tried inner join but nothing fruitful date make it more difficult for me.
to print the table it can be something similar to follow using the array prepared as final array
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
</head>
<body>
<h1>Customer Ledger(<?php echo $rearrangedFinalData[0]['customer'] ?>)</h1>
<table>
<tr>
<td>Date</td>
<td>Invoice No</td>
<td>Debit</td>
<td>Credit</td>
<td>Balance</td>
</tr>
<?php
//initialize balance as per your requirement
$balance = 0;
foreach($rearrangedFinalData AS $row) {
?>
<tr>
<td><?php echo $row['date'] ?></td>
<td><?php echo $row['invoice'] ?></td>
<td><?php echo $row['debit'] > 0 ? $row['debit'] : '' ?></td>
<td><?php echo $row['credit'] > 0 ? $row['credit'] : '' ?></td>
<td><?php echo $balance = ($balance + $row['debit'] - $row['credit']) ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
<?php
$CONNECTION = mysqli_connect('localhost','root','','laravel');
$debitTable = 'debt';
$creditTable = 'credit';
$finalData = array();
// get debt data
$queryOfDebt = mysqli_query($CONNECTION,"select * from ".$debitTable." order by Db_date");
while($row = mysqli_fetch_assoc($queryOfDebt)) {
$finalData[$row['cust_name']][] = $row;
}
// get credit data
$queryOfCredit = mysqli_query($CONNECTION,"select * from ".$creditTable." order by cr_date");
while($row = mysqli_fetch_assoc($queryOfCredit)) {
$finalData[$row['cust_name']][] = $row;
}
// rearrange all data with date
$rearrangedFinalData = array();
foreach($finalData AS $first) {
foreach($first AS $data) {
$temp = array();
$temp['date'] = isset($data['Db_date']) ? $data['Db_date'] : $data['cr_date'];
$temp['invoice'] = isset($data['dm_invoice']) ? $data['dm_invoice'] : $data['Invoice_no'];
$temp['credit'] = isset($data['cr_amount']) ? $data['cr_amount'] : 0;
$temp['debit'] = isset($data['Debt_amount']) ? $data['Debt_amount'] : 0;
$temp['customer'] = $data['cust_name'];
$rearrangedFinalData[] = $temp;
}
}
usort($rearrangedFinalData,function($a,$b){
return strtotime($a['date']) > strtotime($b['date']);
});
var_dump($rearrangedFinalData);
consider the rearrangedFinalData will hold all the table entries, you can calculate balance based on either credit is set or debit is set in final array
consider updating table or column name based on your requirement

I don't get all the data from mysql - PHP

I've been searching for this for while but didn't find anything related.
So my problem is that I do get all the data from mysql with while(). However, all the articles I am trying to get displays as only 1 article even though the content is different. Sorry, it's not easy to explain that but see pictures below:
My database:
How it is displayed:
my articlesFunction.php code:
// check if user is logged in to view the content:
if(!isset($_SESSION['loggedin']) && !isset($_SESSION['loggedinAdmin'])){
header("Location: login.php");
}else{
}
//
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//
my articles.php:
<?php
///////////////////////////////////////////////////////////////////////////////////////
// UNFINISHED //
///////////////////////////////////////////////////////////////////////////////////////
session_start();
require_once 'connect.php';
include 'articlesFunction.php';
?>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Blog posts</title>
<link rel="stylesheet" href="css/articles.css">
</head>
<body>
<div id="bannerDiv" style="background-image: url(images/banner.jpg); background-size: 100% 100%; height:150px;">
<h2 id="bannerTitle"><u><i>Articles about travel that everyone loves...</i></u></h2>
<p>Homepage</p>
<span id="BannerMenu"><?php echo 'logged in as: '.$_SESSION['username'].' ';?></span><button>Logout</button>
</div>
<div id="container">
<div id="articles">
<div id="Display Articles">
<h1><u>Our set of articles:</u>
</h1>
<div id="display">
<?php
echo $fullArticle;
?>
</div>
</div>
</div>
</div>
</body>
</html>
So, I hope you understand my issue now. First, in this example, when I put it alone in the div, I only get the oldest article and I get only 1. If I add a while to the div, It gives me the results in the picture above:
So, how can I display the articles (all of them) and each one to be different as they are in the database.
You are overwriting your variable on every iteration of the while loop.
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle = 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}
so as a simple example
$a = 0;
$b = 3;
while($a < $b){
$output = $a;
$a++;
}
echo $output;
This gives back 2 because $output is being over written every-time. There are two approaches to keeping all the values.
Option one, concatenate the variable
$a = 0;
$b = 3;
$output = '';
while($a < $b){
$output .= $a;
$a++;
}
echo $output;
Which will output 012. We have to define the variable before using it with the .=. With the .= it is trying to concatenate the value first so it must already exist.
Option two, store the values in an array
$a = 0;
$b = 3;
while($a < $b){
$output[] = $a;
$a++;
}
print_r($output);
This will output:
Array
(
[0] => 0
[1] => 1
[2] => 2
)
This way is a bit more work because when you want to access it later you have to re-iterate through it. However it can be better if you want to be able to access each data point separately.
foreach($output as $value) {
echo $value;
}
Also note if users are providing their usernames, article name, or description and you aren't filtering that this will open you to XSS injections.
https://en.wikipedia.org/wiki/Cross-site_scripting
https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet#A_Positive_XSS_Prevention_Model
Usage in your actual code would be:
$sql = "SELECT * FROM `articles` ORDER BY id DESC";
$result = mysql_query($sql);
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
This should be your code, in order to avoid the errors you mentioned in the comments;
//init fullname variable
$fullArticle = '';
while($row = mysql_fetch_assoc($result)){
$displayUsername = $row['username'];
$displayArticleName = $row['name'];
$displayArticleDescription = $row['description'];
$fullArticle .= 'Article name: '.$displayArticleName.'<br/> This article was posted by: '.$displayUsername.'<br/>'.$displayArticleDescription.'<hr/>';
}?>
//

PHP problems with read data from database [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 7 years ago.
I've try to read data from my database but I don't know what it don't work and show me that error
Notice: Array to string conversion in C:\Users\VladxD\Desktop\Xampp\htdocs\Web(workspace)\Test\show_animation.php on line 65
Here is my code:
MySQL_connect:
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpassword = '';
$conn = mysqli_connect($dbhost, $dbuser, $dbpassword, "portofoliu_database") or die ("<div id='err'>Could not connect:</div> ");
Code:
<?php session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Directory Contents</title>
<link rel="stylesheet" href="show_folder.css">
<link rel="stylesheet" href="NewFile.css">
</head>
<body>
<div id=wapper>
<?php include 'Menu.php';
include 'MySQL_connect.php'; ?>
<div class="box">
<div id="container">
<table class="sortable">
<thead>
<tr>
<th>File name</th>
<th>Uplaod time</th>
</tr>
</thead>
<tbody>
<?php
// Opens directory
$user = #$_SESSION ['account'];
$dir = #$_SESSION ['account'] . '/image/';
if (is_dir($dir) == true) {
$myDirectory = opendir($dir);
// Gets each entry
while ($entryName = readdir($myDirectory)) {
$dirArray [] = $entryName;
}
// Closes directory
closedir($myDirectory);
// Counts elements in array
$indexCount = count($dirArray);
// Sorts files
sort($dirArray);
// Loops through the array of files
for ($index = 0; $index < $indexCount; $index++) {
// Allows ./?hidden to show hidden files
if ($_SERVER ['QUERY_STRING'] == "hidden") {
$hide = "";
} else {
$hide = ".";
}
//-------------------------------------------------------------------------------------------------
//$modtime=date("M j Y g:i A", filemtime($dir.$dirArray[$index]));
$modtime_test = mysqli_query($conn, "SELECT file_upload_time FROM users WHERE file_name ='$dirArray[$index]'");
$modtime = mysqli_fetch_assoc($modtime_test);
$timekey = date("YmdHis", filemtime($dir . $dirArray[$index]));
//-------------------------------------------------------------------------------------------------
if (substr($dirArray [$index], 0, 1) != $hide) {
// Gets File Names
$name = $dirArray [$index];
// Print 'em
echo "
<tr class='file'>
<td><a href=#' onclick='showImage(\"$index\")'>$name</a></td>
<td sorttable_customkey='$timekey'><a href='#'>$modtime</a></td>
</tr>";
}
}
}
?>
</tbody>
</table>
</div>
<div id="imageHolder">
<?php if (is_dir($dir) == false)
echo("<div id = 'noFile'>Your folder it's empty, upload file</div>");
?>
<script>
var array = [
<?php
foreach ($dirArray as $item)
{
echo "\"$dir{$item}\",";
}
?>
];
function showImage(index) {
var url = array[index];
url = "<img src='" + url + "'>";
document.getElementById("imageHolder").innerHTML = url;
}
</script>
</div>
</div>
</div>
</body>
</html>
I want to get my data time from my database and show it on my folder
Here is my element from database: http://i.imgur.com/kYciFQJ.png
and here are my site: http://i.imgur.com/HeEv1yG.png
If you see below "Upload time" I have this text "Array" but I want to get me data time from my database and put there.
As mysqli_fetch_assoc returns an array, not a single value, even if there is a single field being returned... try changing
$modtime = mysqli_fetch_assoc($modtime_test);
to
$results = mysqli_fetch_assoc($modtime_test);
$modtime = $results["file_upload_time"];
You have a PHP notice, "PHP array to string conversion".
<tr class='file'>
<td><a href=#' onclick='showImage(\"$index\")'>$name</a></td>
<td sorttable_customkey='$timekey'><a href='#'>$modtime</a></td>
</tr>";
In that code $modtime is array. You need to use $modtime['file_upload_time'].

PHP looping over object manipulate output based on object length

I have a PHP object that I am looping over, I know 2 things are definate with this object, I will never need to loop more than 12 times (1-12) and I will also always have to loop at least once.
My problem comes when the object is longer than 6 items, as if it is longer than 6 items I need to split the results into 2 <ol> and for the live of me I cannot figure out a nice way to do this?
Here is my attempt,
<?php $count = 1; ?>
<?php if(is_object($active_projects)) : ?>
<div class="col_1">
<?php if($count < 2) : ?>
<strong>Active projects</strong> View All
<?php endif; ?>
<ol <?php echo ($count > 1 ? " class='no-header'" : ""); ?>>
<?php foreach($active_projects as $project) : ?>
<li><?php echo $project->project_name; ?></li>
<?php $count ++; ?>
<?php endforeach; ?>
</ol>
</div>
<?php endif; ?>
Now my attempt displays all the results in one list, how can if there are more than 6 items in the object, split the loop in 2 so that I output 2 <div class="col_1"> with a list of 6 items in each?
Try this:
<?php
//create an object with 12 items
$obj = new stdClass();
for($i = 1; $i <= 12; $i++)
{
$project = "project_$i";
$obj->{$project} = new stdClass();
$obj->{$project}->name = "Project $i";
}
function wrapInLi($projectName)
{
return "<li>$projectName</li>\n";
}
function wrapInOl($arrayOfLi)
{
$returnString = "<ol>\n";
foreach ($arrayOfLi as $li)
{
$returnString .= $li;
}
return $returnString . "</ol>\n";
}
/*
* The classname is adjustable, just in case
*/
function wrapInDiv($ol, $class)
{
return "<div class='$class'>\n$ol</div>\n";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<?php
$arrayOfLi = array();
foreach($obj as $project)
{
//fill an array with list-items
$arrayOfLi[] = wrapInLi($project->name);
//six list-items? wrap it
if(count($arrayOfLi) === 6)
{
//wrap in unordered list
$ol = wrapInOl($arrayOfLi);
//wrap in div and echo
echo wrapInDiv($ol, 'col_1');
//reset array
$arrayOfLi = array();
}
}
?>
</body>
</html>

Sorting data by value (and using color) in php

I have a chart and a text file that is taking in some data. I would like to organize the data I have by putting the user with the highest score on the top of the table and coloring everything in their row blue. Any idea how I could do this?
file one:
<!doctype html public "-//W3C//DTD HTML 4.0 //EN">
<html>
<head>
<title>High Score</title>
</head>
<body>
form action="data.php" method="POST">
<table border="1">
<tr><td>Player Name</td><td><input type="text" name="name"</td></tr>
<tr><td>Score</td><td><input type="text" name="score"</td></tr>
<tr><td colspan="2" align="center"><input type="submit"></td></tr>
</table>
</form>
</body>
</html>
Data.php:
<?php
$name = $_POST['name'];
$score = $_POST['score'];
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
# $fp = fopen("$DOC_ROOT/../phpdata/highscore.txt","ab");
if(!$fp) {
echo 'Error: Cannot open file.';
exit;
}
fwrite($fp, $name."|".$score."\n");
?>
<?php
$DOC_ROOT = $_SERVER['DOCUMENT_ROOT'];
$players = file("$DOC_ROOT/../phpdata/highscore.txt");
echo "<table border='2'>";
echo "<tr> <td>Name</td> <td>Score</td> </tr>";
for($i = 0; $i < sizeof($players); $i++) {
list($name,$score) = explode('|', $players[$i]);
echo '<tr><td>'.$name.'</td><td>'.$score.'</td></tr>';
}
echo '</table>';
?>
Format all players/scores into arrays like array('name' => 'Bob', 'score' => 42):
foreach ($players as &$player) {
list($name, $score) = explode('|', $player);
$player = compact('name', 'score');
}
unset($player);
Sort the array by score (PHP 5.3 syntax):
usort($players, function ($a, $b) { return $b['score'] - $a['score']; });
Output the results, setting a class on the first row:
$first = true;
foreach ($players as $player) {
$class = $first ? ' class="highlight"' : null;
$first = false;
printf('<tr%s><td>%s</td><td>%s</td></tr>', $class, htmlspecialchars($player['name']), htmlspecialchars($player['score']));
}
Now highlight that class using CSS (or do it directly in the HTML, or whatever else you want to do).

Categories