PHP报Call to a member function exec() on string 新闻系统图片字段无法入库
报错直接原因
你把原本的PDO数据库连接对象$mysql给覆盖成了SQL字符串,这就是报错的核心诱因:
// 此处原本$mysql是PDO连接对象,你把它赋值成了普通SQL字符串 $mysql="INSERT INTO `news` (image_name, location) VALUES('$image', '$location')"; // 字符串没有exec()方法,同时你传入的$query变量根本没有定义 $mysql->exec($query);
其他核心问题
- 你写了两次INSERT操作,会生成两条完全独立的新闻记录:一条只有标题、内容、时间,另一条只有图片信息,完全不符合业务需求
- 直接拼接SQL语句存在SQL注入风险
- 上传的文件统一命名为
news.pdf,后续上传的文件会直接覆盖之前的文件 - 上传成功后你直接用JS跳转页面,后面插入标题、内容的代码根本不会执行
修复后完整代码
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>添加新闻</title> </head> <body> <?php if(isset($_POST["submit"])){ require("mysql.php"); // 处理文件上传 $file_name = $_FILES['image']['name']; $file_temp = $_FILES['image']['tmp_name']; $exp = explode(".", $file_name); $ext = end($exp); $ext_allowed = array("pdf"); // 文件名加时间戳避免重名覆盖 $image = "news_".time().'.'.$ext; $location = "uploads/".$image; // 先校验文件格式 if(!in_array($ext, $ext_allowed)) { echo "<script>alert('仅支持上传PDF格式文件!')</script>"; echo "<script>window.location='addnews.php'</script>"; exit; } // 移动上传文件 if(!move_uploaded_file($file_temp, $location)) { echo "<script>alert('文件上传失败,请检查uploads目录权限!')</script>"; echo "<script>window.location='addnews.php'</script>"; exit; } // 一次插入所有字段,无需分两次操作 $stmt = $mysql->prepare("INSERT INTO news (TITEL, NEWS, CREATED_AT, image_name, location) VALUES (:titel, :news, :now, :image_name, :location)"); // 绑定参数防止注入 $stmt->bindParam(":titel", $_POST["titel"], PDO::PARAM_STR); $stmt->bindParam(":news", $_POST["news"], PDO::PARAM_STR); $stmt->bindParam(":now", time(), PDO::PARAM_STR); $stmt->bindParam(":image_name", $image, PDO::PARAM_STR); $stmt->bindParam(":location", $location, PDO::PARAM_STR); // 执行插入 if($stmt->execute()) { echo "<script>alert('新闻添加成功!')</script>"; echo "<script>window.location='addnews.php'</script>"; } else { echo "新闻添加失败,请重试。"; } } ?> <form action="addnews.php" method="post" enctype="multipart/form-data"> <input type="text" name="titel" placeholder="新闻标题" required><br> <textarea name="news" cols="30" rows="10" placeholder="新闻内容"></textarea><br> <input type="file" name="image" required="required" /> <br> <br> <button type="submit" name="submit">添加新闻</button><br> </form> </body> </html>
额外注意事项
- 请提前在代码同级目录创建
uploads文件夹,并给足写入权限 - 如果需要支持上传图片,把允许的后缀数组修改为对应格式即可,例如
array("jpg","png","gif")
内容的提问来源于stack exchange,提问作者Force01
相关产品推荐
相关产品推荐

