Dynamic CSS with PHP based on database - php

found a couple answers here on StackOverflow and used them as my models, but I must be missing something. I'm trying to set a couple of background colors dynamically in CSS based on what is in my database, but it's not working - when I check Inspect Element in Chrome, background-color has a line through it and a warning mark for 'Invalid property value'.
Here's my code; it's in two separate files - the first is in the header include file, and the second is in the linked .php / css-esque file.
Header include: [Edited 4/29 to include session code]
session_start();
// check if $_SESSION was set before
if (!isset($_SESSION['email'])) {
header("Location: bad_login.php");
exit();
}
$_SESSION['companyid'] = $_POST['companyid'];
$companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];
require_once('../includes/_connection.inc.php');
$connect = dbConnect('read');
$sql = 'SELECT colorone, colortwo, logo
FROM companies
WHERE companyid = ' . $companyID;
$result = $connect->query($sql) or die(mysqli_error());
$row = $result->fetch_assoc();
$colorOne = '#' . $row['colorone'];
$colorTwo = '#' . $row['colortwo'];
$carrierLogo = '/companylogos/' . $row['logo'];
PHP/CSS file:
<?php header("Content-type: text/css");
?>
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: <?php echo $colorOne; ?>;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: <?php echo $colorTwo; ?>;
}
EDIT 4/29:
This is the CSS generated:
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: ;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: ;
}
I also echoed the variable back in the html so I know that there should be something in the variable. Should I be opening the database and assigning the variable inside the css.php file?
CSS/PHP is linked this way in header:
<link type="text/css" rel="stylesheet" href="../css/carrier.php">

Instead of using the .css file extension, use .php
in the html file: is it linked to .php?
<link rel='stylesheet' type='text/css' href='css/style.php' />
in the style.php add
<?php
header("Content-type: text/css; charset: UTF-8");
?>
Now you can set up variables for whatever you like:
source
Edit:
Don't forget about session_start(); since you're using sessions (I don't understand how, since nothing gets posted to css/carrier.php you should rather have it in session from a different file & then just use the $companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];).
is this the way your code looks?
<?php
session_start();
header("Content-type: text/css; charset: UTF-8");
$_SESSION['companyid'] = $_POST['companyid'];
$companyID = $_SESSION['companyid'];
$email = $_SESSION['email'];
require_once('../includes/_connection.inc.php');
$connect = dbConnect('read');
$sql = 'SELECT colorone, colortwo, logo
FROM companies
WHERE companyid = ' . $companyID;
$result = $connect->query($sql) or die(mysqli_error());
$row = $result->fetch_assoc();
$colorOne = '#' . $row['colorone'];
$colorTwo = '#' . $row['colortwo'];
$carrierLogo = '/companylogos/' . $row['logo'];
?>
#main {
width: 85%;
margin: 0 auto;
padding: 0.75em 0;
}
#colorOne {
width: 100%;
height: 12px;
background-color: <?php echo $colorOne; ?>;
}
#colorTwo {
width: 100%;
height: 7px;
background-color: <?php echo $colorTwo; ?>;
}

The answer of yesitsme is correct. Other thing you can do is that each storage changes in the database, run the process of creating this "new" CSS file with the appropriate .css extension.
What if with every request you create a new CSS file?
I mean, you have two paths, when creating the first call to the Web and update it from time to time, either, at the time you keep the data in the database associating it to a script.
With this new CSS and stored is generated through fwrite () and other functions that PHP has to manage files, keep the name of the CSS created in the BDD and then in your place the link as appropriate.

Related

Use CSS to define print page

The last few days I've been experimenting with defining CSS stylesheet that is configuring the page to be printed out.
This is my final solution, which is working (at least what I can see in the html output):
home.php being called initially:
<?php
$_SESSION['pageWidth'] = 20;
$_SESSION['pageHeight'] = 15;
$_SESSION['pageOrientation'] = "landscape";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1">
<?php
echo "<style type='text/css' media='print'>
.card {
clear: both;
page-break-before: always;
}
.no-print, .no-print *
{
display: none !important;
}
#page : left{
margin: 0.5cm;
}
#page : right{
margin: 0.5cm;
}
#page : top{
margin: 1.5cm;
}
/* https://docs.w3cub.com/css/#page/size */
#page {
size: " . $_SESSION['pageWidth'] + 2.5 ."cm " . $_SESSION['pageHeight'] + 2.5 . "cm " . $_SESSION['pageOrientation'] . " !important;
}
</style>";
?>
</head>
During using integrated php files (called by include "cardGenerator.php";), the session_variables are updated with other values (width, height and maybe orientation, depending on the content).
Unfortunately, even my initial set values are ignored by browsers even though in the browser session, it looks all good:
I've been trying it with chrome, edge and firefox - all of them ending up in ignoring the #page{size: } statement.
Does anybody have an idea or same experiences with browsers?
I've been doing this:
put variable values into session to overwrite these value from any php file at any time and to integrate it into css
put css <style> </style> section into header of home.php which is the "leading" php
trying to print out from chrome, edge, firefox
trying with different width/height values
checked many solutions in stackoverflow
During studying some additional material, I've realized that defining a width and a height actually leads to kind of a landscape/portrait. So this information is obsolete. My working code:
<?php
echo "<style type='text/css' media='print'>
.card {
clear: both;
page-break-before: always;
}
.no-print, .no-print *
{
display: none !important;
}
#page : left{
margin: 0.5cm;
}
#page : right{
margin: 0.5cm;
}
#page : top{
margin: 1.5cm;
}
/* https://docs.w3cub.com/css/#page/size */
#page {
size: " . $_SESSION['pageWidth'] + 2.5 ."cm " . $_SESSION['pageHeight'] + 2.5 . "cm !important;
}
</style>";
?>
So, hopefully, this helps other with similar issues. As well as my approach on passing PHP variables into a stylesheet.

PHP file_exists method not working as expected

I am trying to set the background of the html body dynamically. Basically if a file exists, use it, otherwise use the default. But it keeps using the default regardless of whether the file exists or not.
<style>
body
{
padding-top: 50px;
background-image: url("<?php
clearstatcache();
if(file_exists("/profile_img/".$profileData["ID"]."_bg.jpg"))
{
echo "/profile_img/".$profileData["ID"]."_bg.jpg?". rand(5, 15);
}
else
{
//echo "/profile_img/".$profileData["ID"]."_bg.jpg?". rand(5, 15);
echo "/profile_img/default.jpg?". rand(5, 15);
}
?>");
background-size: cover;
background-position: 50% 50%;
}
</style>
I have tried using the file (the commented line) and it works. I can not see why this doesn't work
Some issues:
Using / will be absolute, causing it to look in the root directory.
Always check vars are set before using.
All that's changing is the filename, so you can use a ternary, which will reduce alot of that code.
<?php
$background = isset($profileData["ID"]) && file_exists('./profile_img/'.$profileData["ID"].'_bg.jpg')
? $profileData["ID"].'_bg.jpg' : 'default.jpg';
?>
<style>
body {
padding-top: 50px;
background-image: url("/profile_img/<?= $background.'?_='.microtime(true) ?>");
background-size: cover;
background-position: 50% 50%;
}
</style>
If it's still not working:
Check the file actually exists.

How to i save style="position: relative; left: 77px; top: -14px;" in php variable

One of my div dynamically outputs this:
style="position: relative; left: 77px; top: -14px;"
while i use dragging.
How can i save this in a php variable and store it in the database.
Here is one way of doing it. But please note that this uses jQuery, jQuery UI and a PHP page to handle and save the data. In other words, this is an inefficient mess. Someone should be coming up with a better way shortly.
This answer uses code from this answer, thanks to Simen Echholt: https://stackoverflow.com/a/4139860/3186769
To see if the div was dragged, we first check if there is a mousedown event on the div. If there is, then we check if there is a mousemove event on it before there is a mouseup. If there is, then the div has been dragged.
We post the left and top position of the div if it has been dragged. Here is the javascript to implement this:
// For the sake of simplicity, let us assume the div had an id "d".
$(function() {
var isDragging = false;
$("#d")
.mousedown(function() {
$(window).mousemove(function() {
isDragging = true;
$(window).unbind("mousemove");
});
})
.mouseup(function() {
var wasDragging = isDragging;
isDragging = false;
$(window).unbind("mousemove");
if (wasDragging) {
var left = $("#d").position().left;
var top = $("#d").position().top;
$.post("backend.php", {left: left, top: top});
}
});
$("#d").draggable(); // allow the div to be dragged.
});
Here is an example of what backend.php could look like. This is the PHP page that our javascript is posting to.
<?php
if (isset($_POST['left']) && isset($_POST['top']))
{
$db = new mysqli("localhost", "test", "test", "test") or die("This error message will not be visible on your HTML page unless you add a function in the jQuery post method to handle the returned output");
$res = $db->query("INSERT INTO rememberPosition (left, top) values (" . $db->escape_string($_POST['left']) . ", " . $db->escape_string($_POST['top']) . ")");
$db->close();
}
?>
The HTML for the div is pretty simple, and it should look something like this:
<div id="d" style="<?php require('memory.php'); echo $styleString; ?>">Here is a div with super-powers... It can actually fly around :)</div>
where we load the saved position values in memory.php. Here is an example of what memory.php could look like:
<?php
$styleString = "position: relative; left: 0px; top: 0px;";
$db = new mysqli("localhost", "test", "test", "test") or die("Error connecting to database.");
if ($res = $db->query("SELECT left, top FROM rememberPosition"))
{
if ($row = $res->fetch_assoc())
{
$styleString = "position: relative; left: " . $row['left'] . "px; top: " . $row['top'] . "px;";
}
}
$db->close()
?>
Hope that helps :) You should wait for a better method, before using this one.
EDIT:
You should add jQuery and jQuery UI for this example to work.
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
Any of the below will work
$var = "style=\"position: relative; left: 77px; top: -14px;\"";
$var = 'style="position: relative; left: 77px; top: -14px;"';
$var = addslashes('style="position: relative; left: 77px; top: -14px;"');
That last one is really pointless, but I figured I'd put it there for reference. I'd suggest the middle option as the best way.
The database insertion will take care of any necessary escaping, assuming you use prepared. statement.

Keep div in desired place with css, external content

Here is my problem.
I have a function, PHP class side, that reads all data from one table, create all divs with specific CSS ids, puts the data in place, and in one of them the data comes from an external source, an external php file.
So I do this in the code:
$Return .= "</div><div id='PostTitleComplete'><strong>Post Completo</strong></div><div id='PostText'>";
$Return .= include($row['PathFile']);
$Return .= "</div><div id='PostData'>";
All divs are opening and closing properly, all data worked correctly until i changed the data that used to be loaded fom the table to the div here the included file is know.
The external file only have HTML code generated by HTML copy from Visual studio and its all good to, ive used to use that html code in other places, no problem till know.
So, the CSS are the ones that follow:
This is the CSS used to hold the included file:
#PostText {
text-align:center;
padding: 15px;
word-wrap: break-word;
}
This is the parent of the above one:
#PostBody {
border: #00C 1px solid;
width:80%;
background:#FFFFFF;
float:left;
}
and this ones are the CSS from the included file:
One div includes the one, just like the name says.
#FirstOne {
border: #000080 1px solid;
color: #000;
font-family: 'Courier New', Courier, Monospace;
font-size: 9pt;
}
#SecondOne {
background: #000080;
color: #fff;
font-family: Verdana, Tahoma, Arial, sans-serif;
font-weight: bold;
padding: 2px 5px;
}
I used this same structure in one blog, but instead of an include file I used data from the table, so i think the problem are from the CSS. This is the result i get. This Giang Div is totally adjustable to the screen size, but it stays up there instead of here the arrow points and here the include is printed.
Well...
The value 1 is returned because the include-statement was performed successfully.
If the included file doesn't contain any code that needs to run, you can use file_get_contents():
$Return .= "</div><div id='PostTitleComplete'><strong>Post Completo</strong></div><div id='PostText'>";
$Return .= file_get_contents($row['PathFile']);
$Return .= "</div><div id='PostData'>";
As a reference, if the include file does have code that has to be executed, use output buffering:
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
return ob_get_clean();
}
return false;
}
$Return .= "</div><div id='PostTitleComplete'><strong>Post Completo</strong></div><div id='PostText'>";
$Return .= get_include_contents($row['PathFile']);
$Return .= "</div><div id='PostData'>";
Above code is taken from the PHP-manual (include-statement, example 6)
Instead of using incude try using file_get_content()
$Return .= "</div><div id='PostTitleComplete'><strong>Post Completo</strong></div>";
$Return .= "<div id='PostText'>";
$Return .= file_get_content($row['PathFile']);
$Return .= "</div><div id='PostData'>";

Return a variable from Php to JQuery Ajax

What I'm Trying to Do
I want to send a user's name and score to my php page where it inserts the data into the database, then spits out an html string showing the top ten scores.
What's Actually Happening
I enter the user's name and score and click submit. The data is sent over to php which then stores it in the database. The php file then constructs the string correctly which I can see by visiting the php page directly. However, the string is not returned back to my JQuery.
$("#leaderboardForm > input[type=image]").click(function() {
var theName = $("input#leaderboardName").val();
var theScore = $("input#theScore").val();
$.ajax({
type: "POST",
url: "../admin/submitleaderboard.php",
data: { leaderboardName: theName, theScore: theScore },
dataType: "html",
success: function(leaderboard) {
$("div#deadStats").html(leaderboard);
},
error: function() {
alert("An error occured submitting your score.");
}
});
});
$name = $_POST['leaderboardName'];
$score = $_POST['theScore'];
$sql="INSERT INTO leaderboard (leaderboard_date,leaderboard_name,leaderboard_score) VALUES (CURDATE(),'$name','$score')";
$result = mysql_query($sql);
$sql="SELECT * FROM leaderboard";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$leaderboard = $leaderboard . "<div style='width: 433px; padding: 8px; overflow: hidden; border: 1px solid #300; margin-bottom: 5px;'>";
$leaderboard = $leaderboard . "<div style='width: 200px; height: 30px; float: left;'>";
$leaderboard = $leaderboard . "<span style='color: #EFEFEF; font-weight: bold; font-size: 20px;'>" . $row['leaderboard_name'] . "</span></div>";
$leaderboard = $leaderboard . "<div style='width: 200px; height: 30px; float: left;'>";
$leaderboard = $leaderboard . "<span style='color: #A00; font-weight: bold; font-size: 20px;'>" . $row['leaderboard_score'] . "</span></div>";
$leaderboard = $leaderboard . "</div>";
}
echo $leaderboard;
mysql_close();
Your $.ajax method expects json response. You're returning text/plain. change last php line into:
echo json_encode($leaderboard);
It will work like that but to be really correct, you should probably add:
header('Content-Type: application/json');
To the top of your PHP page before anything is outputted too.
Update
I see you're reading through database rows and echoing it in php. Then you want to append it onto your page.
The easiest way to do this is to just remove dataType: "html" part in your $.ajax call. (Don't do any of the things above update title, I assumed you were returning an array there).
You say you are expecting html as an answer, yet you declare the datatype of your ajax request to json:
dataType: "json"
Try removing it, or setting it to html.
I think I may have found the solution.
For some reason, if I am using an input>image or input>submit as the trigger for my Ajax, I get the error. If I use a div/span/textfield or any other element that does not typically submit a form, it works just fine.
Can anybody elaborate on this?

Categories