duanjing1276 2013-04-27 13:08
浏览 31
已采纳

PHP MYSQL仅当php会话变量存在时才这样做

i would like my mysql query to be different depending on the content of a php variable (session) it has to be something like:

if ($_SESSION['session_id'] != NULL) { 
   $var1 = "and id = '$_SESSION[session_id]'";
}
$result = mysql_query("
SELECT  field1, field2
FROM    table
WHERE   name = '$_GET[name]' $var1
") or die(mysql_error());

which will be: WHERE name = '$_GET[name]' and id = '$_SESSION[session_id]' or: WHERE name = '$_GET[name]'

how can i do this? Thanks.

  • 写回答

1条回答 默认 最新

  • doujing3896 2013-04-27 13:16
    关注

    The code you are trying to create has some serious (and less serious) problems that you need to fix right away if you ever want to make your site usefull.

    First of, dont use mysql_ function but switch to mysqli or pdo. mysql functions have been deprecated.

    Also you are inserting user input directly into your query. This causes some serious SQL injection problems. Always make sure to validate and escape user input.

    To create a query like you want I'd use:

    <?php
    $name = $_GET['name'];
    
    //validate $name according to your choice of mysql provider. EG: mysqli_real_escape_string
    //this is just basic validation. make sure you also add other types of validation. If a name is always alphanumeric, make sure you also check that it is before using it.
    
    /*
    if you dont validate and I would enter my name like: hugo' OR 1=1 --
    I would be able to access any record in your database. And that is just a harmless example.
    */
    
    $query = "SELECT field1, field2 FROM table WHERE name = '".$name."'"
    
    //for sake of simplicity I assume the id is numeric
    if (!empty($_SESSION['session_id']) AND is_numeric($_SESSION['session_id'])) { 
       $query .= " and id = '".$_SESSION['session_id']."'";
    }
    
    //exec query
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部