pheromix
pheromix

Reputation: 19347

Tooltip is broken when encountering apostrophe

I want to display links of images , and their title attribute are from a MySQL database :

for ($i=0; $i<$ret['cnt']; $i++)
{
    $html .= "<td width='15'><a href='" . HTTP_MAIN . $ret[$i]['menu_url'] . "?action=".$ret[$i]['menu_action']."'><img src='" . HTTP_ICONES . $ret[$i]["menu_icone_img"] . "' title='".$ret[$i]["menu_icone_title"] . "' width='12' height='12'></a></td>";
}

As you can see the title attribute is from $ret[$i]["menu_icone_title"]. Here is the query :

$sSQL = "SELECT menu_icone_img, menu_icone_title, menu_url, menu_action
                FROM menu 
                WHERE menu_icone_flag = 1
                ORDER BY menu_icone_ordre";

        $this->db->query($sSQL) ;
        $ret['cnt'] = $this->db->num_rows();
        $i = 0;
        while ( $this->db->next_record() ) {
            $ret[$i]["menu_icone_img"]  = stripslashes($this->db->f('menu_icone_img'));
            $ret[$i]["menu_icone_title"] = stripslashes($this->db->f('menu_icone_title'));
            $ret[$i]["menu_url"]    = stripslashes($this->db->f('menu_url'));
            $ret[$i]["menu_action"] = stripslashes($this->db->f('menu_action'));
            $i++;
        }

The problem is when the "menu_icone_title" column has apostrophe inside , like Initialisation des niveaux d'activités

So in runtime the tooltip is broken : Initialisation des niveaux d .

So how to show all of the text ?

Upvotes: 0

Views: 1223

Answers (2)

Nick
Nick

Reputation: 6346

HTML should really be outside of any PHP. E.g.

<?php 
function cleantext ($string) {
  return htmlentities($string);
}

for ($i=0; $i<$ret['cnt']; $i++)
{
    ?>
    <td width="15">
       <a href="<?php echo HTTP_MAIN . cleantext($ret[$i]['menu_url']); ?>?action=<?php echo $ret[$i]['menu_action'];?>">
         <img src="<?php echo HTTP_ICONES . cleantext($ret[$i]["menu_icone_img"]); ?>" title="<?php echo cleantext($ret[$i]["menu_icone_title"]); ?>" width="12" height="12" />
       </a>
    </td>
  <?php
}
?>

It makes your code a lot more readable / easier to maintain.

I've also added a function around any output, which will clean the output for you. At the moment all this function is doing is doing htmlentites on the string, but you could easily extend it if/when required.

Upvotes: 0

Oussama Jilal
Oussama Jilal

Reputation: 7739

just replace :

$ret[$i]["menu_icone_title"]

By

str_replace("'","\\'",$ret[$i]["menu_icone_title"]);

Upvotes: 2

Related Questions