I am trying to make a program that can get data from Sql using php. the received data is a number from 1 to 5 and each number presents a color. every time a number is received a counter adds 1 for that color in html. I have been able to code this but if the page is refreshed the counted value becomes 0.
<?php
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
echo $row['name'].", ".$row['color']";
$red = "5";
$pink = "4";
$yellow = "3";
$black = "2";
$white = "1";
$colorid = $row['color'];
if ($colorid == $red){
echo "Red";
$re = 1;
$re = ++;
} elseif ($colorid == $pink){
echo "Pink";
$pi = 1;
$pi = ++;
} elseif ($colorid == $yellow){
echo "Yellow";
$ye = 1;
$ye = ++$;
} elseif ($colorid == $black){
echo "Black";
$blk = 1;
$blk = ++;
} elseif ($colorid == $white){
echo "White";
$wh = 1;
$wh = ++;
} else {
echo "Cannot verify the color code";
}
}
?>
<div>
<span>White: </span><input name="white" value="<?php echo (isset($wh))?$wh:'';?>">
<span>Black: </span><input name="black" value="<?php echo (isset($blk))?$blk:'';?>">
<span>Yellow: </span><input name="yellow" value="<?php echo (isset($ye))?$ye:'';?>">
<span>Pink: </span><input name="pink" value="<?php echo (isset($pi))?$pi:'';?>">
<span>Red : </span><input name="red" value="<?php echo (isset($re))?$re:'';?>">
</div>
My Answer:
To increment the counter every time data is received from SQL and maintain the count even after page refresh, you can use sessions in PHP. Here's an example code snippet to achieve this:
php
session_start();
// Check if data is received from SQL
if (isset($_GET['color'])) {
$color = $_GET['color'];
// Increment counter for the received color
if (isset($_SESSION['count'][$color])) {
$_SESSION['count'][$color]++;
} else {
$_SESSION['count'][$color] = 1;
}
}
// Display the counters for each color
echo "Red: " . ($_SESSION['count']['red'] ?? 0) . "
";
echo "Blue: " . ($_SESSION['count']['blue'] ?? 0) . "
";
echo "Green: " . ($_SESSION['count']['green'] ?? 0) . "
";
echo "Yellow: " . ($_SESSION['count']['yellow'] ?? 0) . "
";
echo "Purple: " . ($_SESSION['count']['purple'] ?? 0) . "
";
?>
In this code, we are starting a session at the beginning of the script. We are checking if data is received from SQL and then incrementing the counter for the received color in the session variable `$_SESSION['count']`. Finally, we are displaying the counters for each color.
This way, the counters will be maintained even after the page is refreshed.
Rate this post
4 of 5 based on 7066 votesComments