0

我希望我的 mysql 查询根据 php 变量(会话)的内容而有所不同,它必须类似于:

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());

这将是:WHERE name = '$_GET[name]' and id = '$_SESSION[session_id]' 或:WHERE name = '$_GET[name]'

我怎样才能做到这一点?谢谢。

4

1 回答 1

1

您尝试创建的代码有一些严重(和不太严重)的问题,如果您想让您的网站有用,您需要立即修复这些问题。

首先,不要使用mysql_函数,而是切换到mysqlipdomysql功能已被弃用。

此外,您正在将用户输入直接插入到您的查询中。这会导致一些严重的 SQL 注入问题。始终确保验证和转义用户输入。

要创建您想要的查询,我会使用:

<?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
?>
于 2013-04-27T21:16:02.863 回答