出于学习目的,我在本地系统上创建了一个密码管理器。但是,在将数据插入数据库时存在问题,而且我不确定它为什么不起作用。
我的整个文档可以在下面找到。
<?php
$user = 'root';
$pass = '';
$db = 'accounts';
$server = 'localhost';
$db_handle = mysql_connect($server, $user, $pass);
if (!$db_handle) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
$db_found = mysql_select_db($db, $db_handle);
if ($db_found) {
if (isset($_POST['type'])) {
$getOrSet = $_POST['type'];
$site = $_POST['site'];
$login = $_POST['login'];
if ($getOrSet == 'get') {
$pass = mysql_fetch_assoc(mysql_query("SELECT password FROM manager WHERE site = '$site' AND username = '$login'"))['password'];
} else if ($getOrSet == 'set') {
$url = $_POST['url'];
$pass = $_POST['pass'];
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login' '$pass')");
}
}
} else {
echo "Unable to select database: " . mysql_error();
}
mysql_close($db_handle);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#left,#right{width:50%;margin:0;padding:0;float:left;text-align:center}
form{width:300px;margin:0 auto}
label{width:300px;display:block;line-height:1.65em}
input{float:right}
#pass{width:300px}
#pass>span{float:right}
</style>
</head>
<body>
<h1>Password Manager</h1>
<div id="left">
<h2>Get Password</h2>
<form action="index.php" method="post">
<label>Site: <input type="text" name="site" /></label>
<label>Email/Username: <input type="text" name="login" /></label>
<input type="hidden" name="type" value="get" />
<?php if(isset($_POST['type'])){if ($getOrSet == 'get') {echo "<span id=\"pass\">Password: <span>$pass</span></span>";}} ?>
<input type="submit" value="Submit" />
</form>
</div>
<div id="right">
<h2>Set Password</h2>
<form action="index.php" method="post">
<label>Site: <input type="text" name="site" /></label>
<label>URL: <input type="text" name="url" /></label>
<label>Email/Username: <input type="text" name="login" /></label>
<label>Password: <input type="password" name="pass" /></label>
<input type="hidden" name="type" value="set" />
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
有人可以告诉我为什么这段代码不起作用?
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login' '$pass')");
答案 0 :(得分:3)
在插入之前使用转义符
$site = mysql_real_escape_string($site);
$url = mysql_real_escape_string($url);
$login = mysql_real_escape_string($login);
$pass = mysql_real_escape_string($pass);
// now insert
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login', '$pass')");
注意: mysql_*
已弃用。 use mysqli_*
或PDO
答案 1 :(得分:1)
问题是,
之后缺少'$login'
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login' '$pass')");
应该是
mysql_query("INSERT INTO manager (site, url, username, password) VALUES ('$site', '$url', '$login', '$pass')")