使用面向对象的php进行服务器端验证;数据未插入数据库

问题描述 投票:0回答:2

我试图通过使用面向对象的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();

}

?>
php mysql forms
2个回答
1
投票

如果客户表中有超过2列,请在查询中添加列名。

$sql="insert into customer (column1,column2) values('".$this->name."','".$this->mobile."')";

示例查询。

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]')";

要么

为剩余字段添加null。假设你有3列。

  • ID
  • 那么
  • 移动 $ sql =“插入客户值(NULL,'”。$ this-> name。“','”。$ this-> mobile。“')”;

注意:字段与MySQL表字段的顺序和编号相同。


0
投票

如果customer表只有两列,那么您要插入的查询应该可以工作。没有保存的原因是因为customer类中的属性是私有的。让它们公开

更改

private $name;
private $mobile;

public $name;
public $mobile;

另外,您的插入查询仅受SQL注入攻击。使用预备陈述。有关更多信息,请查看manual

© www.soinside.com 2019 - 2024. All rights reserved.