0

So i read article on css-tricks.com˙(http://css-tricks.com/css-variables-with-php/) about PHP in CSS and I tried it myself. I'm having problem structuring it. To be specific, i'm using Sql to take image from database and use result as a background image. Like this:

<?php

header("Content-type: text/css; charset: UTF-8");

$con = mysql_connect("localhost","root","");
if (!$con)
{
    die('Could not connect: ' . mysql_error());
}
mysql_select_db("login", $con);
$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result))
{
?>

Then goes my css, i will just write needed ID:

#user {
background: url(../img/<?php echo $row['cover']; ?>) fixed;
}

And at the end, I close connection:

<?php
};

mysql_close($con);

?>

Everything works except css is outputted double, that is listed twice.Can anyone point the problem? Thanks.

5
  • after $result = run echo mysql_num_rows($result) and tell us the output. Commented Mar 14, 2014 at 17:54
  • your while loop might be running 2 times(fetching 2 rows) Commented Mar 14, 2014 at 17:54
  • It's a 5 year old article. I suggest you use a more recent tutorial for learning. Also, use the MySQLi or PDO extensions with prepared statements and bind variables, rather than learning using the old, deprecated MySQL extension. Commented Mar 14, 2014 at 17:55
  • I haven't even looked at the date of article -.- i guess I need to start. Commented Mar 14, 2014 at 18:00
  • clearly you have 2 rows with cover as an array key... Commented Mar 14, 2014 at 18:02

2 Answers 2

1

you're going to create:

   background: url(../img/<?php echo $row['cover']; ?>) fixed;

for each row returned by the database. you need to limit the results, either in the sql like:

 $result = mysql_query("SELECT * FROM users where userId = $userId");

or in the php like:

if ($row['userId']==$userId){ ?>
     background: url(../img/<?php echo $row['cover']; ?>) fixed;
<?php}
Sign up to request clarification or add additional context in comments.

Comments

0

It will return as many values as you have in your DB table "users"

If you only want 1 result you need to write

"SELECT * FROM users LIMIT 1"

You dont have a "WHERE" statement for the query?

"SELECT * FROM users WHERE SOME_COLUMN = $your_variable "

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.