如何确保mysql查询字符串php中没有缺失值
我有一个php类和方法,它在Mysql表中创建记录,如下所示如何确保mysql查询字符串php中没有缺失值,php,mysql,Php,Mysql,我有一个php类和方法,它在Mysql表中创建记录,如下所示 <?php class Site{ // database connection and table name private $conn; private $table_name = "sites"; // object properties public $id; public $name; public $location; public $saddress; public $duration; p
<?php
class Site{
// database connection and table name
private $conn;
private $table_name = "sites";
// object properties
public $id;
public $name;
public $location;
public $saddress;
public $duration;
public $created;
// create new site record
function create(){
// to get time stamp for 'created' field
$this->created=date('Y-m-d H:i:s');
// insert query
$query = "INSERT INTO " . $this->table_name . "
SET
site_name = :name,
site_location = :location,
site_address = :address,
site_duration = :duration,
created = :created";
// prepare the query
$stmt = $this->conn->prepare($query);
// sanitize
$this->name=htmlspecialchars(strip_tags($this->name));
$this->location=htmlspecialchars(strip_tags($this->location));
$this->saddress=htmlspecialchars(strip_tags($this->saddress));
$this->duration=htmlspecialchars(strip_tags($this->duration));
$this->created=htmlspecialchars(strip_tags($this->created));
// bind the values
$stmt->bindParam(':name', $this->name);
$stmt->bindParam(':location', $this->location);
$stmt->bindParam(':address', $this->saddress);
$stmt->bindParam(':duration', $this->duration);
$stmt->bindParam(':created', $this->created);
// execute the query, also check if query was successful
if($stmt->execute()){
return true;
}else{
$this->showError($stmt);
return false;
}
}
public function showError($stmt){
echo "<pre>";
print_r($stmt->errorInfo());
echo "</pre>";
}
}
?>
我很困惑,因为我的HTLM表单字段和数据库表列字段的名称写得正确,而且每当我从查询中删除site_address字段时,其他数据都会插入表中,所以应该有人来帮忙。
下面是类的实现
你在发帖吗
$_POST[站点地址]
应该是什么时候
“站点地址”列不能为空
请改为尝试$\u POST['site\u address']
站点地址=:地址
这不应该是saddress吗?您的数据库中有数据吗?$saddress应该是$this->saddress在数据库中存储时不应该使用htmlspecialchars和strip_标记。在网页上显示数据时应使用它们,以防止XSS。@user837288是的,我的数据库中有数据。只有未插入到表中的列site\u地址我从未看到$this->name或任何这些属性被分配。你从来没有告诉我们你是如何使用新网站的。我已经纠正了这一点,但没有工作到现在
Array
(
[0] => 23000
[1] => 1048
[2] => Column 'site_address' cannot be null
)
<?php
// get database connection
$database = new Database();
$db = $database->getConnection();
// pass connection to objects
$Construction = new Site($db);
// if the form was submitted -
if(isset($_POST['submit'])){
// set user property values
$Construction->name = $_POST['sitename'];
$Construction->location = $_POST['sitelocation'];
$Construction->saddress = $_POST["siteaddress"];
$Construction->duration = $_POST['siteduration'];
//Check if Construction Site already Exist
if($Construction->siteExists())
{
echo '<div class="alert alert-danger text-center">
<a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
<strong>Sorry!</strong> User Already Exist.
</div>';
}else{
$Construction->create();
}
}
?>