Skip to content
Advertisement

How can I give an html element an ID taken from a php variable?

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement