开发者

What is the correct way to make a SELECT in PHP and MYSQL?

开发者 https://www.devze.com 2023-01-21 05:54 出处:网络
How can i do a select from a variable received from a form? I have the following code but i think that i cannot do this : \'%\'.$texto.\'%\'

How can i do a select from a variable received from a form?

I have the following code but i think that i cannot do this : '%'.$texto.'%'

$busqueda=$_POST['texto'];
$tipo=$_POST['tipo'];

if($tipo='titulo')
    $res=mysql_query("SELECT * FROM LI开发者_如何学GoBRO WHERE LI_TITULO like '%'.$texto.'%'",$conexion);

What should i do? Thank you for your time.


Always do mysql_real_escape_string() on variables or some kind of filtering:

if you expect integer parse the variable

$myId = (int)$POST['id'];

if you expect string with no HTML:

$myString = mysql_real_escape_string(strip_tags($POST['string']));

And so on. Never trust user's input!!!

The best option is to use a PHP framework because all frameworks have thought of potential weaknesses and provide reliable architecture and classes/functions for common tasks, e.g. Database, User login, etc.

Some frameworks you can have a look: CakePHP, CodeIgniter, Zend Framework, Symfony


  1. if($tipo == 'titulo'), or you'll always get true there
  2. mysql_real_escape_string on any user input that you put in your query strings
  3. comment your code
  4. indent you SQL, even if it's in a PHP string. like so:

    $res = mysql_query("
        SELECT * 
        FROM `libro` 
        WHERE `li_titulo` LIKE '%".mysql_real_escape_string($texto)."%'
    ", $conexion);
    
  5. uppercase only for keywords and maybe functions. MySQL is case insensitive.


mysql_query("SELECT * FROM LIBRO WHERE LI_TITULO like '%{$busqueda}%'",$conexion); 

Edit:

You also have bug in your if statement:

if($tipo='titulo') 

That's not a comparison, it's an assignment. If you want to compare, use

if($tipo==='titulo') 
0

精彩评论

暂无评论...
验证码 换一张
取 消