我想让我的代码尽可能干净,这就是目前的样子:
$query = "INSERT INTO Users"
."(Avatar, Biography, Birth_Date, Email, Location, Password, Profile_Views, Real_Name, Reputation, Signup_Date, Username) VALUES "
."('default',"
." 'User since ".date("d-m-Y")."',"
." '0000-00-00',"
." '".$email."',"
." 'default',"
." '".hash("sha256", $password)."',"
." 0,"
." 'default',"
." 0,"
." '".date('Y-m-d H:i:s')."',"
." '".$this->username."'"
.");";
您可以看到它非常混乱,那么,将SQL代码放入PHP中的好方法是什么?
答案 0 :(得分:3)
HEREDOC和参数化查询。你做就像而不是是SQL注入的受害者,对吗?当然。
$query = <<<_E_
INSERT INTO Users
(Avatar, Biography, Birth_Date, Email, Location, Password, Profile_Views, Real_Name, Reputation, Signup_Date, Username)
VALUES ('default', :bio, '0000-00-00', :email, 'default', :pass, 0, 'default', 0, :singup, :uname);
_E_;
$params = array(
'bio' => 'User since'.date("d-m-Y"),
'email' => $email,
'pass' => hash("sha256", $password),
'singup' => date('Y-m-d H:i:s'),
'uname' => $this->username,
);
// you also like checking return values, right?
// of course.
if( ! $stmt = $dbh->prepare($query) ) { die($dbh->errorInfo()); }
if( ! $stmt->execute($params) ) { die($stmt->errorInfo()); }
或多或少假设PDO,但如果我没记错的话,MySQLi是相似的。
答案 1 :(得分:1)
您可以使用sprintf
并且它不那么混乱,但这是一个非常糟糕的解决方案,因为它不会增加任何安全性。
您应该使用prepared statements.
来自链接页面:
$mysqli = new mysqli("example.com", "user", "password", "database");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") ".
$mysqli->connect_error;
}
/* Prepared statement, stage 1: prepare */
if (!($stmt = $mysqli->prepare("INSERT INTO test(id) VALUES (?)"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
/* Prepared statement, stage 2: bind and execute */
$id = 1;
if (!$stmt->bind_param("i", $id)) {
echo "Binding parameters failed: (" . $stmt->errno . ") " . $stmt->error;
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
答案 2 :(得分:0)
PHP支持多行字符串
所以例如
$sql = "
SELECT
*
FROM
table
WHERE
column = value
AND
column2 = value2
";
通常是我写我的。至于变量替换,使用参数化查询,而不是在where子句中使用静态值,而是用以下任一项替换它:
PDO
WHERE
column = ':col1'
或Mysqli
WHERE
column = ?
所有时间都坚持多行字符串,缩进2个空格
以mysqli为例
$sql = "
SELECT
*
FROM
table
WHERE
column = ?
AND
column2 = ?
";