我试图通过使用面向对象的 php 验证的表单将数据插入数据库。我没有收到任何错误,但数据未插入数据库。有人可以帮我找出问题所在吗?一个简单的解释将不胜感激,因为我是初学者。
这些是我的代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Customer Registration</h1>
<form action="oovalidation.php" method="post">
<label>Name</label>
<input type="text" name="name" id="nameField"/>
<br>
<label>Mobile</label>
<input type="text" name="mobile" id="mobileField"/>
<br>
<button type="submit" name="submit"> Add</button>
</form>
<script type="text/javascript">
function checkName(){
var text=document.getElementById("nameField").value;
if(text.length>=3){
alert("Name is ok");
return true;
}else{
alert("Wrong name");
return false;
}}
function checkMobile(){
var text=document.getElementById("mobileField").value;
if(text.length==10){
alert("Mobile is ok");
return true;
}else{
alert("Wrong mobile");
return false;
}}
function checkForm(){
var x=checkName();
var y=checkMobile();
return x&&y;
}
</script>
</body>
</html>
<?php
Class customer{
private $name;
private $mobile;
public function setName($name){
$namelen=strlen($name);
if($namelen>=3){
$this->name=$name;
return true;
}else{
echo "Wrong Name";
return false;
}
}
public function getName(){
return $this->name;
}
public function setMobile($mobile){
$mobilelen=strlen($mobile);
if($mobilelen==10){
$this->mobile=$mobile;
return true;
}else{
echo "Wrong Mobile";
return false;
}
}
public function getMobile(){
return $this->mobile;
}
public function save(){
$db=new DBManager();
$con=$db->getConnection();
$sql="insert into customer values('".$this->name."','".$this->mobile."')";
mysqli_query($con,$sql);
mysqli_close($con);
}
}
Class DBManager{
private $hostname='localhost';
private $dbuser='root';
private $dbpass='123';
private $dbname='sem3';
public function getConnection(){
return mysqli_connect($this->hostname,$this->dbuser,$this->dbpass,$this->dbname);
}
}
if(isset($_POST['submit'])){
$name=$_POST['name'];
$mobile=$_POST['mobile'];
$x=new customer();
$nameValidity=$x->setName($name);
$mobileValidity=$x->setMobile($mobile);
if($nameValidity && $mobileValidity)
$x->save();
}
?>
最佳答案
如果客户表中有超过2列, 在查询中添加列名称。
$sql="insert into customer (column1,column2) values('".$this->name."','".$this->mobile."')";
示例查询。
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')";
或
为剩余字段添加 null。假设您有 3 列。
- ID
- 姓名
移动设备
$sql="插入客户值(NULL,'".$this->name."','".$this->mobile."')";
注意:字段的顺序和数量与 MySQL 表字段相同。
关于php - 使用面向对象的 php 进行服务器端验证;数据未插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49022873/