Search code examples
phpmysqlsqljoomlaampersand

Joomla 1.7 DB Query does not work when query has an ampersand


I am getting mental on this. I have tried everything so far, for hours. Here is the task:

In a module override, I use this code:

$db =& JFactory::getDBO();
$title = "Analysen & Auswertungen Infos";
$query = "SELECT introtext FROM #__content WHERE title=\"$title\"";
$db->setQuery($query);
$result = $db->loadRow();
echo $result;

This works, but since I am getting the $title dynamically from a variable I need this to work:

$db =& JFactory::getDBO();
$title = "$linktext Infos";
$query = "SELECT introtext FROM #__content WHERE title=\"$title\"";
$db->setQuery($query);
$result = $db->loadRow();
echo $result;

I have 6 variables that populate $linktext in a foreach loop, all work except the one with the string including the "&"...

I tried htmlentities and utf8_encode and different kind (actually all combinations) of " and ' in the query... nothing worked.

Whe I use the following sql query in phpmyadmin it works:

SELECT `introtext` FROM `x999x_content` WHERE `title`="Analysen & Auswertungen Infos"

I am really puzzled over this, and right now very tired and angry... Any help will be greatly appreciated!!!


Solution

  • Sometimes a good long sleep is the best you can do!

    I just used strlen to check the length of $linktext (which I get from DB via a foreach loop) and found that it is longer than the visible chars. This is logical because of the & which is returned as &.

    In order to use this $linktext inside a new DB query, all I needed to do was to decode the html entity:

    $db =& JFactory::getDBO();
    // this is the correct way of doing it
    $title = html_entity_decode($linktext)." Infos"; 
    $query = "SELECT introtext FROM #__content WHERE title=\"$title\"";
    $db->setQuery($query); 
    $result = $db->loadRow(); 
    

    or any other combi for the query (",',`,$query->select ) as pointed out in the other answers