简体   繁体   中英

PHP GET request using varchar datatype as input

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 = 

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM