tags:

views:

167

answers:

2

Hi.

Ive been programming a search form with three fields, and the one thatt is giving me troubles is the one that use "LIKE" clause in sql.

Here is the code:

            <form method="post" action="<?php $_SERVER['PHP_SELF']?>">
             <p>

             <label for="nome">Nome Empresa:</label>
             <input type="text" name="nome"  id="nome"/>

             <label for="concelho">Concelho:</label>
                <select name="concelho">
                        <option id="" selected="selected" value="">Seleccione o Concelho</option>
                          <option value="1" id="1">Um</option>
                          <option value="2" id="1">Dois</option> 
                 </select>

             <label for="actividade">Actividade:</label>
                <select name="actividade">
                        <option id="" selected="selected" value="">Seleccione a actividade</option>
                          <option value="1" id="1">Actividade Um</option>
                          <option value="2" id="1">Actividade Dois</option>    
                 </select>   
             </p>
             <p>
             <input type="submit" name="pesquisar" value="Pesquisar"/>
             </p>
            </form>

// the sql (not all)

        $nome = mysql_real_escape_string($_POST['nome']);



    // Pesquisa a partir da form
    if (isset($_POST['pesquisar'])) {

    $queryStr = 'SELECT * FROM ';
    if(!empty($nome)){
     $queryStr .= 'tbl_clientes  WHERE nome LIKE '%'$nome'%'';
    }

Why it gives me two times, this error?

Warning: Division by zero in .. on line ..

   Warning: Division by zero in .. on line ..

I'm not making a Division...am i??

Thanks in advance

+9  A: 

Yes, you do. The % signs used by LIKE are outside the string, and hence interpreted as the modulo operator. Remove the additional ' signs.

$queryStr .= "tbl_clientes WHERE nome LIKE '%$nome%'";

(Here I used a mixture of single and double quotes to sove the problem. Eoin Campbell's solution of escaping the inner single quotes is just as valid. You will often find that you will need to use (a combination of) these techniques when programming in PHP.)

Stephan202
Or use sprintf:$queryStr .= sprintf("tbl_clientes WHERE nome LIKE '%%s%'", $nome);
Daniel
and what about punctuation? Sometimes if i write in the input box something like "A.Helper" and in the database the name exists, why there are no results?
dutraveller
@Daniel: you'd need to write %% to get a literal %.
Stephan202
@dutraveller: LIKE doesn't treat punctuation differently. Without any additional information, it's hard to guess what goes wrong.
Stephan202
+2  A: 

Your error is with this piece of SQL

'tbl_clientes  WHERE nome LIKE '%'$nome'%''

You need to escape the extra apostrophes inside your string.

I assume the PHP syntax for this is the \ character

e.g.

'tbl_clientes  WHERE nome LIKE \'%'$nome'%\''
Eoin Campbell