PHP-MySQL,Can';我不知道如何创建这个程序
我必须为学校制定这个计划,我不知道该怎么办。我问老师,下一步该去哪里,结果一无所获。(基本上得到了“谷歌it”的回应) 任务如下: 创建一个名为“User”的PHP类,其中包含以下私有字段: 名字, yyyy/mm/dd格式的出生日期, 年龄,及 部门 在类中,包含getter和setter方法以获取和设置这些变量的值 使用HTML文本输入框和提交按钮编写数据输入Web表单。当用户单击submit按钮时,将实例化一个“user”类,并填充新用户对象的字段。HTML输入框对应于“User”类中的字段。 添加一个“插入”按钮,允许用户将表单数据插入MySQL表。 添加一个“显示”按钮当最终用户单击该按钮时,会在web表单上显示MySQL表的内容 这就是我迄今为止所做的: PHP:PHP-MySQL,Can';我不知道如何创建这个程序,php,mysqli,Php,Mysqli,我必须为学校制定这个计划,我不知道该怎么办。我问老师,下一步该去哪里,结果一无所获。(基本上得到了“谷歌it”的回应) 任务如下: 创建一个名为“User”的PHP类,其中包含以下私有字段: 名字, yyyy/mm/dd格式的出生日期, 年龄,及 部门 在类中,包含getter和setter方法以获取和设置这些变量的值 使用HTML文本输入框和提交按钮编写数据输入Web表单。当用户单击submit按钮时,将实例化一个“user”类,并填充新用户对象的字段。HTML输入框对应于“User”类中的字
在编写准备好的语句时,似乎将过程样式与面向对象样式混合在一起
正如达曼所说,你不应该引用?占位符(因此在所有占位符中应为?而不是“?”)
另一方面,您已经声明了一个类并向代码中添加了一个setter,但它们不是必需的。(因此可以删除)
对于连接语句(localhost/username/password/db),您可以将其移动到另一个include文件(例如connection.php),然后在php脚本中包含一次
因此,请尝试将PHP更改为以下内容:
connection.php
<?php
$conn = new mysqli("localhost", "xxxxxusername", "xxxxpassword", "junkdb");
/// other system initstatements
?>
您的PHP
<?PHP
include_once 'connection.php';
$query = "INSERT into junkdb (username, birthday, age, department) VALUES(?,?,?,?)";
$stmt = $conn -> prepare($query);
$stmt->bind_param('ssss', $_POST['Name'], $_POST['Birth'], $_POST['Age'], $_POST['Depart']);
if ($stmt->execute()) {
echo "Record added";
} else {
echo "Not added";
}
$stmt->close();
$conn->close();
?>
我在这里突出显示了您应该更正它
$query = "INSERT into junkdb (username, birthday, age, department) VALUES(?,?,?,?)";
$stmt = $conn->prepare($query);
if($stmt->affected_rows){
echo "<p>Record added.</p>";
} else {
echo "<p>Not added...</p>";
}
$stmt->close();
$conn->close();
$query=“插入junkdb(用户名、生日、年龄、部门)值(?、、?、?)”;
$stmt=$conn->prepare($query);
如果($stmt->受影响的行){
echo“添加了记录。”;
}否则{
回显“未添加…”;
}
$stmt->close();
$conn->close();
或者,您可以复制完整的代码并运行:
<?PHP
if ($_POST) {
//create a connection
$conn = mysqli_connect('localhost', 'xxxxxx_hidden', 'xxxxxxxxxx_hidden');
if (! $conn) {
die("Connection failed" . mysqli_connect_error());
}
else {
mysqli_select_db($conn, 'junkdb');
}
class USER {
private $userName;
private $userBirthday;
private $userAge;
private $userDepart;
function setter($userName,$userBirth,$userAge,$userDepart) {
$this->$_POST['Name'] = $userName;
$this->$_POST['Birth'] = $userBirth;
$this->$_POST['Age'] = $userAge;
$this->$_POST['Depart'] = $userDepart;
}
}
$query = "INSERT into junkdb (username, birthday, age, department) VALUES(?,?,?,?)";
$stmt = $conn->prepare($query);
$stmt->bind_param('ssss', $_POST['Name'], $_POST['Birth'], $_POST['Age'], $_POST['Depart']);
if($stmt->execute()){
echo "<p>Record added.</p>";
} else {
echo "<p>Not added...</p>";
}
$stmt->close();
$conn->close();
}
?>
首先要做的是整理您编写的类。这并不坏,但你错过了正确的行话,然后它是一个有点混乱。我想我会补充一些建议,让你保持跑步
Setter和getter函数是可以用来操作对象私有字段的函数,而无需利用它们。例如,它们用于对要存储在类实例中的值进行健全性检查
通常它们被称为get和set。您可以使用automagic函数来创建它们,但是,对我来说,您节省了一些输入,但必须与ide的自动完成进行斗争,而且一个方法太通用了
您需要将类的代码与从db加载/存储值或从web检索用户输入的代码分开。每一段代码只需要做一件事(并且要做到最好)
contactform.html
文件是:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8">
<h1>{{ contentTitle }}</h1>
{{ content }}
</div>
</div>
</div>
</body>
</html>
<form name="contact-form" action="insert.php" method="POST" id="contact-form">
<input name="uid" value="{{ uid }}" type="hidden">
<div class="form-group">
<label for="Name">Name</label>
<input name="Name" value="{{ userName }}" type="text" class="form-control" name="Name" placeholder="Name" required>
</div>
<div class="form-group">
<label for="Birthday">Birthday</label>
<input name="Birth" value="{{ userBday }}" type="text" class="form-control" placeholder="YYYY/MM/DD" required>
</div>
<div class="form-group">
<label for="Age">Age</label>
<input name="Age" value="{{ userAge }}˝ type="text" class="form-control" name="Age" placeholder="Your Age" required>
</div>
<div class="form-group">
<label for="Depart">Department</label>
<input name="Depart" value="{{ userDep }}" type="text" class="form-control" placeholder="Your Department" required>
</div>
<button type="submit" class="btn btn-primary" name="submit" value="Submit" id="submit_form">Submit</button>
</form>
我们需要一个BaseView对象来组装完整的html页面:
class HtmlPage {
private $template;
function __construct() {
/* We need to load a template somehow. */
$this->template = file_get_contents(`/path/to/template/base.html`);
}
function render($content) {
/* When we do not pass any user, just show the form, otherwise
* we will fill it with the data of the user we have
* to show/edit
*/
// get a copy of the template, maybe we will need to show another
// user in the next future, who know.
$htmlform = $this->template;
// change all the placeholder
foreach ($fields as $field => $value) {
$htmlform = str_replace($field, $value, $htmlform);
}
return $htmlform;
}
}
现在您的用户类已与html解耦,您可以更改视图,而无需更改保存宝贵数据的类
我们只需要一个工厂就可以从web用户的输入中创建用户。或者从数据库,或者从其他来源
这是一项全新的任务,因此我们需要一个全新的对象。
此类的任务是创建用户
Class UserFactory {
private $dbc;
function setDbConnector($pdo) {
/* just injecting an object to manage the interaction with a db */
$this->dbc = $pdo;
}
function createFromHash($data) {
/* Sometime you will need to use different verbs to
* send data to the server, hance the need to
* decouple the array we take the data from.
*
* Important, we should take the time here to
* check the input for malicious input.
* Since it is an example and I'm too lazy we will
* skip this important phase of input retrieving.
*/
$requiredFields = ['uid', 'Name', 'Birth', 'Age', 'Depart'];
$actual = array_intersect($requiredFields, array_keys($data));
if (count($requiredFields) != count($actual)) {
throw new \InvalidArgumentException("Some field is missing");
}
$user = new User();
$user->setId($data['uid']);
$user->setName($data['Name']);
$user->setBirthdate($data['Birth']);
$user->setAge($data['Age']);
$user->setDepart($data['Depart']);
return $user;
}
function createFromDb($userId) {
/* If you need to retrieve data from a database,
* just retrieve them, put in a suited array hash an
* reuse the method we already implemented.
*
* It
*/
$query = "SELECT id as "uid",
username as "Name",
birthday as "Birth",
age as "Age",
department as "Depart"
FROM users
WHERE id = :userid";
$stmt = $this->dbc->prepare($query);
$stmt->bindParam(':userid', $userId, PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
return $this->createFromHash($data);
}
}
如何进入数据库?
我认为您使用的函数实际上是保留的,可能已被弃用,
只要坚持使用数据库就可以了。
PDO用于连接不同的数据库引擎,确保可以使用公共接口连接到数据库并执行
现在是时候把所有的东西放在一起了
#Include all the php files you need
// instance $pdo, a PDO object to connect to the database
try{
$factory = new UserFactory();
$user = $factory->createFromHash($_POST);
} catch (InvalidArgumentException $e) {
$user = new User(); // an empty one
}
$page = new HtmlPage();
$contactForm = new UserViewContactForm();
echo $page->render($contactForm->render($user));
您应该准备好一个呈现页面来获取数据。
有一些捷径,还有很多工作要做才能得到一个真正有效的解决方案,但我认为这是一个你可以建立的基础。通常你想把你的类放在一个单独的页面上,必要时要求或包括(可能一次)。您的连接也应位于单独的安全文件夹中。。。而您只需在不安全的页面中包含或要求。您通常不需要自己设置$\u POST
属性,只需实例属性,如$this->userName=$\u POST['propertyHere']代码>。只有注释。键入“?”
。占位符不应该被引用。哦,谢谢你(对不起,我只是从OP复制而来,没有注意到),我已经更正了它们。如果你的答案真的包含一些解释,那就太好了。OP有非常混乱的代码,他们有很多问题。您的代码可能会工作,但我不确定它是否能很好地解释您所做的更改。同意。我添加了更多解释。如果尚未执行查询,受影响的行应包含什么内容?$this->$\u POST['Name']=$userName代码>-你能解释一下那行应该做什么吗?@NicoHaase让我们假设你有一个变量$aname=“Hello”
。在PHP中,如果您有一个名为$Hello
的类,那么习惯用法$this->$aname
相当于$this->Hello
。在我看来,你永远不应该使用这样的习惯用法,因为它让人困惑,而且你所使用的ide无法追踪它,因此,请列举最明显的反对理由。这是在原来的问题中,用错了方法(因为有一种正确的方法使用它;-))对不起,我在原来的问题中没有看到。这听起来相当混乱,因为如果字段名来自POST请求,您无法安全地再次读取该属性。。。。。
class UserViewContactForm {
private $template;
function __construct() {
/* We need to load a template somehow. */
$this->template = file_get_contents(`/path/to/template/contactform.html`);
}
function render(?User $user=Null) {
/* When we do not pass any user, just show the form, otherwise
* we will fill it with the data of the user we have
* to show/edit
*/
if (!$user) {
$user = new User();
}
$fields = [
"{{ uid }} => $user->getId(),
"{{ userName }}" => $user->getName(),
"{{ userBday }}" => $user->getBirthday(),
"{{ userAge }}" => $user->getAge(),
"{{ userDep }}" => $user->getDepartment()
];
// get a copy of the template, maybe we'll need it for another one
$htmlform = $this->template;
// change all the placeholder
foreach ($fields as $field => $value) {
$htmlform = str_replace($field, $value, $htmlform);
}
return $htmlform;
}
}
class HtmlPage {
private $template;
function __construct() {
/* We need to load a template somehow. */
$this->template = file_get_contents(`/path/to/template/base.html`);
}
function render($content) {
/* When we do not pass any user, just show the form, otherwise
* we will fill it with the data of the user we have
* to show/edit
*/
// get a copy of the template, maybe we will need to show another
// user in the next future, who know.
$htmlform = $this->template;
// change all the placeholder
foreach ($fields as $field => $value) {
$htmlform = str_replace($field, $value, $htmlform);
}
return $htmlform;
}
}
Class UserFactory {
private $dbc;
function setDbConnector($pdo) {
/* just injecting an object to manage the interaction with a db */
$this->dbc = $pdo;
}
function createFromHash($data) {
/* Sometime you will need to use different verbs to
* send data to the server, hance the need to
* decouple the array we take the data from.
*
* Important, we should take the time here to
* check the input for malicious input.
* Since it is an example and I'm too lazy we will
* skip this important phase of input retrieving.
*/
$requiredFields = ['uid', 'Name', 'Birth', 'Age', 'Depart'];
$actual = array_intersect($requiredFields, array_keys($data));
if (count($requiredFields) != count($actual)) {
throw new \InvalidArgumentException("Some field is missing");
}
$user = new User();
$user->setId($data['uid']);
$user->setName($data['Name']);
$user->setBirthdate($data['Birth']);
$user->setAge($data['Age']);
$user->setDepart($data['Depart']);
return $user;
}
function createFromDb($userId) {
/* If you need to retrieve data from a database,
* just retrieve them, put in a suited array hash an
* reuse the method we already implemented.
*
* It
*/
$query = "SELECT id as "uid",
username as "Name",
birthday as "Birth",
age as "Age",
department as "Depart"
FROM users
WHERE id = :userid";
$stmt = $this->dbc->prepare($query);
$stmt->bindParam(':userid', $userId, PDO::FETCH_ASSOC);
$stmt->execute();
$data = $stmt->fetch(PDO::FETCH_ASSOC);
return $this->createFromHash($data);
}
}
#Include all the php files you need
// instance $pdo, a PDO object to connect to the database
try{
$factory = new UserFactory();
$user = $factory->createFromHash($_POST);
} catch (InvalidArgumentException $e) {
$user = new User(); // an empty one
}
$page = new HtmlPage();
$contactForm = new UserViewContactForm();
echo $page->render($contactForm->render($user));