写一个php添加的代码,数据库包含a.id,bookname,categoryName,salePrice,picture,publishingName from books AS a INNER JOIN books_category AS b ON a.categoryId=b.id,图片的值为'upload/'.$newFileName
时间: 2024-03-06 21:47:15 浏览: 146
好的,根据您的描述,我可以提供以下的PHP代码来添加一条数据到books表中:
```php
<?php
// 假设您已经连接到数据库
// 假设您已经获取了表单提交的数据
$bookname = $_POST['bookname'];
$categoryName = $_POST['categoryName'];
$salePrice = $_POST['salePrice'];
$picture = 'upload/'.$newFileName; // 假设$newFileName是您上传的图片文件名
$publishingName = $_POST['publishingName'];
// 准备SQL语句,使用INNER JOIN来关联books和books_category表
$sql = "INSERT INTO books (bookname, categoryId, salePrice, picture, publishingName)
SELECT :bookname, b.id, :salePrice, :picture, :publishingName
FROM books_category AS b
WHERE b.categoryName = :categoryName";
// 准备执行SQL语句的参数
$params = array(
':bookname' => $bookname,
':categoryName' => $categoryName,
':salePrice' => $salePrice,
':picture' => $picture,
':publishingName' => $publishingName,
);
// 执行SQL语句,并检查是否执行成功
$stmt = $pdo->prepare($sql);
if ($stmt->execute($params)) {
echo "Add book successfully.";
} else {
echo "Failed to add book.";
}
?>
```
上面的代码使用了PDO来执行SQL语句,使用了预处理语句来减少SQL注入的风险。同时,为了关联books和books_category表,使用了SELECT INTO语句。
阅读全文