【发布时间】:2018-06-22 12:14:47
【问题描述】:
使用 PHP OOP 和 mysqli 在产品添加页面上工作,此时我正在处理准备好的语句实现,但找不到有关如何将它们添加到此类代码中的信息。
我们将不胜感激。
代码:
数据库连接类:
<?php
class DbConfig {
private $_host = 'localhost';
private $_username = 'root';
private $_password = 'falcons17';
private $_database = 'scandiweb';
protected $connection;
public function __construct()
{
if (!isset($this->connection)) {
$this->connection = new mysqli($this->_host, $this->_username, $this->_password, $this->_database);
if (!$this->connection) {
echo 'Cannot connect to database server';
exit;
}
}
return $this->connection;
}
}
?>
执行函数:
public function execute($query) {
$result = $this->connection->query($query);
if ($result == false) {
echo mysqli_error($this->connection); /*'Error: cannot execute the command'*/
return false;
} else {
return true;
}
}
验证和添加程序:
<?php
//including the database connection file
include_once("classes/Crud.php");
include_once("classes/Validation.php");
$crud = new Crud();
$validation = new Validation();
if(isset($_POST['Submit'])) {
$sku = $crud->prepare_string($_POST['sku']);
$name = $crud->prepare_string($_POST['name']);
$price = $crud->prepare_string($_POST['price']);
$products = $crud->prepare_string($_POST['products']);
$weight = $crud->prepare_string($_POST['weight']);
$capacity = $crud->prepare_string($_POST['capacity']);
$height = $crud->prepare_string($_POST['height']);
$width = $crud->prepare_string($_POST['width']);
$length = $crud->prepare_string($_POST['length']);
$check_int = $validation->is_int($_POST, array('price','weight','capacity','height','width','length'));
if ($check_int != null){
echo $check_int;
}else {
$result = $crud->execute("INSERT INTO products(sku,name,price,product_type,weight,capacity,height,width,length) VALUES('$sku','$name','$price','$products','$weight','$capacity','$height','$width','$length')");
//display success message
echo "<font color='green'>Data added successfully.";
echo "<br/><a href='index.php'>View Result</a>";
}
}
?>
【问题讨论】:
-
你看过documentation吗?哪些部分不清楚?
-
在 __construct 中的返回是无用的,并且 __construct 不应该用于在其受保护时获取外部连接
-
您的脚本对SQL Injection Attack 甚至if you are escaping inputs, its not safe! 都是开放的,在
MYSQLI_或PDOAPI 中使用prepared parameterized statements -
如果您准确描述您的问题/错误是什么会有所帮助
-
什么是
prepare_string?如果它正在转义数据,那么我强烈建议您停止这样做,而是使用准备好的/参数化的查询。如果你想要一个 db 类方法,你可能更喜欢使用 PDO 而不是 Mysqli,所以我建议试一试
标签: php oop mysqli prepared-statement