gpt4 book ai didi

php - PHP5中的简单插入

转载 作者:行者123 更新时间:2023-11-29 05:10:27 25 4
gpt4 key购买 nike

我正在尝试了解 oop php 最佳实践,但很难调试,我知道这可能是一个重复的问题,我希望不会得到很多反对票,所以让我们开始吧问题:

我在 Products.php 中有一个 Product

class Product {

public $id;
public $name;
public $price;
public $description;

function __construct($id, $name, $price, $description)
{
$this->$id = $id;
$this->$name = $name;
$this->$price = $price;
$this->$description = $description;

}
}

ProductsManager.php 中的 ProductManger

include('Products.php');
include('config.php');

class ProductManager {


function addProduct($conn,Products $p)
{

$query="INSERT INTO `products`( `name`, `description`, `price`) VALUES ('".$name."','".$price."','".$description."')";
$c->exec($query);

}
}

config.php 中的config

class config {

function connect() {

$serverName="localhost";
$dbName="phppoo";
$user="root";
$pass="";

return $conn = new PDO("mysql:host=$serverName;dbname=$dbName",$user,$pass);
}
}
//to be clear i think there are no issue related to connection

我提交表单的 Html 页面

 <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">

</head>

<body>
<form action="AddProduct.php" method="POST">
<table border="3">
<tr>
<td>Reference<td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Nom<td>
<td><input type="text" name="desc"></td>
</tr>

<tr>
<td>date de création <td>
<td><input type="number" name="price"></td>
</tr>


<tr>
<td> <td>
<td><input type="submit" name="ajouter" value="ajouter"></td>
</tr>


</form>
</table>


</body>
</html>

最后是 AddProduct.php 我在其中实例化产品经理并发送数据,以便我可以执行 query

include('ProductsManager.php');

$co = new config();
$c=$co->connect();


if(isset($_POST['name']) and isset($_POST['desc'])and isset($_POST['price']) ) {
$p=new ProductManager($_POST['name'],$_POST['desc'],$_POST['price']);
$p->addProduct($c,$p);
}

现在,如果我尝试从 html 页面提交 form,我将被重定向到一个空白页面 AddProduct.php,这是正常原因我没有返回值。

这里的问题是,我没有将提交的新值插入到我的数据库中。

感谢任何帮助,PS:如果您认为这不是最佳做法,请提及更好的方法或教程。谢谢

最佳答案

这样修改插入语句。因为您可以通过引用访问产品属性。<​​/p>

$query="INSERT INTO `products`( `name`, `description`, `price`) VALUES  
('".$p['name']."','".$p['description']."','".$p['price']."')";

关于php - PHP5中的简单插入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40167693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com