-4

I have the following PHP code that fill table from mySQL database

<?php               
     while($res = mysqli_fetch_array($result)) {         
         echo "<tr>";
         echo "<td>".$res['id']."</td>";
         echo "<td>".$res['name']."</td>";
         echo "<td>".$res['number']."</td>";
         echo "<td>".$res['nid']."</td>";     
 }
 ?>  

Using CSS, How can I change background color for nid field?

I'm has trying the below, but it doesn't work:

echo "<td style="background-color:red" >".$res['nid']."</td>";
Abdulsalam Elsharif
  • 4,773
  • 7
  • 32
  • 66

4 Answers4

2

Try this

echo "<td style='background-color:red' >".$res['nid']."</td>";
Bonish Koirala
  • 641
  • 5
  • 16
1

Use this:

echo "<td style='background-color:red'>".$res['nid']."</td>";
Marty1452
  • 430
  • 5
  • 19
1

You can use any of the following examples.

Use different "quotes" for attributes

echo '<td style="background-color:red">'.$res['nid'].'</td>';

Or use the Complex (curly) syntax

echo "<td style='background-color:red'>{$res['nid']}</td>";

Or you can escape the double quotes in the string

echo "<td style=\"background-color:red\">".$res['nid']."</td>";

Or use multiple techniques

echo "<td style=\"background-color:red\">{$res['nid']}</td>";

Do note that the {} can only be used in a string/ double quotes.

Your code doesn't work since everytime you use the same quote after the first you break out of the string. So with:

"<td style="background-color:red" >".$res['nid']."</td>";

PHP thinks "<td style=" is a string and background-color:red is PHP code which it isn't. You can see that in the code highlighting aswell. Maybe this question will help you explain it a bit better.

SuperDJ
  • 7,488
  • 11
  • 40
  • 74
  • Funny how everyone is giving a solution, but doesn't explain why it's not working. If you explain not to or how to mix quotes, I'll upvote this answer. – DigiLive Oct 28 '18 at 11:56
0

I think you need to escape the " character. The escaping character is \, so you have to use it as a prefix for your ". For example:

<?php               
     $val1="I want this normal";
     $val2="I want this normal";
     $val3="I want this normal";
     $val4="I want this RED";

     echo "<table><tr>";
     echo "<td>".$val1."</td>";
     echo "<td>".$val2."</td>";
     echo "<td>".$val3."</td>";
     echo "<td style=\"background-color:red;\" >".$val4."</td>"; //Change the " for '  or escape " with \
     echo "</tr></table>";  //And don't forget to close this tag too ;)

?>

In your code it would be something like:

<?php               
 while($res = mysqli_fetch_array($result)) {         
     echo "<tr>";
     echo "<td>".$res['id']."</td>";
     echo "<td>".$res['name']."</td>";
     echo "<td>".$res['number']."</td>";
     echo "<td style=\"background-color:red\" >".$res['nid']."</td>";     

} ?>

Mariela
  • 134
  • 2
  • 13