duanji5116
duanji5116
2018-02-05 12:08
浏览 35
已采纳

too long

Sorry if the wording in the title is not correct (new to PHP). I'm trying to return results from a mysql db using below php scripts.

php script

<?php

require "conn.php";

$adopt_id = $_GET["adopt_id"];

  $query = "
select *
from temp_table
where adopt_id = $adopt_id
";

....
?>

Now if I run the above in my browser as url below, it returns as expected http://localhost/searchfeed.php?adopt_id=1

Dump of above query:

select *
from temp_table
where adopt_id = 1

Same php script but filtering on a diff field which is of varchar data type.

php script

    <?php

    require "conn.php";

    $GENDER = $_GET["gender"];

      $query = "
    select *
    from temp_table
    where gender = $GENDER
    ";

    ....
    ?>

Now if I run the above in my browser as url below, it returns null because its not getting any results = http://localhost/searchfeed.php?gender=M

I dumped the above query to a log file, seems like it doesn't do anything with the $GENDER. This is what the query looks like

select *
from temp_table
where gender = 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dongzang5815
    dongzang5815 2018-02-05 12:20
    已采纳

    I don't see any problem with your PHP code in your second statement, but as suggested by others, your MySQL query consists of incorrect statement.

    Please, update your MySQL statement to look either like:

    select *
    from temp_table
    where gender = '$GENDER'
    

    or

    select *
    from temp_table
    where gender like '$GENDER'
    

    Also consider using any MySQL library, as such usually consists of various security patches (as noted in the previous answer - the SQL injections)

    or at least use mysqli_real_escape_string() function

    Edit: Problem solved most probably by incorrect variable name spelling. GET variables are all stored in $_GET array.

    your value of gender can be accessed by this statement: $gender = $_GET['gender'];

    note: for others - be careful to spell variable like $_GET not $GET

    点赞 评论
  • dongshi1606
    dongshi1606 2018-02-05 12:13

    This is because you need to put non-numeric values within single quotes.

    select *
    from temp_table
    where gender = '$GENDER'
    

    Please also have a look at Prevent SQL Injections

    点赞 评论
  • duanchen7703
    duanchen7703 2018-02-05 12:33

    The correct should be this way.

    <?php
    
    require "conn.php";
    
    $GENDER = $_GET["gender"];
    
      $query = "
    select *
    from temp_table
    where gender = '".$GENDER."'";
    
    ....
    ?>
    

    This way our query will work even ig the $GENDER value is a string. In the previous answeres the mysql will return an error.

    点赞 评论

相关推荐