PHP - Can't use the fetched data - javascript

Hello monsters of programming, Good day! What i want to do is, when the user click the file button and upload the image it will update, else if the user didn't change it just echo that image. But when the user didn't change the image, im having an error **Warning**: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\studentportal\edit2.php on line 27 Can someone help me? The if(isset($_FILES['image'])) is working properly but the else statement is not. How can i just echo that image if the user didn't change it? Im new to php and starting to learn it please give me ideas.
this is cause of the error the $newsimages = $row['news_image']; in the else statement.
else{
$title = $_POST['titles'];
$date = $_POST['dates'];
$content = $_POST['contents'];
$newsimages = $row['news_image'];
$sql ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content', news_image ='$newsimages' WHERE news_id = '$newsid'";
mysqli_query($con, $sql);
echo "oh it worked again ";
}
this is all of the php code
<?php
include_once('connection.php');
$newsid = $_GET['news_id'];
if(isset($_POST['esubmit'])){
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "SELECT * FROM news WHERE news_id = ? LIMIT 1")) {
/* bind parameters */
mysqli_stmt_bind_param($stmt, "s", $newsid);
/* execute query */
mysqli_stmt_execute($stmt);
/* get the result set */
$result = mysqli_stmt_get_result($stmt);
/* fetch row from the result set */
$row = mysqli_fetch_array($result);
}
}
if(isset($_POST['update'])){
if(isset($_FILES['image'])){
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"img/" . $_FILES["image"]["name"]);
$newsimage="img/" . $_FILES["image"]["name"];
$title = $_POST['titles'];
$date = $_POST['dates'];
$content = $_POST['contents'];
$sql ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content', news_image ='$newsimage' WHERE news_id = '$newsid'";
mysqli_query($con, $sql);
echo "oh it worked ";
}
else{
$title = $_POST['titles'];
$date = $_POST['dates'];
$content = $_POST['contents'];
$newsimages = $row['news_image'];
$sql ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content', news_image ='$newsimages' WHERE news_id = '$newsid'";
mysqli_query($con, $sql);
echo "oh it worked again ";
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['esubmit'])){
?>
<form method="post" action ="edit2.php?news_id=<?php echo $row['news_id']; ?>" enctype="multipart/form-data">
Title<input type ="text" name ="titles" value="<?php echo $row['news_title']; ?>"/><br>
Date<input type ="text" name="dates" value="<?php echo $row['news_date']; ?>" /><br>
Content<textarea name="contents"><?php echo $row['news_content']; ?></textarea>
<input class="form-control" id="image" name="image" type="file" accept="image/*" onchange='AlertFilesize();'/>
<img id="blah" src="<?php echo $row['news_image']; ?>" alt="your image" style="width:200px; height:140px;"/>
<input type="submit" name="update" value="Update" />
</form>
<?php
}
?>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#image").change(function(){
readURL(this);
});
</script>
</body>
</html>

What you can do is remove <img></img> out of the first form and put it in separate <form> with separate submit button and add more php code to just update image only.You will have two forms and two updates like
$sql1 ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content' WHERE news_id = '$newsid'";
$sql2="update new SET new_image='$newsimages' WHERE new_id='$newsid'";
I Hope You undestand.I have done same thing for one of my websites.I think this is the best solution.Try it.For further query you can comment.

Related

Prepared statement to make pictures show up on php page, when JOINING tables

I currently have a loginsystem where a user is able to register and login as a user.
My system is based on PHP PDO.
When the user is logged in they should be able to upload a picture which is linked to their account.
Right now i have a fully functional loginsystem so thats great, and the user is currently able to upload a picture to the database, but he cant yet see it on the site.
Right now my problem is to make the pictures show up on the site.
I want the user to be able to see his OWN pictures that he uploaded, and not anybody elses pictures.
This is what i have so far! :)
This my Database!
TABLE PICTURES with the following rows:
descPicture
id
imageFullNamePicture
titlePicture
userid
TABLE USERS with the following rows:
user_email
user_id
user_name
user_password
user_phone
user_zip
This is my CODE so far:
DBH.INC.PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "chhoe17";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname",
$username,
$password,
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(PDOException $e) {
echo $e->getMessage();
}
UPLOAD.INC.PHP
<?php
include "../upload.php";
//Find the ID of the USER
// session_start();
include_once 'dbh.inc.php';
$pictureTitle = ($_POST["filetitle"]);
$pictureText = ($_POST["filedesc"]);
//Fnd ID from the user
//$user = $_SESSION["u_id"];
$user = $_SESSION['u_id'];
$queryUserID = 'SELECT user_id from '.'users'. ' where user_name="'. $user.'";';
$stmt = $conn -> prepare($queryUserID);
$stmt -> execute();
$result = $stmt -> fetch(PDO::FETCH_ASSOC);
//FileDic
$fileDirectory = "../uploads/";
$fileHandled = $fileDirectory . basename($_FILES["file"]["name"]);
//The "tmp_name" is the temporary location the file is stored in the browser, while it waits to get uploaded
if (move_uploaded_file($_FILES["file"]["tmp_name"], $fileHandled)) {
//echo "The file " . basename($_FILES["file"]["name"]) . " has been uploaded.";
$picture = 'INSERT INTO pictures (titlePicture, descPicture, userid, imageFullNamePicture)
VALUES (:titlePicture, :descPicture, :userid, :imageFullNamePicture);';
$stmt = $conn->prepare($picture);
$stmt -> bindParam(":titlePicture", $pictureTitle);
$stmt -> bindParam(":descPicture", $pictureText);
$stmt -> bindParam(":userid", $user);
//$stmt -> bindParam(":userid", $result['user_id']);
$stmt -> bindParam(":imageFullNamePicture", $fileHandled);
$stmt -> execute();
header("Location: ../upload.php?`Success");
?>
<?php } else {
header("Location: ../upload.php?Error");
//echo "Sorry, there was an error uploading your file.";
}
header("Location: ../upload.php");
UPLOAD.PHP
<body>
<section class="main-container">
<div class="main-wrapper">
<h2>Manage your pictures</h2>
<?php
//display a message and images if logged in!
if (isset($_SESSION['u_id'])) {
echo "Upload your pictures";
echo '<div class="picture-upload">
<h2>Upload</h2>
<br>
<br>
<br>
<form action="includes/upload.inc.php" id="upload" method="POST" enctype="multipart/form-data">
<input type="text" name="filetitle" placeholder="Image title">
<input type="text" name="filedesc" placeholder="Image description">
<input type="file" id="file" name="file">
<button type="submit" name="submit">Upload</button>
</form>
</div>';
}
if (isset($_SESSION['users'])) {
echo ' <section class="picture-links">
<div class="wrapper">
<h2>Pictures</h2> ';
$user_data = 'SELECT * FROM' . ' users ' . 'INNER JOIN pictures on users.user_id
= pictures.userid WHERE name="' . $_SESSION['u_id'] . '";';
$stmt = $conn->prepare($user_data);
$stmt->execute();
while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
<div class="pictures">
<a target="file" href= <?php ?>>
<img class="pic" src= <?php echo $data['imageFullNamePicture']; ?>></a>
<div class="titlePicture"><?php echo $data['titlePicture']; ?> <br> </div>
<div class="descPicture" >Your description:</div>
<div class="text"><?php echo $data['titleDesc']; ?> <br> ?> </div>
</div>
<?php
}
};
?>
</div>
</section>
</body>
</html>
<?php
include_once 'footer.php';
?>
So yea the problem is that i cant get the pictures that connects to the currently logged in user to show up on the page upload.php
I hope that somebody can help me! :)
EDIT!!!:
So i currently have this piece of code. IT should make the user see the pictures that he uploaded to the database, but it is very buggy. And it only shows one picture per user. Can somebody help make this work.
if (isset($_SESSION['u_id'])) {
echo ' <section class="picture-links">
<div class="wrapper">
<h2>Pictures</h2> ';
?>
<div id="pictures">
<?php
$sql = "SELECT * FROM pictures WHERE userid = '{$_SESSION['u_id']}'";
//$sql = "SELECT * FROM pictures ORDER BY userid DESC LIMIT 20;";
$stmt = $conn->prepare($sql);
$stmt->execute();
$pictures = $stmt->fetchAll();
// if ($pictures !== null) {
foreach ($pictures as $pic)
?>
<figure id="<?php echo $pic['id']; ?>">
<b><figcaption><?php echo $pic["titlePicture"] ?>
<img src = <?php echo $pic["imageFullNamePicture"] ?>>
<?php echo $pic["descPicture"] ?> <br>
</figure>
<?php
// }
}
?>
</div>
Your fetching the data as numerically indexed arrays PDO::FETCH_NUM, yet your using the keys in your code:
UPLOAD.INC.PHP
//instead of PDO::FETCH_NUM
while ($data = $stmt->fetch(PDO::FETCH_ASSOC)) { ?>
...
<?php echo $data['imageFullNamePicture']; ?>
...
<?php }
Use PDO::FETCH_ASSOC instead.
Please don't do this with PDO:
$user_data = 'SELECT * FROM' . ' users ' . 'INNER JOIN pictures on users.user_id
= pictures.userid WHERE name="' . $_SESSION['u_id'] . '";';
$stmt = $conn->prepare($user_data);
$stmt->execute();
If someone manages to get data in here name="' . $_SESSION['u_id'] . '" you've just defeated the whole purpose of preparing your SQL. It shouldn't matter where that data came from, you never know when a simple coding mistake or something will allow user data into a session variable.
$user_data = 'SELECT * FROM users INNER JOIN pictures on users.user_id
= pictures.userid WHERE name=:u_id';
$stmt = $conn->prepare($user_data);
$stmt->execute(['u_id'=>$_SESSION['u_id']]);
It's that easy to prepare it properly. You don't really need to even use bind whatever with PDO, unless you wan't to restrict the Type. But I think it's also the only way to do LIMIT :limit. Anyway I almost never use them. In general both PHP and MySQL are smart enough to do the proper type casting.
PS. don't forget to call session_start() if your using $_SESSION or none of that will work. I didn't see it in the code that was posted, so I have to mention it.

How to keep appending data from database as you retrieve, on a webpage?

Whenever I enter an id number in text box and click scan button, i get data from database and it is displayed below the text box in a predefined format. Now when i enter another id and hit scan, the new data thus retreived replaces the older one. I want it to be displayed below the already existing data on the page.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title> ShopNGo </title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header id="header">
<div class="container">
<form name="products" method="POST">
<br><br>
<button type="submit" name="scan" id="scan"> <h1> SCAN! </h1> </button>
<br><br><br>
<input type="text" name="id">
</form>
</div>
</header>
<div class="main">
<table border="0">
<?php
if (isset($_POST["scan"])) {
$servername = "localhost";
$username = "#";
$password = "#";
$dbname = "#";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection Failed:" . mysqli_connect_error());
$query = "SELECT name, price, img FROM product WHERE id = $_POST[id]";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
echo "<tr> <table border='0'> <tr>";
echo "<img src='$row[img]'>";
echo "<br>";
echo $row["name"];
echo "<br>";
echo $row["price"];
echo "</tr> </table> </tr>";
}
}
mysqli_close($conn); }
?>
</table>
</div>
</body>
</html>
please help me !!
also it would be a great help if u can suggest some improvements in the existing code other than what i asked for... Thank you so much !!
use ajax to post your id to another php script that checks id for data, put the html into a string variable and then echo it at the end. You can use the ajax success callback to append the data
$.ajax({
type: "POST",
url: url,
data: id,
success: function(data){
$('#targetDiv').append(data);
}
});
php script:
$query = "SELECT name, price, img FROM product WHERE id = $_POST[id]";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row =
mysqli_fetch_assoc($result))
{
$element = "<tr> <table border='0'> <tr>";
$element .= "<img src='$row[img]'>";
$element .= "<br>";
$element .=$row["name"];
$element .= "<br>";
$element .= $row["price"];
$element .= "</tr> </table> </tr>";
}
}
echo $element;

Get data MySQL DB and display on in HTML

How would I code into my program using PHP/JavaScript and HTML/CSS to display data from a database I made in MySQL Monitor on the blue section below:
I made buttons that use PHP to go into the database and show the data on the HTML page:
HTML:
<form action="fullridez.php" method="post">
<h4 id="Filter">GPA</h4>
<input id="FilterBox" name="gpa" type="text"/>
<h4 id="Filter">Amount</h4>
<input id="FilterBox" name="amount" type="text"/>
<h4 id="Filter">School</h4>
<input id="FilterBox" name="school" type="text"/>
<input type="submit" id="FilterBox" name="myForm" onkeypress="checkEnter()" ><img src="search.png" width=15 height=15 /></button>
</form>
<script>
</script>
PHP:
<?php
if(isset($_POST['myForm'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarshiplist";
$conn = mysqli_connect($servername, $username, $password, $database);
$gpa = $_POST['gpa'];
$amount = $_POST['amount'];
$count = "SELECT * FROM scholarships";
$result = mysqli_query($conn, $count);
if ($result->num_rows > 0) {
$sql = "SELECT * FROM scholarships WHERE GPA <= " . $gpa . " AND Amount <= "
. $amount;
if ($result = mysqli_query($conn, $sql)) {
while ($row=mysqli_fetch_row($result)) {
for($i = 0; $i < count($row); $i++) {
echo $row[$i] . '<br>';
}
}
}
} else {
echo "0 results";
}
$conn->close();
}
SQL:
USE ScholarshipList;
CREATE TABLE Scholarships
(
id int unsigned NOT NULL auto_increment,
School varchar(500) NOT NULL,
GPA decimal(10,2) NOT NULL,
Amount decimal(10,2) NOT NULL,
PRIMARY KEY (id)
);
I am using XAMPP
When I click the button on the HTML file it bring me to the PHP page and all I see is the PHP code. I don't want it to go to the page but stay on the same page showing the data below the buttons.
This is what the page looks like so far
page
What am I doing wrong?
If your HTML form is contained within the 'fullridez.php' file and you are posting the form inputs to that same file, then you need to have some PHP where you'd like to output to be checking for results and then looping through those results while echoing them out:
<table>
<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td></tr>
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<tr><td>"
. $row['col_1'] . "</td><td>"
. $row['col_2'] . "</td><td>"
. $row['col_3'] . "</td></tr>";
}
?>
</table>
You can build a wireframe div table with for loop:
<?php
$num_rows = mysql_num_rows($result);
for ($i=0;$i<$num_rows;$i++) {
//loop through all rows of data
$row = mysql_fetch_assoc($result); // your data is now: $row['fieldName']
?>
<div>
GPA <input name="" value="<?php echo($row['gpa'])?>;" type="text">
AMOUNT <input name="" value="<?php echo($row['amount'])?>;" type="text">
SCHOOL <input name="" value="<?php echo($row['school'])?>;" type="text">
</div>
<?php
} //end of the loop
?>

PHP - Edit elements is gone after updating

Goodmorning. My problem is after clicking the update button the edit elements are gone like the title, date, content and the image only the echo output is shown "successfully updated". What i want to do is after clicking the update button the elements will stay there and it will echo there.
Here is my edit2.php
after i click the update button only the output "Successfully update" is shown the edit elements is gone
here is the php code for edit2.php
<?php
include_once('connection.php');
$newsid = $_GET['news_id'];
if(isset($_POST['esubmit'])){
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "SELECT * FROM news WHERE news_id = ? LIMIT 1")) {
/* bind parameters */
mysqli_stmt_bind_param($stmt, "s", $newsid);
/* execute query */
mysqli_stmt_execute($stmt);
/* get the result set */
$result = mysqli_stmt_get_result($stmt);
/* fetch row from the result set */
$row = mysqli_fetch_array($result);
}
}
if(isset($_POST['update'])){
if($_FILES['image']['error'] == 0) {
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"img/" . $_FILES["image"]["name"]);
$newsimage="img/" . $_FILES["image"]["name"];
$title = $_POST['titles'];
$date = $_POST['dates'];
$content = $_POST['contents'];
$sql ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content', news_image ='$newsimage' WHERE news_id = '$newsid'";
mysqli_query($con, $sql);
echo "successfully updated";
}
else{
$title = $_POST['titles'];
$date = $_POST['dates'];
$content = $_POST['contents'];
$sql ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content' WHERE news_id = '$newsid'";
mysqli_query($con, $sql);
echo "successfully updated";
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['esubmit'])){
?>
<form method="post" enctype="multipart/form-data" action ="edit2.php?news_id=<?php echo $row['news_id']; ?>" >
Title<input type ="text" name ="titles" value="<?php echo $row['news_title']; ?>"/><br>
Date<input type ="text" name="dates" value="<?php echo $row['news_date']; ?>" /><br>
Content<textarea name="contents"><?php echo $row['news_content']; ?></textarea>
<input class="form-control" id="image" name="image" type="file" accept="image/*" onchange='AlertFilesize();'/>
<img id="blah" src="<?php echo $row['news_image']; ?>" alt="your image" style="width:200px; height:140px;"/>
<input type="submit" name="update" value="Update" />
</form>
<?php
}
?>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#image").change(function(){
readURL(this);
});
</script>
</body>
</html>
The problem is because of this if block,
if(isset($_POST['esubmit'])){ ...
When you submit the form, $_POST['esubmit'] will be not get set and hence, the form won't get displayed again. So your if block should be like this:
if(isset($_POST['esubmit']) || isset($_POST['update'])){ ...
Overall, you need to change your first and third if blocks in the following way,
if(isset($_POST['esubmit'])){
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "SELECT * FROM news WHERE news_id = ? LIMIT 1")) {
/* bind parameters */
mysqli_stmt_bind_param($stmt, "s", $newsid);
/* execute query */
mysqli_stmt_execute($stmt);
/* get the result set */
$result = mysqli_stmt_get_result($stmt);
/* fetch row from the result set */
$row = mysqli_fetch_array($result);
/* get all values */
$title = $row['news_title'];
$date = $row['news_date'];;
$content = $row['news_content'];
$newsimage = $row['news_image'];
}
}
And
if(isset($_POST['esubmit']) || isset($_POST['update'])){
?>
<form method="post" enctype="multipart/form-data" action ="edit2.php?news_id=<?php echo $newsid; ?>" >
Title<input type ="text" name ="titles" value="<?php if(isset($title)){ echo $title; } ?>"/><br>
Date<input type ="text" name="dates" value="<?php if(isset($date)){ echo $date; } ?>" /><br>
Content<textarea name="contents"><?php if(isset($content)){ echo $content; } ?></textarea>
<input class="form-control" id="image" name="image" type="file" accept="image/*" onchange='AlertFilesize();'/>
<img id="blah" src="<?php if(isset($newsimage)){ echo $newsimage; } ?>" alt="your image" style="width:200px; height:140px;"/>
<input type="submit" name="update" value="Update" />
</form>
<?php
}
From the extended discussion,
Since you're making image upload optional, you need to fetch image details in the else block where you process the form in case user doesn't upload an image, like this:
if(isset($_POST['update'])){
if($_FILES['image']['error'] == 0) {
// your code
}else{
// your code
/* get the image details*/
if ($stmt = mysqli_prepare($con, "SELECT news_image FROM news WHERE news_id = ? LIMIT 1")) {
mysqli_stmt_bind_param($stmt, "s", $newsid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result);
$newsimage = $row['news_image'];
}
}
}

Adding image to comment box

Thanks for your time guys.
I have the following code working for my commenting system though I can't really be sure about the security for now. But I need your help guys in :
Allowing anyone that comment to add their image to their comment whether registered users or Visitors
Building the inside comment or reply box. This is what I got.
Comment for comment counter
Here is the PHP code for the comment:
<?php
// Connect to the database
include('config.php');
$id_post = "1"; //the post or the page id
?>
<div class="cmt-container" >
<?php
$sql = mysql_query("SELECT * FROM comments WHERE id_post = '$id_post'") or die(mysql_error());;
while($affcom = mysql_fetch_assoc($sql)){
$name = $affcom['name'];
$email = $affcom['email'];
$comment = $affcom['comment'];
$date = $affcom['date'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<div class="cmt-cnt">
<img src="<?php echo $file_path; ?>" height="250" />
<div class="thecom">
<h5><?php echo $name; ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input type="text" id="name-com" name="name-com" value="" placeholder="Your name" />
<input type="text" id="mail-com" name="mail-com" value="" placeholder="Your e-mail adress" />
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var theName = $('#name-com');
var theMail = $('#mail-com');
if( !theCom.val()){
alert('You need to write a comment!');
}else{
$.ajax({
type: "POST",
url: "ajax/add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&name='+theName.val()+'&email='+theMail.val()+'&comment='+theCom.val(),
success: function(html){
theCom.val('');
theMail.val('');
theName.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>
And the Ajax Script :
<?php
extract($_POST);
if($_POST['act'] == 'add-com'):
$name = htmlentities($name);
$email = htmlentities($email);
$comment = htmlentities($comment);
// Connect to the database
include('../config.php');
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . $default . "&s=" . $size;
if(strlen($name) <= '1'){ $name = 'Guest';}
//insert the comment in the database
mysql_query("INSERT INTO comments (name, email, comment, id_post)VALUES( '$name', '$email', '$comment', '$id_post')");
if(!mysql_errno()){
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" alt="" />
<div class="thecom">
<h5><?php echo $name; ?></h5><span class="com-dt"><?php echo date('d-m-Y H:i'); ?></span>
<br/>
<p><?php echo $comment; ?></p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<?php endif; ?>

Categories