我想我的mysql查询是不同的取决于内容对于PHP变量(session),它必须是这样的:
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]'
我该怎么做?谢谢。
你正在尝试创建的代码有一些严重的(和不太严重的)问题,如果你想让你的网站有用,你需要马上修复。
首先,不要使用mysql_
功能,而是切换到mysqli或pdo。mysql
函数已弃用
您还将用户输入直接插入到查询中。这会导致一些严重的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
?>