Solved

PHP Function to create a CSS Class

Posted on 2013-11-09
19
456 Views
Last Modified: 2013-12-02
I would like to create a function, that creates a css Class depending upon a MySQL Query return:
My PHP Query:
class Assets {		
		function Color(#color Value) {
			$pdo = new PDO("mysql:host=localhost.......");
			$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
			$sql = "SELECT id, name, color
					FROM assets";
			$asset = $pdo->prepare($sql);
			
			try	{
				$asset->execute();	
				$results = $asset->fetch();
				return $results;
			}
			catch(PDOException $a) {
   				echo 'ERROR: ' . $a->getMessage();
			}
			
			////  HERE IS WHERE I'M STUCK
			
			while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
	$ac = $row['color'];
			<style>
			(class Name) .$ac {
			    -moz-box-shadow:inset 0 0 10px 0 $ac;
    			-webkit-box-shadow:inset 0 0 10px 0 $ac;
    			box-shadow:inset 0 0 10px 0 $ac;
   				 border: 1px solid $ac;
   				 display: block;
			</style>
			}	
		}
}

	$asset = new ShowAssets();
	$ass = $asset->Color();
	
?>
<table>
	<?php foreach ($ass->color as $col) {
		echo '<tr>
		<td class="'. $col .'"/></td>
		</tr>';	
	}
	?>
</table>

Open in new window


I want to create individual classes for each item returned.
0
Comment
Question by:rgranlund
  • 7
  • 6
  • 3
  • +2
19 Comments
 
LVL 58

Expert Comment

by:Gary
Comment Utility
What is (class Name) supposed to be?
0
 
LVL 7

Author Comment

by:rgranlund
Comment Utility
ForEach iteration of $row['color'] I want to create a specific style class with variable as a name. So depending upon the content of the return, it will give a TD a specific class.
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
Sooo...
echo '<style>'
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
	$ac = $row['color'];
	echo '	.$ac {
			    -moz-box-shadow:inset 0 0 10px 0 $ac;
    			-webkit-box-shadow:inset 0 0 10px 0 $ac;
    			box-shadow:inset 0 0 10px 0 $ac;
   				 border: 1px solid $ac;
   				 display: block;
		}';
}
echo '</style>';

Open in new window


Edited
0
 
LVL 7

Author Comment

by:rgranlund
Comment Utility
Yes, but how do I pass that with a function?
<?php
	$asset = new ShowAssets();
	$ass = $asset->Color();
	
?>
<table>
	<?php foreach ($ass->color as $col) {
		echo '<tr>
		<td class="'. $col .'"/></td>
		</tr>';	
	}
	?>
</table>

Open in new window

0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
$col= array();

echo '<style>'
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
	$ac = $row['color'];
	array_push($col, $ac);

	echo '	.$ac {
			    -moz-box-shadow:inset 0 0 10px 0 $ac;
    			-webkit-box-shadow:inset 0 0 10px 0 $ac;
    			box-shadow:inset 0 0 10px 0 $ac;
   				 border: 1px solid $ac;
   				 display: block;
		}';
}
echo '</style>';
return $col;

Open in new window

0
 
LVL 7

Author Comment

by:rgranlund
Comment Utility
So are you saying I do it like this:
$col= array();

echo '<style>'
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
	$ac = $row['color'];
	array_push($col, $ac);

	echo '	.$ac {
			    -moz-box-shadow:inset 0 0 10px 0 $ac;
    			-webkit-box-shadow:inset 0 0 10px 0 $ac;
    			box-shadow:inset 0 0 10px 0 $ac;
   				 border: 1px solid $ac;
   				 display: block;
		}';
}
echo '</style>';

return $col;
<td class="$col"></td>

Open in new window


I'm a little confused now cause I will have a list of 100 items and each TD will contain a name and be a specific color. How do I loop through numerous TD's?
0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
No, like this.

class Assets {		
	function Color(#color Value) {
		$pdo = new PDO("mysql:host=localhost.......");
		$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
		$sql = "SELECT id, name, color
				FROM assets";
		$asset = $pdo->prepare($sql);
		
		try	{
			$asset->execute();	
			$results = $asset->fetch();
			return $results;
		}
		catch(PDOException $a) {
  				echo 'ERROR: ' . $a->getMessage();
		}
		
		////  HERE IS WHERE I'M STUCK
			
		$col= array();

		echo '<style>'
		while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
			$ac = $row['color'];
			array_push($col, $ac);

			echo '	.$ac {
				-moz-box-shadow:inset 0 0 10px 0 $ac;
	    			-webkit-box-shadow:inset 0 0 10px 0 $ac;
	    			box-shadow:inset 0 0 10px 0 $ac;
   				border: 1px solid $ac;
   				display: block;
			}';
		}
		echo '</style>';
		return $col; 

	}
}

$asset = new ShowAssets();
$ass = $asset->Color();
	
?>
<table>
	<?php foreach ($ass->color as $col) {
		echo '<tr>
		<td class="'. $col .'"/></td>
		</tr>';	
	}
	?>
</table>

Open in new window

0
 
LVL 7

Author Comment

by:rgranlund
Comment Utility
I get the ERROR:
 Invalid argument supplied for foreach()

This is everything I have so far:
function:
	function Color() {
		$pdo = new PDO("........");
		$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
		$sql = "SELECT *
				FROM assets";
		$asset = $pdo->prepare($sql);
		
		try	{
			$asset->execute();	
			$results = $asset->fetch();
			return $results;
		}
		catch(PDOException $a) {
  				echo 'ERROR: ' . $a->getMessage();
		}
		
		////  HERE IS WHERE I'M STUCK
			
		$col= array();

		echo '<style>';
		while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
			$ac = $row['color'];
			array_push($col, $ac);

			echo '	.$ac {
				-moz-box-shadow:inset 0 0 10px 0 $ac;
	    			-webkit-box-shadow:inset 0 0 10px 0 $ac;
	    			box-shadow:inset 0 0 10px 0 $ac;
   				border: 1px solid $ac;
   				display: block;
			}';
		}
		echo '</style>';
		return $col; 

	}	

Open in new window


CODE:
$asset = new ShowAssets();
$ass = $asset->Color();
 
foreach ($ass->color as $col) {
		echo '<tr>
		<td align="left"><a href="delete_asset.php?id=' . $ass->asset_id . '"><img src="img/icons/delete.png"/></a></td>
		<td align="left"><a href="edit_asset.php?id=' . $ass->asset_id . '"><img src="img/icons/edit-icon.png"/></a></td>
		<td align="left" class="'. $col .'"/>' . $ass->asset_name . '</td>
		<td align="left" class="'. $col .'"/>' . $ass->asset_type . '</td>
		<td align="left">' . $ass->asset_desc . '</td>
	</tr>
	';
}

Open in new window

0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
foreach ($ass->color as $col) {

should be
foreach ($ass as $col) {


Just to be sure do a dump of $ass to make sure their is data returned.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 7

Author Comment

by:rgranlund
Comment Utility
Ok, getting there.  However, it only fetches the very first record and repeats it. Please look at the following.  I don't think I have it right.

foreach ($ass as $col) {
		echo '<tr>
		<td align="left"><a href="delete_asset.php?id=' . $ass->asset_id . '"><img src="img/icons/delete.png"/></a></td>
		<td align="left"><a href="edit_asset.php?id=' . $ass->asset_id . '"><img src="img/icons/edit-icon.png"/></a></td>
		<td align="left" class="'. $col .'"/>' . $ass->asset_name . '</td>
		<td align="left" class="'. $col .'"/>' . $ass->asset_type . '</td>
		<td align="left">' . $ass->asset_desc . '</td>
	</tr>
	';
}

Open in new window

0
 
LVL 58

Expert Comment

by:Gary
Comment Utility
Now you have added extra fields, thought you just wanted the class name.

Change
array_push($col, $ac);
to
array_push($col, $row);
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
Comment Utility
I must be missing something.  Why is it necessary to incur all that extra overhead generating all those styles instead of having them in a stylesheet, and then just applying the class to the table elements as they are generated.

Does every row have a unique color or are their duplicates?  Duplicates would mean generating the exact same class entry in some cases.

It also looks like a separate style tag for each row.  That could be a problem because you will end up with a bloated stylesheet object in the DOM.  Some version of IE have a limit on the number of stylesheets, but I cannot remember if that is just for external stylesheets or the number of entries in the stylesheet collection of the DOM.

Anyway this looks like it is being over complicated unles I am missing something fundamental.

Cd&
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Something here is unnecessarily complicated.  I think if we had a "higher-level" view of the problem it might make sense to approach this a bit differently.

Also, the combination of PDO and MySQLi is a sure recipe for confusion.  You want to choose one or the other.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Couple of other thoughts...
Invalid argument supplied for foreach()
You can use var_dump() to find out what is contained in the variable that caused the message.  Often this appears when the iterator (foreach) expects an array or object, but is given a string or boolean.

And there is a special meaning to single quotes in PHP.  They are used to prevent variable substution.  This article explains it.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_12241-Quotation-Marks-in-PHP.html

And if you use PDO correctly, you can get the entire results set back as an array without having to use the iterators to retrieve each rows one-at-a-time.
0
 
LVL 7

Author Comment

by:rgranlund
Comment Utility
@all, I will be cleaning this up so it is strictly PDO, however, I'm just trying to piece it together so I understand how to do it.  Here is the issue;
When an asset (Truck Name or Employee Name) is entered into the DB, there is a color picker that you can choose a unique color to identify that asset. Later on when you query the DB for Certain assets (Certain Trucks or Employees) they are listed in a table for structural purposes.  The <td></td> That contains the Asset Name is styled with their color.

So, the color HEX is pulled out of the DB with name, creates a unique style and assigns it to the <TD>.

I want to have this all within a function.  I will submit more code as I clean it up but any advice will be appreciated.
0
 
LVL 7

Author Comment

by:rgranlund
Comment Utility
@all
This is what I have and it works 100% the way I want it to.  however, please have a look at my code and let me know if there is anything I can do to tighten it up and/or make it better. Thanks in advance!
function Color() {
		$pdo = new PDO(".........");
		$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
		
		$sql = "SELECT asset_id, asset_name, asset_type, asset_desc, color
				FROM assets";
		$asset = $pdo->prepare($sql);
		
		try	{
			$asset->execute();	
			 while($row = $asset->fetch()):
			 	$ac = $row->color;
				 if($ac != "ffffff") {
				 	$st = 'style="-moz-box-shadow:inset 0 0 20px 0 #'.$ac.';
	    						-webkit-box-shadow:inset 0 0 20px 0 #'.$ac.';
	    						box-shadow:inset 0 0 20px 0 #'.$ac.';
   								border: 1px solid #'.$ac.';
   								vertical-align:middle;"';
   					} else {
   						$st ='';
   					}
					
					echo '<tr>
						<td align="left"'; echo $st.'><a href="delete_asset.php?id=' . $row->asset_id . '"><img src="img/icons/delete.png"/></a></td>
						<td align="left"'; echo $st.'><a href="edit_asset.php?id=' . $row->asset_id . '"><img src="img/icons/edit-icon.png"/></a></td>
						<td align="left"'; echo $st.'>' . $row->asset_name . '</td>
						<td align="left"'; echo $st.'>' . $row->asset_type . '</td>
						<td align="left"'; echo $st.'>' . $row->asset_desc . '</td>
					</tr>';
			 endwhile;	
		}
		catch(PDOException $a) {
  			echo 'ERROR: ' . $a->getMessage();
		}

	}	

Open in new window

0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Some semi-random thoughts...

My guess is that you could use a PDO connection elsewhere in the script, so it might make sense to move the connection outside the function and use a singleton connection object.

As a general rule, you would want to isolate functionality as much as possible.  It's commonly expressed "Code to the interface."  So while this function retrieves information from the data base and produces "n" rows of table output it would be interesting to consider its role in the larger context of the script that builds the web page.  Or to put it another way, if there is only one place in the script that calls this function, why even have a function?

If you include the align= attribute in your HTML, you've created HTML that will not validate and cannot be overridden in the style sheet.  Best to omit that sort of thing and use CSS appropriately for alignment.
0
 
LVL 53

Expert Comment

by:COBOLdinosaur
Comment Utility
That produces unbelievable ugly, inefficient and unmaintainable markup.  There is absolutely no logical reason you cannot just have a stylesheet with the possible colors in classes and set a class in the tags instead of making a mess with inline styling.

However if it works, I guess that is all that matters; but I would be ashamed to put my name on a mess like that.

Cd&
0
 
LVL 33

Accepted Solution

by:
Slick812 earned 500 total points
Comment Utility
greetings   rgranlund, ,  I see what you are trying to do, and have distinctive colors for each row , but you may should just have each ROW <tr> have the background color, as having each <td> with colors makes for repetitive views?

you have the code in your post to do this already, what I do is instead of ECHO out I use TWO separate strings to get the <style> and <table> output and then echo them out later, to separate the the style from the table
any how, here is some code with your <td> structures-colors that works on my server -
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html><head><title>Color Tables TD</title></head>
<body bgcolor="#d0e0ff"><h2>Color Tables TD</h2>
<p>
<?php
$dbcon = 'mysql:host=mysql.sql.com; dbname=new_go';
$user = 'me';
$password = 'passw';

// array data to insert to table
$inDB = array(array(123, 'name1', 'type1', 'desc for first', 'bb0000'),
  array(223, 'name two', 'type two', ' second desc', '00bb00'),
  array(323, 'name3', 'type 3', 'desc Three', '0000bb'),
  array(423, 'name four', 'type four', 'Fourth desc', 'bb00bb'));


try {$dbo = new PDO($dbcon, $user, $password, array(PDO::ATTR_EMULATE_PREPARES => false));
  $dbo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $dbo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);

// the TABLE creatin code below is JUST FOR ME to test this, 
// DO NOT do this - CREATE TEMPORARY TABLE - or the INSERT in your code
  $sql = "CREATE TEMPORARY TABLE IF NOT EXISTS assets (
    id int(11) NOT NULL AUTO_INCREMENT,
    asset_id int(11) NOT NULL DEFAULT '0',
    asset_name varchar(16) NOT NULL DEFAULT 'an',
    asset_type varchar(16) NOT NULL DEFAULT 'at',
    asset_desc varchar(32) NOT NULL DEFAULT 'ad',
    color varchar(8) NOT NULL DEFAULT '000000',
    sFLAG int(1) NOT NULL DEFAULT '0',
    PRIMARY KEY (id)) ENGINE=MEMORY";

$dbo->query($sql);

$sql = 'INSERT INTO assets (asset_id, asset_name, asset_type, asset_desc, color) VALUES (?, ?, ?, ?, ?)';
$stmt = $dbo->prepare($sql);
for ($i=0; $i < count($inDB); ++$i) $stmt->execute($inDB[$i]);

echo 'SELECT OUTPUT BELOW -<br />';
$sql = 'SELECT asset_id, asset_name, asset_type, asset_desc, color FROM assets';
$st = ''; // create empty strings to ECHO later
$trs = '';

// you do not need to do prepare and execute without VARIABLE input
foreach ($dbo->query($sql) as $row) { 
  $ac = $row->color;
  if($ac != "ffffff") {
  $st .= '.c'.$ac.'{}.c'.$ac.' td {-moz-box-shadow:inset 0 0 20px 0 #'.$ac.';
  -webkit-box-shadow:inset 0 0 20px 0 #'.$ac.';
  box-shadow:inset 0 0 20px 0 #'.$ac.';
  border: 1px solid #'.$ac.';
  vertical-align:middle;
  text-align:left;}
  ';
  }
					
  $trs .= '<tr class="c'.$ac.'">
  <td><a href="delete_asset.php?id=' . $row->asset_id . '"><img src="img/icons/delete.png" alt="delete"/></a></td>
  <td><a href="edit_asset.php?id=' . $row->asset_id . '"><img src="img/icons/edit-icon.png" alt="edit"/></a></td>
  <td>' . $row->asset_name . '</td>
  <td>' . $row->asset_type . '</td>
  <td>' . $row->asset_desc . '</td>
  </tr>
  ';
  }


  } catch (PDOException $e) {echo 'PDO ERROR: '.$e->getMessage().'<br />';}

echo '<style>
'.$st.'
</style>';
echo '
<table>
'.$trs.'
</table>';

?>
</p>THE END
</body></html>

Open in new window

This looks like it does the <td> color and box-shadow as your first code,
be sure that you do NOT do the TABLE creation code !
AND DO NOT do the INSERT code in your code, since you already have the TABLE assets in you DB !


I use this CSS mechanism to have less code write in the <td> -

.cbb0000{}
/* below does ALL <td> inside a <tr>
.cbb0000 td {-moz-box-shadow:inset 0 0 20px 0 #bb0000;
  -webkit-box-shadow:inset 0 0 20px 0 #bb0000;
  box-shadow:inset 0 0 20px 0 #bb0000;
  border: 1px solid #bb0000;
  vertical-align:middle;
  text-align:left;}

You really should reconsider having a CLASS with just one function in it. I did not bother to have my code in a function since it uses a PDO database connection, seems like a function might be problem for some PDO stuff? ?

ask questions if you need more info.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now