0

I have this PHP snippet that makes an <li> with some id which is chosen by mysqli_query fetched row. It looks like this:

while($row=mysqli_fetch_array($run_query)){
  $name=$row['company_name'];
  echo "<li><a href='#' id=".$name." class='category_sidebar2'>$name</a></li>";
}

When the $name is a single entity like Dell or Facebook, it creates the <li> just fine, but when the $name is a space-separated value like "Tata Steel" or something, it creates the <li> with the id just the first value before the space.

For example, if $name is "Tata Steel", it echoes

<li><a href='#' id='Tata'></li>

and not

<li><a href='#' id='Tata Steel'></li>

How do I get around this?

Barmar
  • 741,623
  • 53
  • 500
  • 612
Satyam Raj
  • 61
  • 1
  • 11
  • 4
    Spaces are not valid in the `id` attribute. Are you sure that it's not your browser that is only showing you the first word? – Sean Bright Jun 30 '17 at 18:03
  • https://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html – apokryfos Jun 30 '17 at 18:03
  • Really sorry, it was silly on my side. Should use class then, right? – Satyam Raj Jun 30 '17 at 18:04
  • the second answer seems to solve the problem. why's that? – Satyam Raj Jun 30 '17 at 18:07
  • @SatyamRaj attributes need to be enclosed in quotes. However even though it's working, its still not well formatted HTML. You should remove replace spaces with something else. Why do you need to put that in the Id anyway? Wouldn't putting the row identifier there make more sense? – apokryfos Jun 30 '17 at 18:11

1 Answers1

1

You need to put quotes around an attribute if it contains spaces. Otherwise, the space will end the attribute. You should just get in the habit of always putting quotes around attribute (like you did for href and class).

while($row=mysqli_fetch_array($run_query)){
  $name=$row['company_name'];
  echo "<li><a href='#' id='".$name."' class='category_sidebar2'>$name</a></li>";
}

However, as mentioned in the comments, spaces around allowed in the id attribute. You could replace the space with some other character, e.g.

$name = str_replace(' ', '_', $row['company_name']);
Barmar
  • 741,623
  • 53
  • 500
  • 612