PHP MYSQL 执行且仅当 php session 变量存在时执行

标签 php mysql variables

我希望我的 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_ 函数,而是切换到 mysqlipdomysql 函数已被弃用。

您还将用户输入直接插入查询中。这会导致一些严重的 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/

相关文章:

PHP money_format(); £ 符号不是 GBP

mysql - 将 MMM-YY 字符串转换为可排序日期格式

tsql - 在TransactSQL中,是否可以创建一个采用可变数量的参数(可选参数)的函数?

php - 如何使用 PHP 获取正确格式的 JSON 数据

php - MySQL 在字段中存储

php - Ubuntu 14.04、Apache 2.4.7、Phpbrew 和 PHP7 仅将 PHP 文件呈现为纯文本

mysql - mysql 不同整数类型的含义是什么

mysql - 是否有 RCF2822 格式的日期时间数据类型?

c++ - #define 与 const 声明的优先级

c# - 在 C# 中,我试图显示上一个 WriteLine 方法中的文本字符串。出现编译器错误