How do I make a bar chart in CSS using PHP variables? - php

I have an array of float values in PHP and I want to turn the array into a bar chart using CSS. Each float value represents a percentage, so if a value is 50.0 then the bar should be 50% of a certain height. I am new to CSS, so I was wondering if anyone could show me how I would go about doing this.
I believe it should look something like this. I doubt that this code would work, but it's an example.
<?php
$values = array(50.0, 20.0, 30.0, 45.0); //This is the array of percentage values
?>
<style>
<?php
for ($i = 0; $i < count($values); $i++) //Create a new bar for each value
{?>
#bar
{
height: <?php 300 * ($values[$i] / 100.0); ?> px; //Specify the height of each bar
width: 30px;
}
<?php
}?>
</style>
Edit:
I've added the code suggested by Tom, but my web page currently produces no bars. Here is the full code for my PHP file. Why does it not produce any CSS content?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Visualisation result</title>
<style>
.bar
{
color: #00ff21;
width: 30px;
}
</style>
</head>
<body>
<?php
$values = array(50.0, 20.0, 30.0, 45.0);
for ($i = 0; $i < count($values); $i++)
{
$currentHeight = 300 * $values[$i] / 100.0; ?>
<div class="bar" style="height: <?php echo($currentHeight); ?> "></div>
<?php
}
?>
</body>
</html>

Your approach won't work, as you will be writing out several different rules for the same selector. It is invalid in HTML to have multiple values with the same ID "bar" anyway.
I guess you could do something like this:
.bar {
width: 30px;
}
<?php
for ($i = 0; $i < count($values); $i++) { ?>
<div class="bar" style="height:<?= 300 * $values[$i] / 100.0 ?>"></div>
<?php
} ?>
This generates the elements using the loop, setting their height using the style attribute. I have used the shorthand <?= instead of <?php echo (you weren't doing either in your question).

Related

How to have data allow decimals

I made a program that lets 6 grades be entered into a form, and then calculates the letter grade and the average. The only problem I'm having is that I can't figure out how to get the form to accept decimals. I tried changing my filter_input statement to sanitize floats, but that doesn't seem to fix the problem. Any thoughts would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Grades</title>
<link rel="stylesheet" href="bootstrap.min.css">
<script>
window.onload = () => {
document.getElementById('quiz1').focus();
document.getElementById('quiz1').select();
}
</script>
<style>
input[type="text"] {width: 4em !important; text-align: right; margin-left: .5em; }
ul { list-style-type: none; padding-left: 0; }
</style>
</head>
<body>
<div class="container">
<div class="col-lg-6 mx-auto text-center">
<h1>Enter Quiz Grades</h1>
<form action="." method="post">
<?php
// declare an array to store bowling scores
$quizScores = array();
// declare a variable to be used for the natural counting of the number of games
$numberOfScores = 6;
// declare a variable to be used for array elements - subtract 1 since array elements start at 0
$gamesArrayElements = $numberOfScores - 1;
for ($i = 0; $i <= $gamesArrayElements; $i++){
$quizNumber = $i + 1;
// load values from POST into array elements
if (strlen($_POST['quiz' . $quizNumber]) > 0){
$quizScores[$i] = filter_input(INPUT_POST, 'quiz' . $quizNumber, FILTER_SANITIZE_NUMBER_FLOAT);
}
echo "<div class='form-group form-inline justify-content-center'>\n";
echo "<label for='quiz$quizNumber'>Quiz $quizNumber: </label>\n";
echo "<input type='text' class='form-control' name='quiz$quizNumber' id='quiz$quizNumber' value='$quizScores[$i]'>%\n";
echo "</div>\n";
}
?>
<div class="form-group">
<input type="submit" class="btn btn-secondary" value="Find Average of <?php echo $numberOfScores; ?> Highest Quiz Grades">
Clear
</div>
</form>
<?php
if (count($quizScores) === $numberOfScores){
$total = 0;
echo "<h2>Scores:</h2>\n";
echo "<ul>\n";
// for loop to print array elements and add each score to the total
for ($i = 0; $i <= $gamesArrayElements; $i++){
echo "<li>$quizScores[$i] " . getLetterGrade($quizScores[$i]) . "</li>\n";
$total += $quizScores[$i];
}
echo "</ul>\n";
$average = $total / $numberOfScores;
echo "<h2>Average Score:</h2>\n";
echo "<p>" . number_format($average, 1, .2) . " - " . getLetterGrade($average) . "</p>\n";
} else {
if(count($quizScores) > 0) {
echo "<h2 class='text-danger'>All textboxes should contain grades.</h2>\n";
}
}
?>
</div>
</div>
</body>
</html> ```
I changed number_format($average, 1, .2) to number_format($average, 1) and then I do get the average rounded to one decimal. I also removed the getLetterGrade() function because it is not defined in your code. Finally I change the form action to "", instead of ".", because it didn't work in my test environment.
Perhaps you need to switch on error reporting in PHP? That way you can see what's wrong with your code.

PHP loop for each row with different style

Can someone help me please?
I need a loop for a checkerboard pattern project.
Right now i have this:
<?php
$uitvoer="<table summary=''>\n";
$j=0;
$uitvoer .= "\t<tr>\n";
for($i=0;$i<8;$i++)
{
$uitvoer .= "\t\t<td class='kleur".(($i+$j)%2)."'> </td>\n";
}
echo <<<END
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Page title</title>
<style type="text/css">
<!--
td
{
width: 50px;
height: 50px;
border:4px groove red;
}
td.kleur0
{
background-color: white;
}
td.kleur1
{
background-color: black;
}
-->
</style>
</head>
<body>
$uitvoer
</body>
</html>
END;
?>
Then i get this:
So far so good.
But i need 8 rows with different lines and colors
The result need to be like this:
How can i do that the easiest and fastest way in a loop or a array??
You just need a second loop that adds table rows (<tr>). The beginning of your file should look like this:
$uitvoer="<table summary=''>\n";
for ($j=0; $j < 8; $j++) {
$uitvoer .= "\t<tr>\n";
for($i=0;$i<8;$i++) {
$uitvoer .= "\t\t<td class='kleur".(($i+$j)%2)."'> </td>\n";
}
$uitvoer .= "\t</tr>\n";
}
So, inside the loops, $i will hold your table cell (<td> tag) and $j will hold your table row (<tr> tag).

Strange lines with many divs

The problem can be shown here. I was experimenting with thousands of fixed div boxes to create a randomly generated background. I am aware this has a big impact on performance.
However, I was wondering if there was any solution to the strange white lines in the background of my webpage. I am almost 100% certain there is nothing wrong with my php & css that is determining where the boxes are placed in my background but, here it is just in-case.
define('ROWS', 100);
define('COLUMNS', 100);
$boxes = array();
for($i = 0; $i < ROWS; $i++) {
$boxes[] = array();
for($j = 0; $j < COLUMNS; $j++) {
$boxes[$i][$j] = randColor();
?>
#back<?php echo $i*COLUMNS + $j; ?> {
background: #<?php echo $boxes[$i][$j]; ?>;
width: <?php echo 100.0/COLUMNS ?>%;
height: <?php echo 100.0/ROWS ?>%;
left: <?php echo $j * 100.0/COLUMNS?>%;
top: <?php echo $i * 100.0/ROWS ?>%;
position: fixed;
z-index: -300;
}
Try instead using <canvas> and split the canvas up in pieces instead of divs. It is a rectangular area in a HTML file on which you can draw anything including parts.
Example: Draw a Circle
Javascript
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();
ctx.arc(95,50,40,0,2*Math.PI);
ctx.stroke();
Html
<canvas id="myCanvas" width="200" height="100"
style="border:1px solid #000000;">
</canvas>

Programatically creating divs with different background colors from a php array

I have created divs in a MVC framework (Codeigniter).
From a data array, I am looping through the 'subject' array and making a div for each. I also added a header div and a content div for each subject. So, how do I make the background of the header in each subject have different colors from the colors array. They have to be different unless the number of the subjects is greater than the number of colors in the color array.
Here is the code for looping through each subject:
foreach ($userSubjects as $subject => $info) {
echo "<div class='subject paper'>";
echo "<div class='subjectHeader'>";
echo $info['subject_name'];
echo "</div>";
echo "<div class='subjectContent'>";
echo "</div>";
echo "</div>";
And here is the randColor array:
$colorSet = array(
'#1abc9c',
'#2ecc71',
'#3498db',
'#9b59b6',
'#34495e',
'#f1c40f',
'#e67e22',
'#e74c3c',
'#ecf0f1',
'#95a5a6'
);
I think the best trick is using CSS instead of PHP :
div.subject:nth-child(10n+1) > .subjectHeader { background: #1abc9c}
div.subject:nth-child(10n+2) > .subjectHeader { background: #2ecc71}
div.subject:nth-child(10n+3) > .subjectHeader { background: #3498db}
div.subject:nth-child(10n+4) > .subjectHeader { background: #9b59b6}
div.subject:nth-child(10n+5) > .subjectHeader { background: #34495e}
div.subject:nth-child(10n+6) > .subjectHeader { background: #f1c40f}
div.subject:nth-child(10n+7) > .subjectHeader { background: #e67e22}
div.subject:nth-child(10n+8) > .subjectHeader { background: #e74c3c}
div.subject:nth-child(10n+9) > .subjectHeader { background: #ecf0f1}
div.subject:nth-child(10n+10) > .subjectHeader { background: #95a5a6}
To make it easier to use, you can use this script to generate CSS script;
<style type="text/css">
<?php
$i = 1;
foreach($colorSet as $c)
{
echo "div.subject:nth-child(".count($colorSet)."n+".$i.") > .subjectHeader { background: ".$c."}";
$i++
}
?>
</style>
you can just have a counter variable and add the css as a style attribute.
saves you having to create a style tag for the css rules.
<?php
$colourSet = array(
'#1abc9c',
'#2ecc71',
'#3498db',
'#9b59b6',
'#34495e',
'#f1c40f',
'#e67e22',
'#e74c3c',
'#ecf0f1',
'#95a5a6'
);
$numColours = count($colourSet);
$colourInd = 0;
foreach ($userSubjects as $subject => $info) {
?>
<div class="subject paper">
<div class="subjectHeader" style="background: <?php echo $colourSet[$colourInd]; ?>">
<?php echo $info['subject_name']; ?>
</div>
<div class="subjectContent">
</div>
</div>
<?php
$colourInd = ($colourInd + 1) % $numColours;
}
?>
as this doesn't use nth-child it's backwards compatible with older browsers.
but considering it's only like older than IE8 that doesn't support that, it's not worth worrying about that really.
unless you're planning on dynamically loading these colours, then it's probably better to just define them as css rules like #Aldry-Wijaya suggested
The best way (IMO) would be to use CSS classes to represent the colours. Start by defining your CSS styles:
<style type="text/css">
<?php
foreach($colorSet as $key => $color) {
echo '.color' . $key . ' .subjectHeader { color: "' . $color . '"; }' . PHP_EOL;
}
?>
</style>
Then when you output your divs, output a color style with it:
$i = 0;
foreach ($userSubjects as $subject => $info) :
if(!isset($colorSet[$i]))
$i = 0; // reset to the start of the array if you reach the end
?>
<div class='subject paper color<?=$colorSet[$i++]?>'>
<div class='subjectHeader'>
<?=$info['subject_name']?>
</div>
<div class='subjectContent'>
</div>
</div>
<?php
endif;

Creating 5 Star Rating System With PHP , MySQL ,Jquery And Ajax

I've downloaded this tutorial http://megarush.net/5-star-rating-system-with-php-mysql-jquery-and-ajax/ but I'm getting these errors:
Notice: Undefined variable: rat in C:\xampp\htdocs\rating\rating.php on line 37
Notice: Undefined variable: v in C:\xampp\htdocs\rating\rating.php on line 41
<?php
include("settings.php");
connect();
$ids=array(1,2,3);
?>
<html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<link rel="stylesheet" href="rating.css" />
<script type="text/javascript" src="rating.js"></script>
</head>
<body>
<?php
for($i=0;$i<count($ids);$i++)
{
$rating_tableName = 'ratings';
$id=$ids[$i];
$q="SELECT total_votes, total_value FROM $rating_tableName WHERE id=$id";
$r=mysql_query($q);
if(!$r) echo mysql_error();
while($row=mysql_fetch_array($r))
{
$v=$row['total_votes'];
$tv=$row['total_value'];
$rat=$tv/$v;
}
$j=$i+1;
$id=$ids[$i];
echo'<div class="product">
Rate Item '.$j.'
<div id="rating_'.$id.'" class="ratings">';
for($k=1;$k<6;$k++){
if($rat+0.5>$k)$class="star_".$k." ratings_stars ratings_vote";
else $class="star_".$k." ratings_stars ratings_blank";
echo '<div class="'.$class.'"></div>';
}
echo' <div class="total_votes"><p class="voted"> Rating: <strong>'.#number_format($rat).'</strong>/5 ('.$v. ' vote(s) cast)
</div>
</div></div>';}
?>
</body></html>
$rat and $v are being defined within the scope of your while loop.
If you declare them globally (outside the loop), the rest of your code will recognize them.
$rat = 0;
$v = 1;
while($row=mysql_fetch_array($r))
{
$v=$row['total_votes'];
$tv=$row['total_value'];
$rat=$tv/$v;
}
See here:
http://bgallz.org/988/javascript-php-star-rating-script/
This combines a Javascript code that generated the URL for the different ratings given as well as the change in display for the stars before and after a rating is given.
An overlay DIV is displayed after the rating is given so that no immediate ratings can be given by the same. It also stores the user's IP address with the rating submission to prevent multiple ratings from one user.
This is a simple and easy to use script with just Javascript and PHP for star rating.
The problem is because of scoping of those variables. When you are trying to echo those variables outside the while loop; PHP can not find the varables as they were created (and assigned) inside the loop. To solve this, just assign a blank value to both variables outside too:
if(!$r) echo mysql_error();
$rat = 0;
$v = 1; // In case there are no records.
while($row=mysql_fetch_array($r))
{
$v = $row['total_votes'];
$tv = $row['total_value'];
$rat = $tv/$v;
}
Add this at line at beginning to nide notice error in your code .
error_reporting(E_ALL ^ E_NOTICE);
Most of time notice error do not affect the program.
In case if your votes are not recording then delete your cookies and try to vote from different IP address .This script has a feature to not accept votes from same ip or vistitor to avoid multiple votes by same users on same product.
var cname=document.getElementById(id).className;
var ab=document.getElementById(id+"_hidden").value;
document.getElementById(cname+"rating").innerHTML=ab;
for(var i=ab;i>=1;i--)
{
document.getElementById(cname+i).src="star2.png";
}
var id=parseInt(ab)+1;
for(var j=id;j<=5;j++)
{
document.getElementById(cname+j).src="star1.png";
}
Code from http://talkerscode.com/webtricks/star-rating-system-using-php-and-javascript.php
<style>
.star {
font-size: x-large;
width: 50px;
display: inline-block;
color: gray;
}
.star:last-child {
margin-right: 0;
}
.star:before {
content:'\2605';
}
.star.on {
color: red;
}
.star.half:after {
content:'\2605';
color: red;
position: absolute;
margin-left: -20px;
width: 10px;
overflow: hidden;
}
</style>
<div class="stars">
<?php
$enable = 5.5; //enter how many stars to enable
$max_stars = 6; //enter maximum no.of stars
$star_rate = is_int($enable) ? 1 : 0;
for ($i = 1; $i <= $max_stars; $i++){ ?>
<?php if(round($enable) == $i && !$star_rate) { ?>
<span class="<?php echo 'star half'; ?>"></span>
<?php } elseif(round($enable) >= $i) { ?>
<span class="<?php echo 'star on'; ?>"></span>
<?php } else { ?>
<span class="<?php echo 'star'; ?>"></span>
<?php }
}?>
</div>

Categories