Jump to content

PHP in CSS with SQL and Sessions


Cobra23

Recommended Posts

Hi,

I thought it was easier to open a new thread on a different topic. I have a css file that works fine with PHP, SQL and Sessions but this file affects my users by logging them out after a few clicks when a session is in the file due to it sometimes not recognizing the $_SESSION['identity'] where it gets undelcared. The session is the only way I can get it working from all my tests.

<?php
header("Content-type: text/css; charset: UTF-8");
header('Cache-control: must-revalidate');
mySessionFunction();
$identity = $_SESSION['identity'];
$startquery = "SELECT `id` FROM `user_table` WHERE `identity` = :identity LIMIT 1";
$start1 = $connecting->prepare($startquery);
$start1->execute(array(':identity' => $identity));
while ($start_row = $start1->fetch(PDO::FETCH_ASSOC)) {
	$id = $start_row['id'];
	$querySelect = "SELECT `car_id`, `progress` FROM `cars` WHERE `member_id` = :id LIMIT 1";
	$query = $connecting->prepare($querySelect);
	$query->execute(array(':id' => $id));
	$num = $query->rowCount();
	if ($num !== 0) {
		while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
			$car_id = $row['car_id'];
			$progress = $row['progress'];
			echo '.progressed'.$car_id.'{width: '.$progress.'%;}';
			if ($progress === 0) {
				$hidden_progress = '100';
			} else {
				$progress1 = $progress;
				$hidden_progress = 100 - $progress1;
			}
			echo '.hiddenprogressed'.$car_id.'{width: '.$hidden_progress.'%;}';
		}
	}
}
?>

What I am looking for is how can I get this to work in a different way but to accept the id and progress into the css file. Each user will have different data, so this is why I am doing it this way. Maybe there is a better way outside of css but inline css is not allowed.

 

Link to comment
Share on other sites

I was absolutely shattered when I wrote that. It needed to be more clearer.

What I am trying to do is have the website automatically create css classes in a css file (mainly with a .php extension) but also have php, sql, and sessions data in that file so I can create unique classes that would change based on each users car_id and progress column names in the database (car_id is an example and not my real column name).

I hope that helps. I forgot an include("/database-connection.php"); in the first line which contains a connection for the database.

But If I use the above code and refresh or click the link, the following session

$_SESSION['identity'];

will sometimes become undeclared, and will kick me out of the website.

Link to comment
Share on other sites

"create css classes"  or "use different css classes"???

You could make your process simpler by writing a better query.  It is not recommended to run a query inside a loop.  Write the query to gather All of your desired data then go thru those results without having to do another query.

Also - I don't use headers much other than for normal html page outputs so I don't know what a header using "text/css" is supposed do.  Are you saying that your entire output is simply css data and nothing else?  I don't see much of any typical web page's items here so hard to say WTH you are trying to do.  Have to agree strongly with Benanamen here.

Do you know the typical format of a properly written html document?

Link to comment
Share on other sites

1 hour ago, ginerjm said:

"create css classes"  or "use different css classes"???

You could make your process simpler by writing a better query.  It is not recommended to run a query inside a loop.  Write the query to gather All of your desired data then go thru those results without having to do another query.

Also - I don't use headers much other than for normal html page outputs so I don't know what a header using "text/css" is supposed do.  Are you saying that your entire output is simply css data and nothing else?  I don't see much of any typical web page's items here so hard to say WTH you are trying to do.  Have to agree strongly with Benanamen here.

Do you know the typical format of a properly written html document?

Again, gas! Second post to me and you leave a gas comment, again ? I don't see why you have the need to comment on things you have no clue about? Especially not knowing about a header of "text/css" or the creation of css classes.

Link to comment
Share on other sites

Gas = Laughable

The whole idea of doing it this way is so the css classes can be created as soon as there's a change in the database, and then those classes are used in the html's div or span tags automatically.

But this is too advanced for you by the way you have commented. Explaining it would be useless to you and will get more ridiculous questions. If you don't understand what headers are, how can you understand anything about generating css classes or even how sessions work (in regards to previous thread).

Link to comment
Share on other sites

From the calculations in your code I am guessing you are trying to produce something like below using a weird method involving dynamic CSS (different data, I know, but similar scenario) .

Am I right?

As ginerjm pointed out, a single query should be used, not queries inside a loop. The output below used this data

pupil                                 result                                                      subject
+---------+--------+------------+     +---------+-----------+-------+------------+----------+     +-----------+-----------+
| pupilID | fname  | lname      |     | pupilid | subjectid | pcent | schoolyear | resultid |     | subjectID | subject   |
+---------+--------+------------+     +---------+-----------+-------+------------+----------+     +-----------+-----------+
|       8 | Emma   | Watson     |     |       8 |         1 |    91 |       2014 |        4 |     |         1 | English   |
|       9 | George | Wilson     |     |       9 |         1 |    62 |*      2014 |        5 |     |         2 | German    |
|      15 | Jack   | Williams   |     |      14 |         1 |    64 |       2014 |        8 |     |         3 | Geography |
|      19 | Mary   | Whitehouse |     |      15 |         1 |    93 |       2014 |        9 |     |         4 | Maths     |
+---------+--------+------------+     |      19 |         1 |    60 |       2014 |       11 |     |         5 | Economics |
                                      |       9 |         5 |    50 |*      2014 |       41 |     |         6 | Biology   |
                                      |      14 |         5 |    51 |       2014 |       43 |     |         7 | Chemistry |
                                      |       9 |         7 |    89 |*      2014 |       57 |     |         8 | Physics   |
                                      |      14 |         7 |    53 |       2014 |       59 |     |         9 | History   |
                                      |       9 |         9 |    87 |*      2014 |       76 |     |        10 | Computing |
                                      |      15 |         9 |    54 |       2014 |       78 |     +-----------+-----------+
                                      |      19 |         9 |    58 |       2014 |       81 |
                                      |       8 |         1 |    73 |       2015 |       85 |
                                      |       9 |         1 |    93 |       2015 |       86 |
                                      |      14 |         1 |    79 |       2015 |       89 |
                                      |      15 |         1 |    94 |       2015 |       90 |     
                                      |      19 |         1 |    71 |       2015 |       92 |
                                      |       9 |         5 |    95 |       2015 |      122 |
                                      |      14 |         5 |    92 |       2015 |      124 |
                                      |       9 |         7 |    69 |       2015 |      138 |
                                      |      14 |         7 |    76 |       2015 |      140 |
                                      |       9 |         9 |    61 |       2015 |      157 |
                                      |      15 |         9 |    86 |       2015 |      159 |
                                      |      19 |         9 |    79 |       2015 |      162 |
                                      +---------+-----------+-------+------------+----------+

with this single query to get the 2014 exam results for Wilson

SELECT s.subject
     , r.pcent as pcent
FROM pupil p 
     JOIN result r USING (pupilid)
     JOIN subject s USING (subjectid)
WHERE p.lname = 'Wilson'
	  AND r.schoolyear = 2014
ORDER BY subject;

The charts were drawn using just the pcent values from the database without specific classes for the pcent values, just generated SVG graphics.

Capture.PNG

Edited by Barand
Link to comment
Share on other sites

Very very similar Barand. One query is always best. How does one do the SVG part? I've never used SVG. I do have a few different colors and meanings for all the different graphs produced in the same table and their percentages.

Anyways, I did get this to work perfectly for what i'm doing and stopped users getting kicked out. I'm still curious to know about the other option in SVG output instead of dynamically adding php variables automatically to the css and produce the classes.

Link to comment
Share on other sites

here's the code that produced the example

<?php
$res = $db->prepare("SELECT s.subject
                         , r.pcent
                    FROM pupil p 
                         JOIN result r USING (pupilid)
                         JOIN subject s USING (subjectid)
                    WHERE p.lname = ?
                          AND r.schoolyear = 2014
                    ORDER BY subject;
                    ");
$res->execute( [ 'Wilson'] );
$tdata = '';
foreach ($res as $r)  {
    $tdata .= "<tr><td>{$r['subject']}</td>
                  <td>{$r['pcent']}</td>
                  <td>" . bar (400, 30, $r['pcent']) . "</td>
              </tr>";
}

/**
* bar chart
* 
* @param int $wid
* @param int $ht
* @param mixed $val
* @param int $max       optional default 100
*/
function bar($wid, $ht, $val, $max=100)
{
    $bar = "<svg width='$wid' height='$ht' viewBox='0 0 $wid $ht'>\n";
    $pix = $wid/$max;
    if ($val > 100) $val = 100;
    // percentage labels
    for ($p=25; $p<=75; $p+=25) {
        $ty=10;
        $tx = $p * $pix;
        $bar .= "<path d='M $tx $ty l 0 2' stroke='#AAA' />
            <text x='$tx' y='$ty' class='pcent' >{$p}%</text>\n";
    }
    // draw bar    
    $w = $val * $pix;
    $h = $ht-12;
    $bar .= "<rect x='0' y='12' width='$wid' height='$h' stroke='#444' fill='#EEE' />\n";
    $bar .= "<rect x='0' y='12' width='$w' height='$h' fill='#F48A11' />\n";
    $bar .= "</svg>\n";
    return $bar;
}


?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="generator" content="PhpED 18.0 (Build 18044, 64bit)">
<title>Sample</title>
<meta name="creation-date" content="02/15/2019">
<style type="text/css">
    table {
        width: 500px;
        margin: 10px auto;
    }
    .pcent {
        font-family: calibri, sans-serif;
        font-size: 8pt;
        fill: #AAA;
    }
</style>
</head>
<body>
   <table>
       <tr><th>Subject</th><th>Pcent</th><th>Chart</th></tr>
       <?=$tdata?>
   </table>
</body>
</html>

 

Link to comment
Share on other sites

Here's an optional version - less than 60% (red) over 80% (green)

function bar($wid, $ht, $val, $max=100)
{
    $bar = "<svg width='$wid' height='$ht' viewBox='0 0 $wid $ht'>\n
            <defs>
            <linearGradient id='pchi' x1='0' y1='0' x2='0' y2='1'>
                <stop offset='0%' stop-color='#54BC54'/>
                <stop offset='15%' stop-color='#eee'/>
                <stop offset='100%' stop-color='#0B7604'/>
                </lineargradient>
            <linearGradient id='pclo' x1='0' y1='0' x2='0' y2='1'>
                <stop offset='0%' stop-color='#E02222'/>
                <stop offset='15%' stop-color='#eee'/>
                <stop offset='100%' stop-color='#A91723'/>  
                </lineargradient>
            <linearGradient id='pcmid' x1='0' y1='0' x2='0' y2='1'>
                <stop offset='0%' stop-color='#F2D335'/>
                <stop offset='15%' stop-color='#eee'/>
                <stop offset='100%' stop-color='#EC9807'/>
                </lineargradient>
            </defs>
            ";
    $pix = $wid/$max;
    if ($val > 100) $val = 100;
    // percentage labels
    for ($p=25; $p<=75; $p+=25) {
        $ty=8;
        $tx = $p * $pix;
        $bar .= "<path d='M $tx $ty l 0 4' stroke='#AAA' />
            <text x='$tx' y='$ty' class='pcent' >{$p}%</text>\n";
    }
    // draw bar
    $w = $val * $pix;
    $h = $ht-12;
    
    if ($val > 80) $barfill = 'url(#pchi)';
    elseif ($val > 60) $barfill = 'url(#pcmid)';
    else $barfill = 'url(#pclo)';
    
    $bar .= "<rect x='0' y='12' width='$wid' height='$h' stroke='#444' fill='#DDD' />\n";
    $bar .= "<rect x='0' y='12' width='$w' height='$h' fill='$barfill' />\n";
    $bar .= "</svg>\n";
    return $bar;
}

 

Capture.PNG

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.