gpt4 book ai didi

php - 通过 GET 输入法检查 SQL 条目

转载 作者:行者123 更新时间:2023-11-30 00:24:46 25 4
gpt4 key购买 nike

由于某种原因,我无法让我的代码按照我想要的方式工作。

$Check = $_POST['phrase'];

try{ $db=new readPDO('testDB'); $sql=('

SELECT entry, ID
FROM test
WHERE entry = "$Check "

');

$statement=$db->prepare($sql);
$statement->execute();

如果我尝试这个:

$Check = $_POST['phrase'];

try{ $db=new readPDO('testDB'); $sql=('

SELECT entry, ID
FROM test
WHERE ID= "$Check "

');

$statement=$db->prepare($sql);
$statement->execute();

GET 是一个可以正常工作的数字,但它不适用于字符串。

最佳答案

Strings 下所述:

A string literal can be specified in four different ways:

Single quoted

The simplest way to specify a string is to enclose it in single quotes (the character ').

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

<?
// [ deletia ]

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

 双引号

如果string用双引号 (") 括起来,PHP 将解释更多特殊字符的转义序列:

[ deletia ]

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

In your case, $sql is assigned the value of a single-quoted string literal in which the $Check variable will not be expanded (whilst it is itself enclosed by double-quotes therein, so far as the PHP parser is concerned it is still a single-quoted string literal).

Using a double-quoted string literal would provide variable expansion. If you still wish to quote $Check within the string literal using double-quotes, then they would have to be escaped (with backslashes):

$sql = "
SELECT entry, ID
FROM test
WHERE entry = \"$Check \"
";

或者,现在可以使用单引号引用 $Check (从 MySQL recognises both forms of string quoting 开始,前提是 ANSI_QUOTES 被禁用):

$sql = "
SELECT entry, ID
FROM test
WHERE entry = '$Check '
";

请注意,引号内的尾随空格将被 MySQL 解析为字符串的一部分,这可能不是您的意图。

另请注意,此代码容易受到 SQL 注入(inject)攻击(如果 $Check 碰巧包含某些字符,也会出现错误)。您应该阅读@deceze的博客文章The Great Escapism (Or: What You Need To Know To Work With Text Within Text)更好地理解这一点;然后How can I prevent SQL injection in PHP?了解如何修复它。

关于php - 通过 GET 输入法检查 SQL 条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22973984/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com