我想从2个文本框中获取值,并使用PHP将它们添加到mysql数据库。 我的HTML:
<form name='form' method='post'>
Username:<input type="text" id="username" name="username"/>
Password:<input type="text" id="password" name="password"/>
<input type="submit" name="submit" value="Add" style="width:50%;padding:10px;">
这就是PHP:
<?php
$username="";
$pwd="";
$pword="";
try{
global $username,$pwd;
if ( ! empty($_POST['username']) && ! empty($_POST['password'])){
$username = $_POST['username'];
$pwd = $_POST['password'];
}
$servername = "localhost";
$conusername = "root";
$conpassword = "";
$dbname = "annapoorna";
$dsn='mysql:dbname='.$dbname.';host='.$servername;
$conn = new PDO($dsn, $conusername, $conpassword);
$sql='INSERT INTO users(username, password) values (:username,:password)';
$sth=$conn->prepare($sql);
$sth->execute(array(':username'=>$username,':password'=>$pwd ));
}
catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
?>
但是值没有添加到数据库中。为什么?
答案 0 :(得分:0)
输入值由php trougth name
attr接收
HTML代码:
<form name='form' method='post'>
Username:<input type="text" id="username" name='username'/>
Password:<input type="text" id="password" name='password'/>
<input type="submit" name="submit" value="Add" style="width:50%;padding:10px;">
Global
不需要
PHP代码:
<?php
$username="";
$pwd="";
$pword="";
try{
if ( ! empty($_POST['username']) && ! empty($_POST['password'])){
$username = $_POST['username'];
$pwd = $_POST['password'];
}
$servername = "localhost";
$conusername = "root";
$conpassword = "";
$dbname = "annapoorna";
$dsn='mysql:dbname='.$dbname.';host='.$servername;
$conn = new PDO($dsn, $conusername, $conpassword);
$sql='INSERT INTO users(username, password) values (:username,:password)';
$sth=$conn->prepare($sql);
$sth->execute(array(':username'=>$user`enter code here`name,':password'=>$pwd ));
}catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
?>
答案 1 :(得分:0)
评论有点太长了,但它可能会帮助您解决问题:您应该设置PDO以在出现问题时抛出异常。现在你正试图捕捉它们,但可能没有任何东西被抛出。
您可以在构造函数中执行此操作:
$conn = new PDO(
$dsn,
$conusername,
$conpassword,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)
);
您还应启用错误处理并全部显示。您可以通过将其添加到脚本顶部来实现:
error_reporting(E_ALL);
ini_set('display_errors', '1');
请注意,我假设您已在表单中添加了缺少的name
属性,如评论中所述。
另请注意,您应该使用例如password_hash()
对密码进行哈希和加密,不要存储纯文本,加密或弱哈希密码。