I’m learning PDO and I want to insert data from form into database using class but it’s not working.
Here are the pages:
connect.php
class Connection {
public function __construct() {
$dsn = "mysql:host=localhost;dbname=nascms";
$user = "root";
$password = "";
try {
@$pdo = new PDO($dsn, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
}
}
$connection=new Connection;
insertPost.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert new post</title>
</head>
<body>
<form method="post" action="insertPost.php" enctype="multipart/form-data" >
<table align="center" border="1" width="500">
<tr>
<td align="center" colspan="6" bgcolor="yellow"><h1>Insert new post here</h1> </td>
</tr>
<tr>
<td align="right" >Post title</td>
<td><input type="text" name="title" size="50"></td>
</tr>
<tr>
<td align="right">Post author</td>
<td><input type="text" name="author" size="50"></td>
</tr>
<tr>
<td align="right">Post keywords</td>
<td><input type="text" name="keywords" size="50"></td>
</tr>
<tr>
<td align="right">Post image</td>
<td><input type="file" name="image" size="50"></td>
</tr>
<tr>
<td align="right">Post content</td>
<td><textarea name="content" cols="40" rows="20" ></textarea></td>
</tr>
<tr>
<td align="center" colspan="6">
<input type="submit" name="submit"value="Publish now">
</td>
</tr>
</table>
</form>
</body>
</html>
<?php
if(!empty($_POST['submit']))
{
require_once 'includes/Posts.php';
@$title = $_POST['title'];
@$date = date('d-m-y');
@$author = $_POST['author'];
@$keywords = $_POST['keywords'];
@$image = $_FILES['image']['name'];
@$image_tmp = $_FILES['image']['tmp_name'];
@$content = $_POST['content'];
if(Posts::insert(@$title, @$date, @$author, @$keywords, @$image, @$image_tmp, @$content)){
echo "Uspesan unos";
}
}
?>
Posts.php
<?php
require_once 'connect.php';
class Posts {
public function insert($title, $date, $author, $keywords, $image, $image_tmp, $content) {
global $connection;
if (empty($title) or empty($date) or empty($author) or empty($keywords) or empty($content)) {
echo "<script>alert('fill all the fields')</script>";
exit();
} else {
global $connection;
//move_uploaded_file($image_tmp, "../images/$image");
$sql = "INSERT INTO posts VALUES(:post_title,:post_date,:post_author,
:post_image,:post_keywords,:post_content)" or die();
$stmt = @$pdo->prepare($sql);
$stmt->bindParam(":post_title", $title, PDO::PARAM_STR);
$stmt->bindParam(":post_date", $date, PDO::PARAM_STR);
$stmt->bindParam(":post_author", $author, PDO::PARAM_STR);
$stmt->bindParam(":post_image", $image, PDO::PARAM_STR);
$stmt->bindParam(":post_keywords", $keywords, PDO::PARAM_STR);
$stmt->bindParam(":post_content", $content, PDO::PARAM_STR);
$stmt->execute();
}
}
}
?>