我希望我的 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 注入(inject)问题。始终确保验证并转义用户输入。
要创建一个像你想要的查询,我会使用:
<?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
?>
关于PHP MYSQL 执行且仅当 php session 变量存在时执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16256881/