PHP & SQL query to change CSS class

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 2543 Views - Last Post: 03 February 2014 - 12:16 PM Rate Topic: -----

#1 brianborn1968  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 76
  • Joined: 15-November 11

PHP & SQL query to change CSS class

Posted 31 January 2014 - 01:46 PM

I have many websites that use some of the same content blocks and instead of manually adding the content to each website, I thought it would be a good idea to have the content stored in a database as to only have one copy instead of multiple. This works great except for one issue... the images that are in the article sometimes need to be left aligned and other times right aligned depending on the site it is on.

My solution was to add the following code to the article's image CSS tag that is in the database. Once the page queries the database and pulls the content into the page, the variable would then be changed so the class in the CSS could format the image.

<p><img src="img/charleston.jpg" class="<?php echo $ImgClass01; ?>">Is it the delightful year-round climate? The almost-European feel of its downtown city streets? The overwhelming...</p>


However, when the database is queried, the webpage is only showing the text instead of the php code with variable when viewing the source code. Is this possible? Am I asking the question correctly?

Here is the code on the page...

    <?php
    $PageTitle = "Charleston, South Carolina | Local Towns";
    $PageDescription = "Charleston is rated the first most popular vacation destination in the United States, and it surely must rank in...";

    // 1. Create a database connection
    $link = mysql_connect ("localhost", "root", "");
    if (!$link) die("Could not connect: " . mysql_error());

    // 2. Select a database to use
    if (!mysql_select_db ("articleBank"))
      die("Problem with the database: " . mysql_error());

    // 3. Set up query for items to display
    $query = "SELECT article FROM `articles` WHERE ID = 1";

    // 4. Execute the query
    $result_set = mysql_query ($query);

    include ("theme/header.php");

    // value for the class within the article to be printed on the page
    $ImgClass01 = 'img-responsive img-rounded pull-right';

//Start a while loop to process all the rows
while ($row = mysql_fetch_assoc ($result_set))
{
    $article = $row['article'];
    echo $article; 
} //END WHILE

    // 5. Close Connection
    mysql_close();

    include ("theme/footer.php");
    ?>



Is This A Good Question/Topic? 0
  • +

Replies To: PHP & SQL query to change CSS class

#2 ArtificialSoldier  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1842
  • View blog
  • Posts: 5,793
  • Joined: 15-January 14

Re: PHP & SQL query to change CSS class

Posted 31 January 2014 - 02:35 PM

Why not always give the images the same class, but just change the various CSS sheets to align it differently?
Was This Post Helpful? 1
  • +
  • -

#3 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 13,493
  • Joined: 08-August 08

Re: PHP & SQL query to change CSS class

Posted 31 January 2014 - 02:39 PM

The functions you're using are deprecated because they're insecure. You need to use prepared statements. Here's a great tutorial on PDO.
After you've converted to PDO or MySQLi with prepared statements we can worry about any logic problems.

Oh, and web pages shouldn't see any PHP code. That's processed on the server.
Was This Post Helpful? 1
  • +
  • -

#4 brianborn1968  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 76
  • Joined: 15-November 11

Re: PHP & SQL query to change CSS class

Posted 01 February 2014 - 04:56 AM

View PostArtificialSoldier, on 31 January 2014 - 04:35 PM, said:

Why not always give the images the same class, but just change the various CSS sheets to align it differently?


All websites will be using bootstrap CSS. I do not want to add additional custom styles to every site.
Was This Post Helpful? 0
  • +
  • -

#5 brianborn1968  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 76
  • Joined: 15-November 11

Re: PHP & SQL query to change CSS class

Posted 01 February 2014 - 05:04 AM

View PostCTphpnwb, on 31 January 2014 - 04:39 PM, said:

The functions you're using are deprecated because they're insecure. You need to use prepared statements. Here's a great tutorial on PDO.
After you've converted to PDO or MySQLi with prepared statements we can worry about any logic problems.

Oh, and web pages shouldn't see any PHP code. That's processed on the server.


I learned about the deprecated code and security issues yesterday while searching for answers. However, it would be easier for me to get a working example first before trying to change. The reasoning is that I'm almost there with a working example. When I get stuck trying to convert to "PDO or MySQLi with prepared statements" and need to ask questions, I can provide an example of what I'm trying to do in hopes that is will help with feedback that isn't going to confuse me any more.

As for your comment "web pages shouldn't see any PHP code. That's processed on the server.", I'm aware of this and the reason I came here for help.
Was This Post Helpful? 0
  • +
  • -

#6 brianborn1968  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 76
  • Joined: 15-November 11

Re: PHP & SQL query to change CSS class

Posted 01 February 2014 - 05:33 AM

View PostCTphpnwb, on 31 January 2014 - 04:39 PM, said:

The functions you're using are deprecated because they're insecure. You need to use prepared statements. Here's a great tutorial on PDO.


Thanks for the link and have been reading it and will post new code soon and hopefully get some help finding a sollution to my challenge.
Was This Post Helpful? 0
  • +
  • -

#7 brianborn1968  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 76
  • Joined: 15-November 11

Re: PHP & SQL query to change CSS class

Posted 01 February 2014 - 05:52 AM

I'm still reading about PDO, but here is the new code I'm using that results in an error.

<?php
// Fill in all the info we need to connect to the database.
// This is the same info you need even if you're using the old mysql_ library.
$host = 'localhost';
$port = 3306; // This is the default port for MySQL
$database = 'articleBank';
$username = 'root';
$password = '';

// Construct the DSN, or "Data Source Name".  Really, it's just a fancy name
// for a string that says what type of server we're connecting to, and how
// to connect to it.  As long as the above is filled out, this line is all
// you need.
$dsn = "mysql:host=$host;port=$port;dbname=$database";

// Connect!
$db = new PDO($dsn, $username, $password);
?>

<!doctype html>
<html>
<head>
<title></title>
</head>
<body>

<?php
// value for the class within the article to be printed on the page
$ImgClass01 = 'img-responsive img-rounded pull-right';   // this is the variable I'm trying to add into the content that comes from the database.

$statement = $db->prepare("SELECT article FROM `articles` WHERE ID = ?");
$statement->execute(array($_POST['article']));	// I get the following error... "Undefined index: article" and I'm guessing because the field is not indexed in the database. Sometime this field could have a lot of content so I'm not sure which data type I should use here.

while ($result = $statement->fetchObject()) {
    echo $result->article;
    echo "<br />";
}
?>

</body>
</html>


If it helps, here is my database.

-- phpMyAdmin SQL Dump
-- version 4.0.4
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Feb 01, 2014 at 10:31 AM
-- Server version: 5.6.12-log
-- PHP Version: 5.4.16

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";


/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `articlebank`
--
CREATE DATABASE IF NOT EXISTS `articlebank` DEFAULT CHARACTER SET armscii8 COLLATE armscii8_general_ci;
USE `articlebank`;

-- --------------------------------------------------------

--
-- Table structure for table `articles`
--

CREATE TABLE IF NOT EXISTS `articles` (
  `ID` int(20) NOT NULL AUTO_INCREMENT,
  `Article` text NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB  DEFAULT CHARSET=armscii8 AUTO_INCREMENT=2 ;

--
-- Dumping data for table `articles`
--

INSERT INTO `articles` (`ID`, `Article`) VALUES
(1, '<p><img src="img/charleston-sc-bridge.jpg" width="300" height="200" class="<?php echo $ImgClass01; ?>">Is it the delightful year-round climate? The almost-European feel of its downtown city streets? The overwhelming amount of history lurking behind...</p>');

/*!40101 SET [email protected]_CHARACTER_SET_CLIENT */;
/*!40101 SET [email protected]_CHARACTER_SET_RESULTS */;
/*!40101 SET [email protected]_COLLATION_CONNECTION */;

Was This Post Helpful? 0
  • +
  • -

#8 Atli  Icon User is offline

  • Enhance Your Calm
  • member icon

Reputation: 4238
  • View blog
  • Posts: 7,216
  • Joined: 08-June 10

Re: PHP & SQL query to change CSS class

Posted 01 February 2014 - 06:51 AM

View Postbrianborn1968, on 01 February 2014 - 12:52 PM, said:

$statement->execute(array($_POST['article']));	
// I get the following error... "Undefined index: article" and I'm guessing because the field is not indexed in the database. Sometime this field could have a lot of content so I'm not sure which data type I should use here.


No, that would be because the POST data does not contain a "article" field. The $_POST array stores incoming HTTP POST data, usually from a HTML <form> element.

You should always check whether user input exists before trying to use it. Read up on the isset and the empty functions. The array_key_exists function is also sometimes used, but I'm not a fan of that method.
// Option #1: Only makes sure the field was sent.
if (isset($_POST["article"])) {
    // Do stuff with $_POST["article"];
}

// Option #2: Makes sure the field was sent, and that it
// has a "non-empty" value. (Empty strings and 0 would be
// considered empty.)
if (!empty($_POST["article"])) {
    // Do stuff with $_POST["article"];
}

// Option #3: Same as option #1, just done differently.
if (array_key_exists("article", $_POST)) {
    // Do stuff with $_POST["article"];
}


Was This Post Helpful? 0
  • +
  • -

#9 brianborn1968  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 76
  • Joined: 15-November 11

Re: PHP & SQL query to change CSS class

Posted 01 February 2014 - 09:56 PM

View PostCTphpnwb, on 31 January 2014 - 04:39 PM, said:

The functions you're using are deprecated because they're insecure. You need to use prepared statements. Here's a great tutorial on PDO.
After you've converted to PDO or MySQLi with prepared statements we can worry about any logic problems.

Oh, and web pages shouldn't see any PHP code. That's processed on the server.


I spent most of the day reading and watching tutorial videos on the subject of PDO. Since I've completed the task, I hope you will help me with the logic now. Also by letting me know if I got all this correct.

<?php
try {
	$db = new PDO('mysql:host=localhost;dbname=articlebank', 'root', '');
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
	echo $e->getMessage();
	die();
}

$query = $db->prepare("SELECT Article FROM articles WHERE ID = ?");
$query->execute(array("1"));   //changing this number will change the article that is pulled from the database.

while($row = $query->fetch(PDO::FETCH_OBJ)) {
	echo $row->Article;
}
?>


I stripped out all the HTML to consolidate the code for easier reading, but can add it back if needed. Back to the original question, the objective here is to pull an article from the database that includes HTML. Within the HTML, I will need to change the class to a variable that will be on the page/file. If not a variable, hopefully some options as how to accomplish this task.
Was This Post Helpful? 0
  • +
  • -

#10 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 4138
  • View blog
  • Posts: 13,074
  • Joined: 08-June 10

Re: PHP & SQL query to change CSS class

Posted 02 February 2014 - 01:36 AM

the easiest option I see is to put a placeholder where the class should go and then replace it with the actual value by str_replace() or printf().

with regards to the PHP code:
- wrap all your code in a single try…catch, that will also catch subsequent exceptions (then you also don’t need to die())
- error messages are not for the user to see, since they may contain sensitive information. put those in a log or an email
- you can loop over a PDO result directly with foreach()
// you only have one value ...
$query->setFetchMode(PDO::FETCH_COLUMN, 0);
foreach($query as $row)
{
    echo $row;
}

- since ID is likely to be an INT, I would always prefer explicit binding
$query = $db->prepare("SELECT Article FROM articles WHERE ID = ?");
$query->bindValue(1, 1, PDO::PARAM_INT);
$query->execute();

This post has been edited by Dormilich: 02 February 2014 - 10:47 AM
Reason for edit:: Fixed error on the setFetchMode() call

Was This Post Helpful? 2
  • +
  • -

#11 brianborn1968  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 76
  • Joined: 15-November 11

Re: PHP & SQL query to change CSS class

Posted 02 February 2014 - 06:37 AM

View PostDormilich, on 02 February 2014 - 03:36 AM, said:

the easiest option I see is to put a placeholder where the class should go and then replace it with the actual value by str_replace() or printf().


Looks like I have some more research to do as I know what a placeholder means, but not in this instance. Soon I will know.

Replacing the code with your suggestion generates an error, but that is part of the learning part of all this.
SQLSTATE[HY000]: General error: fetch mode requires the colno argument



View PostDormilich, on 02 February 2014 - 03:36 AM, said:

with regards to the PHP code:
- wrap all your code in a single try…catch, that will also catch subsequent exceptions (then you also don’t need to die())
- error messages are not for the user to see, since they may contain sensitive information. put those in a log or an email
- you can loop over a PDO result directly with foreach()
// you only have one value ...
$query->setFetchMode(PDO::FETCH_COLUMN);
foreach($query as $row)
{
    echo $row;
}


Thanks for the tip on the try/catch as that sounds logical. This is the first time I have ever used this. As for putting the errors in a log or email, I'm not sure how to do that.



View PostDormilich, on 02 February 2014 - 03:36 AM, said:

since ID is likely to be an INT, I would always prefer explicit binding
$query = $db->prepare("SELECT Article FROM articles WHERE ID = ?");
$query->bindValue(1, 1, PDO::PARAM_INT);
$query->execute();


Some of the videos I watched yesterday used the bindValue and every time I tried using it, I always ended up with errors. I'm doing something wrong here.
Was This Post Helpful? 0
  • +
  • -

#12 CTphpnwb  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3717
  • View blog
  • Posts: 13,493
  • Joined: 08-August 08

Re: PHP & SQL query to change CSS class

Posted 02 February 2014 - 06:43 AM

error_log("your error here");

This will put whatever you like in the error log file. If you want to put an array in the log file you might do this:
error_log(print_r($arrayname,1));


Was This Post Helpful? 1
  • +
  • -

#13 brianborn1968  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 76
  • Joined: 15-November 11

Re: PHP & SQL query to change CSS class

Posted 02 February 2014 - 07:22 AM

View PostDormilich, on 02 February 2014 - 03:36 AM, said:

the easiest option I see is to put a placeholder where the class should go and then replace it with the actual value by str_replace() or printf().


One step at a time and this seems to be a good place to start. After reading about str_replace() and using the code I already had, the following seems like I'm on the right path, but confused with all the examples and different views seen by searching. Also I would like to see how the foreach loops works compared to while, but it needs to work first before I can understand it.

while($row = $query->fetch(PDO::FETCH_OBJ)) {
	$search = "%imagecss%";
	$replace = "img-responsive img-rounded pull-right";
	$subject = $row->Article;
	$newstring = str_replace("$search", "$replace", "$subject");
	echo $newstring;
}

This post has been edited by brianborn1968: 02 February 2014 - 07:28 AM

Was This Post Helpful? 0
  • +
  • -

#14 brianborn1968  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 76
  • Joined: 15-November 11

Re: PHP & SQL query to change CSS class

Posted 02 February 2014 - 07:39 AM

View Postbrianborn1968, on 02 February 2014 - 09:22 AM, said:

while($row = $query->fetch(PDO::FETCH_OBJ)) {
	$search = "%imagecss%";
	$replace = "img-responsive img-rounded pull-right";
	$subject = $row->Article;
	$newstring = str_replace("$search", "$replace", "$subject");
	echo $newstring;
}


or use either...

while($row = $query->fetch(PDO::FETCH_OBJ)) {
	$search = "%imagecss%";
	$replace = "img-responsive img-rounded pull-right";
	$subject = $row->Article;
	print_r(str_replace("$search", "$replace", "$subject"));
}


or the shortened version...

while($row = $query->fetch(PDO::FETCH_OBJ)) {
	print_r(str_replace("%imagecss%", "img-responsive img-rounded pull-right", "$row->Article"));
}


Now to test the error exceptions with email and log.

This post has been edited by brianborn1968: 02 February 2014 - 07:41 AM

Was This Post Helpful? 0
  • +
  • -

#15 brianborn1968  Icon User is offline

  • D.I.C Head

Reputation: 0
  • View blog
  • Posts: 76
  • Joined: 15-November 11

Re: PHP & SQL query to change CSS class

Posted 02 February 2014 - 08:24 AM

Thanks to everyone who helped me with finding a solution to this challenge. The solution is workable and will consider this thread closed, but will refine this as I continue my self education.

I have posted this challenge on several different forums, but I must say that I felt most welcome here at dreamincode.com and will be returning often to learn all that I can. Hopefully I get good enough to be able to share my own knowledge with others who are in need.

To those who helped...

ArtificialSoldier, thanks for the tip about changing the various css sheets, but I wanted a more complex way of doing it and by doing so, I learned a lot from taking an alternate path instead of taking the easy route that I already knew.

CTphpnwb, thanks for the link for the tutorial on PDO. That set me on an all day adventure and I learned a lot. I'm not interested in finding any solution, I strive to find the best sollution. However, sometimes one needs to learn any sollution before being able to progress further. Also thanks for the tips on error logging and I saved a link from the PHP manual for further study on this subject.

Atli, the information you provide on the "isset" and "empty" functions were not needed in this challenge, but I reviewed your examples and the pages in the PHP Manual and I can already see some uses for these function. Thank you for helping!

Dormilich, it was your reply that put me on the path of using a placeholder and the "str_replace()" and the "printf()" functions that ultimately solved the challenge that I had. I still need to further my study into your comments about the "foreach" loop and "bindValue" and will eventually get there. Since I have a working sollution now, I'm not opposed if you want to rewrite my code to show another way for it to work. I would love to see it.

Again, thank you all for your help!

Brian
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2