我正在尝试设置一个newseltter,但在我的通讯类中我一直收到错误:致命错误:在非对象上调用成员函数setAttribute()
我一直在使用较旧的非pdo版本转换文件。
<?php
class NEWSLETTER{
private static $email;
private static $datetime = null;
private static $valid = true;
function __construct($conn){
$this->db = $conn;
}
public function signup($email){
if(!empty($_POST)){
self::$email = $_POST['email'];
self::$datetime = date('Y-m-d H:i:s');
if(empty(self::$email)){
$status = "Error";
$message = "No email entered.";
self::$vaild = false;
}else if(!filter_var(self::$email, FILTER_VALIDATE_EMAIL)){
$status = "Error";
$message = "Vaild email required.";
self::$valid = false;
}
if(self::$valid){
$this->db->setAttribute(PDO::ATTR_ERRMODE_EXCEPTION);
$exist = $this->prepare("SELECT COUNT (*) FROM newsletter WHERE email='$email'");
$exist->execute();
$data_exists = ($exist->fetchColumn() > 0) ? true : false;
if(!$data_exists){
$sql = "INSERT INTO newsletter (email, date) VALUES (:email, :datetime)";
$q = $pdo->prepare($sql);
$q->execute(array(':email'=>self::$email, ':datetime'=>self::$datetime));
if($q){
$status = "Success";
$message = "You have been subscribed to the Epic Owl newsletter.";
}else{
$status = "Error";
$message = "An error occurred, try again.";
}
}else{
$status = "Error";
$message = "You have already subscribed at an earlier date.";
}
}
$data = array('status' => $status, 'message' => $message);
echo json_encode($data);
}
}
}
?>
<?php
ini_set('display_errors', '1');
require_once './includes/conn.php';
if(!empty($_POST['email'])){
$email = $_POST['email'];
$newsletter->signup($email);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>EpicOwl UK | CMS Admin Panel Mail List</title>
<meta charset="utf-8">
<link rel="shortcut icon" href="../images/favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="../css/main.css">
</head>
<body>
<div id="header">
<a href="index.php"><img id="logo" src="../images/logo.png" /></a>
<div id="navigation">
<ul>
<a href="../index.php"><li>Home</li></a>
<a href="./index.php"><li>Admin Panel</li></a>
</ul>
</div>
</div>
<div id="content">
<form method="post">
<br /><h2>Signup to the Epic Owl Newsletter(NOT WORKING! STILL BEING DEVELOPED!)</h2>
<input type="text" name="email" placeholder="Your Email Address" /><br /><br />
<input type="submit" name="submit" value="Signup" /><br /><br /><br /><br />
</form>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="./includes/js/lib.js"></script>
</div>
<div id="footer">
<p class="copyright">© EpicOwl UK. All Rights Reserved.</p>
</div>
</body>
</html>
答案 0 :(得分:1)
$pdo
未在您班级的任何地方定义。
您应该在数据库连接上调用setAttribute()
和prepare()
,即$this->db->setAttribute()
提供的$this->db
实际上是与数据库的有效连接。