好的,这就是问题所在.我试图在我的预定义查询中插入一个变量.但它不起作用.如果我只给它一个值,查询就有效,但当我在其中插入变量时,它会失败.救命?
$connection = new mysqli('localhost', 'user', 'pass', 'db');
$username = "test";
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($result = $connection->query("INSERT INTO users (username, password, email, firstName, lastName, createDate) VALUES ('".$username."', 'test', 'test', 'test', 'test', 'test')")){
echo "success";
$result->close();
}
else {
echo "error";
}
$connection->close();
?>
Run Code Online (Sandbox Code Playgroud)
如果我用任何值替换$ username,它都有效..我在这里遗漏了什么吗?
小智 6
您好,这适用于任何可能仍需要完成原始问题中提出的问题的人.
有人可能不想使用准备好的陈述的原因 - 来自:http: //www.php.net/manual/en/mysqli.quickstart.statements.php
"使用预准备语句并不总是执行语句的最有效方式.只执行一次的预准备语句会导致客户端 - 服务器往返次数超过未准备好的语句."
//you will want to clean variables properly before inserting into db
$username = "MyName";
$password = "hashedPasswordc5Uj$3s";
$q = "INSERT INTO `users`(`username`, `password`) VALUES ('".$username."', '".$password."')";
if (!$dbc->query($q)) {
echo "INSERT failed: (" . $dbc->errno . ") " . $dbc->error;
}
echo "Newest user id = ",$dbc->insert_id;
Run Code Online (Sandbox Code Playgroud)
干杯!