skip to Main Content

I am creating a website which uses php to get data from a phpmyadmin database and use the info from this database in my html.

I have this php query which finds the value from the ‘ID’ field and then creates a variable called ‘$studentID’ with this value (which will be the number 2 in this case):

$result = $conn->query("select * from logins where usertype = 
'student'");
$row = $result->fetch_array();
$studentid = $row['id'];

Then I have attempted to use this variable as the ID for an html element called ‘rowcontainer’:

<div class = 'rowcontainer' id = "<?php echo $studentid; ?> "></div>

Then I have set the background colour of this element using the id "2" to blue (using css):

#2 {
background-color: blue;
}

.rowcontainer {
width: 100%;
height: 30px;
}

When I use the inspect tool, the element ‘rowcontainer’ does appear to have an id of "2" like I want but the colour is still the default white and not blue.

inspect element html

inspect element css

Is there something I have missed, or a better way to achieve this?

2

Answers


  1. First you need to know that you are using class & ID for for styling the same div. The answer of your question is dont pass numerical PHP values to html ID. In your case you are passing 2. Append this variable with some text then it will work.

    <!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    <style>
      .rowcontainer {
        width: 100%;
        height: 30px;
        }
     #2yes{
        background-color: blue;
        color: red;
        }
    </style>
    </head>
    <body>
       <h1 class='rowcontainer' id="<?php print $id.'yes'" ?> > Hello  </h1>
    </body>
    </html>
    
    Login or Signup to reply.
  2. While HTML5 is happy with an id starting with a digit it appears that CSS3 is not.

    If you do stick with having and id that starts with a digit you can get CSS to pick it up by using an attribute selector – this says ‘choose the element that has an id attribute with that string’.

    [id='2']{
    background-color: blue;
    }
    
    .rowcontainer {
    width: 100%;
    height: 30px;
    }
    <div id="2">id is 2</div>

    Or you can prepend (not append) the id with an a-z character or string in your php like this:

    <div class = 'rowcontainer' id = "id<?php echo $studentid; ?>"></div>
    

    and then select this div by

    #id2 {
        background-color: blue;
        }
    

    Incidentally, beware of adding spurious space characters to strings. Your PHP puts a space after the 2. In some cases spaces matter (string matching on the whole) in some they don’t.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search