如何在PHP中通过用户输入使用getter和setter
我已经创建了一个注册表单,现在我想使用getter和setter插入数据。我创建了具有HTML结构和php函数的如何在PHP中通过用户输入使用getter和setter,php,mysql,getter-setter,Php,Mysql,Getter Setter,我已经创建了一个注册表单,现在我想使用getter和setter插入数据。我创建了具有HTML结构和php函数的intAll.php文件,然后创建了具有数据库连接、SQL查询和getter/setter的Encap.php文件。现在,我想将输入数据传递到Encap.php文件,我想在Encap.php文件中捕获它们,并插入到我的SQL数据库中,但我的代码不起作用 那么,如何解决这个问题呢 intAll.php文件 在PHP中使用OOPS将数据插入表中 名称 用户名 密码 Encap.
intAll.php
文件,然后创建了具有数据库连接、SQL查询和getter/setter的Encap.php
文件。现在,我想将输入数据传递到Encap.php
文件,我想在Encap.php
文件中捕获它们,并插入到我的SQL数据库中,但我的代码不起作用
那么,如何解决这个问题呢
intAll.php文件
在PHP中使用OOPS将数据插入表中
名称
用户名
密码
Encap.php文件
不能在字符串中调用函数。您应该中断字符串以执行此操作:
public function insertsingle()
{
$string = "INSERT INTO academic (name,username,pw) VALUES ('" . $this->getName() . "','" . $this->getUserName() . "','" . $this->getPassword() . "')";
$rsint=mysqli_query($this->con, $string);
return $rsint;
}
但是,由于您没有对任何地方的用户输入进行清理,因此此代码容易受到SQL注入攻击,因此您应该改用准备好的语句(注意:未测试的代码,可能需要稍微调整):
它插入了什么?getName()?什么不起作用?您是否收到错误消息(如果是,错误是什么)?乍一看,您的数据库类似乎没有insert()
方法。再看一眼编辑,您的insertsingle()
方法似乎应该使用一个准备好的语句。为什么要制作另一个数据库包装器?php中有一个MySQLi
类。使用它。这样做是毫无意义的。首先,确定数据库应该表示什么:数据库连接或特定表的网关(学术)。然后考虑不要在该类上使用吸收器和设置器,而是让插入单接受要插入的数据。当您意识到它实际上是一个表数据网关时,您还将意识到在它上面为单个行设置setter和getter并没有多大意义。所以去掉它们,只需将单个标量值传递给insertSingle即可。直接传给他们,输入这个,然后找到你的答案。啊,我又错过了关于我的观点comments@SaadSuri总是发生在我身上;-)@KistlakRajapaksha将$stmt->prepare
更改为是的,应该是bind_param
,让我更新我的答案,就像我说的,“未测试”;-)该警告意味着您需要先将三个函数调用放到一个变量中,例如$name=$this->getName()
然后在调用bind_param()
<?php
class Databases{
public $con;
private $id;
private $name;
private $username;
private $password;
function setId($id) {
$this->id = $id;
}
function getId() {
return $this->id;
}
function setName($name) {
$this->name = $name;
}
function getName() {
return $this->name;
}
function setUsername($username) {
$this->username = $username;
}
function getUsername() {
return $this->username;
}
function setPassword($password) {
$this->password = $password;
}
function getPassword() {
return $this->password;
}
public function __construct()
{
$this->con = mysqli_connect("localhost", "root", "", "portal");
if(!$this->con)
{
echo 'Database Connection Error ' . mysqli_connect_error($this->con);
}
}
public function insertsingle()
{
$string = "INSERT INTO academic (name,username,pw) VALUES ('getName()','getUserName()','getPassword()')";
$rsint=mysqli_query($this->con, $string);
return $rsint;
}
}
?>
public function insertsingle()
{
$string = "INSERT INTO academic (name,username,pw) VALUES ('" . $this->getName() . "','" . $this->getUserName() . "','" . $this->getPassword() . "')";
$rsint=mysqli_query($this->con, $string);
return $rsint;
}
public function insertsingle()
{
$string = "INSERT INTO academic (name,username,pw) VALUES (?, ?, ?)";
$stmt = mysqli_prepare($this->con, $string);
$stmt->bind_param("sss", $this->getName(), $this->getUserName(), $this->getPassword());
$rsint = $stmt->execute();
return $rsint;
}