【发布时间】:2022-01-16 14:51:18
【问题描述】:
这是我的索引文件,
<?php
include 'db.php';
$form = read('form');
//echo '<pre>';
//print_r($forms);
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
<form action="store.php" method="post">
<label>
Username:
<input type="text" placeholder="username" name="username">
</label>
<label>
Password:
<input type="text" placeholder="password" name="password">
</label>
<label>
Email:
<input type="text" placeholder="email" name="email">
</label>
<button type="submit" name="submit">
submit
</button>
</form>
<table>
<?php foreach ($form as $user): ?>
<tr>
<?php foreach ($user as $item) {
echo '<td>' . $item . '</td>';
} ?>
</tr>
<?php endforeach; ?>
</table>
</body>
这是我读取数据库的数据库连接文件:
<?php
$servername = "localhost";
$username = "root";
$password = "mhimlaA#1";
try {
$conn = new PDO("mysql:host=$servername;dbname=mydb", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// echo "Connected successfully";
} catch (PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
function read($where = '')
{
global $conn;
$sql = "SELECT * FROM `form` $where LIMIT 1000;";
$stm = $conn->prepare($sql);
$stm->execute();
return $stm->fetchAll(PDO::FETCH_ASSOC);
}
我在这里遇到奇怪的问题,PhpStorm 在商店文件中的$conn 上显示错误。我正在使用此文件将输入文本插入数据库:
<?php
print_r($_POST);
unset($_POST['submit']);
include 'db.php';
$form = read('form');
$sql = "INSERT INTO mydb.form(username, password, email) VALUES (:username,:password,:email)";
$stm = $conn->prepare($sql);
$stm->execute($_POST) or die($conn->errorInfo());
header('location: index.php');
【问题讨论】:
-
您需要将 $conn 声明为全局才能使用它
-
你为什么有
or die($conn->errorInfo())? -
为什么
read()中有$conn->prepare($sql);? -
切勿以明文形式或使用 MD5/SHA1 存储密码! 仅存储使用 PHP 的
password_hash()创建的密码哈希,然后您可以使用password_verify()进行验证。看看这个帖子:How to use password_hash 并了解更多关于bcrypt & password hashing in PHP