gpt4 book ai didi

PHP + MySQL : creating queries

转载 作者:太空宇宙 更新时间:2023-11-03 10:21:50 25 4
gpt4 key购买 nike

假设,您需要将值 $a, $b, $c 插入到数据库行的表中,这些值可能是不安全的,表名存储在执行操作的类中作为常量。可以这样查询

$query = "INSERT INTO `" . self::TABLE . '` ' .
"(a, b, c) VALUES (" .
. intval(a) .
",'" . mysql_real_escape_string(b) . "'" .
",'" . mysql_real_escape_string(b) . "')";

问题来了:是否有更优雅的方式来创建查询?

最佳答案

它叫做prepared statements,它存在于MySQLi(好)或PDO(更好)中。我将在评论中为使用 mysql_* 的人添加常见的内容:

Please stop writing new code with the ancient mysql_* functions. They are no longer maintained and community has begun the deprecation process. Instead you should learn about prepared statements and use either PDO or MySQLi. If you care to learn, here is a quite good PDO-related tutorial.

虽然可以在 mysql_* 函数中执行,但我高度(真的EPICLY)建议不要


在 PDO 中,您的代码将如下所示:

$query = "INSERT INTO `" . self::TABLE . "` (a, b, c) VALUES (:a, :b, :c);";

$statement = $db_connection->prepare($query);

$statement->bindParam(":a", $a);
$statement->bindParam(":b", $b);
$statement->bindParam(":c", $c);

$statement->execute();

关于PHP + MySQL : creating queries,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10563725/

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