我有一个表单,用户将在其中为我正在构建的自定义应用程序定义他们的用户设置。这个项目把我介绍给了stmt,我不得不重新熟悉mysqli。
目前,我正在提交一份表格,其中只定义了几个"选项"。我在代码中的随机回声被打印到屏幕上(用于测试),但当我检查数据库时,只有一个选项被插入(GmailID)选项。
屏幕上的错误消息显示为:
警告:mysqli_stmt::bind_param():变量数与第56行/home/website/public_html/portal/includs/process-user-settings.php中准备好的语句中的参数数不匹配
然而,仔细查看我的代码,似乎我有合适数量的变量和参数。就像我说的,它对GmailID有效,但对GmailPW无效,并且不确定这个错误是否连接到了某个地方?我将包含我的代码文件以备不时之需。
error_reporting(-1);
ini_set('display_errors', 'On');
echo 'Houston we are a go<br />';
if (isset($_GET['GmailID'], $_GET['GmailPW'], $_GET['userID'])) {
include_once 'db_connect.php';
include_once 'psl-config.php';
$error_msg = "";
echo 'Info Set<br />';
$GmailID = filter_input(INPUT_POST, 'GmailID', FILTER_SANITIZE_EMAIL);
$GmailID = filter_var($GmailID, FILTER_VALIDATE_EMAIL);
$GmailPW = filter_input(INPUT_POST, 'GmailPW', FILTER_SANITIZE_STRING);
if (empty($error_msg)) {
echo 'No Errors<br />';
// Create a random salt
$random_salt = hash('sha512', uniqid(openssl_random_pseudo_bytes(16), TRUE));
echo $random_salt . '<br />';
// Create salted password
$GmailPW = hash('sha512', $GmailPW . $random_salt);
echo $GmailPW . '<br />';
$user_id = $_GET['userID'];
/* OPTIONS */
$options = array(
'GmailID' => $GmailID,
'GmailPW' => $GmailPW
);
foreach($options as $key => $value) {
echo 'Made it to the Foreach <br />';
// Insert the options into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO user_settings (user_id, meta_key, meta_value, salt) VALUES ('$user_id', '$key', '$value', ?)")) {
$insert_stmt->bind_param('ssss', $user_id, $key, $value, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../index.php?err=insert');
exit();
}
}
echo ' We are done';
header('Location: ../index.php?user=success');
exit();
}
}
}
您的查询使用占位符是完全错误的:
INSERT [...snip...] ('$user_id', '$key', '$value', ?)")) {
^---one single placeholder
您的查询中正好有ONE占位符,并且有3个直接插入的变量,这意味着您可以接受SQL注入攻击。
应该是
INSERT [...snip...] (?, ?, ?, ?)
以下是最终对我有效的方法,希望它能帮助其他人=)
$options = array(
'GmailID' => $GmailID,
'GmailPW' => $GmailPW,
'WebmailID' => $WebmailID,
'WebmailPW' => $WebmailPW,
'ProfileIMG' => $ProfileIMG
);
foreach($options as $key => $value) {
// Insert the options into the database
if ($insert_stmt = $mysqli->prepare("INSERT INTO user_settings (user_id, meta_key, meta_value, salt) VALUES (?, ?, ?, ?)")) {
$insert_stmt->bind_param('ssss', $user_id, $key, $value, $random_salt);
// Execute the prepared query.
if (! $insert_stmt->execute()) {
header('Location: ../index.php?err=insert');
exit();
}
}
//Success
header('Location: ../index.php?user=success');
exit();
}