Search code examples
phpmysqlsqlsql-like

How can i use variable in Mysql Query


I have this query :

 $result = mysql_query("select * FROM  `agents_infos` 
 WHERE ( agent_name LIKE  '%$name%' )");

the $name is :

 $name =$_POST['name'];

I want to get in the result, all the element that contains the name , but I get nothing. Can you help me please?


Solution

  • in order to receive a list of all element that contains the name, you can write:

    $name = $_POST['name'];  
    $result = mysql_query("SELECT * FROM  `agents_infos` WHERE ( agent_name LIKE  '%".$name."%' )");
    

    to avoid code injection i advice to use

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

    instead of

    $name = $_POST['name'];