Hello everyone I'm completely new to mysqli and PDO. I tried to convert my msqli code to PDO but I keep getting errors. Can someone please help me? the error is like when i click on post, nothing happens and I searched everywhere how to convert from msqli to pdo and I converted some of them but it still doesn't work
<?php
$databaseHost = 'localhost';
$databaseName = 'test';
$databaseUsername = 'test';
$databasePassword = 'pass';
try {
$dbConn = new PDO("mysql:host={$databaseHost};dbname={$databaseName}", $databaseUsername, $databasePassword);
$dbConn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo $e->getMessage();
}
if (isset($_POST['save'])) {
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql = "INSERT INTO comments (name, comment) VALUES ('{$name}', '{$comment}')";
if ($result = $dbConn->query($sql)) {
$id = $link->insert_id;
$saved_comment = '<div class="comment_box">
<span class="delete" data-id="' . $id . '" >delete</span>
<span class="edit" data-id="' . $id . '">edit</span>
<div class="display_name">'. $name .'</div>
<div class="comment_text">'. $comment .'</div>
</div>';
echo $saved_comment;
}else {
echo "Error: ".($dbConn);
}
exit();
}
// delete comment fromd database
if (isset($_GET['delete'])) {
$id = $_GET['id'];
$sql = "DELETE FROM comments WHERE id=" . $id;
($dbConn->prepare($sql));
exit();
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$comment = $_POST['comment'];
$sql = "UPDATE comments SET name='{$name}', comment='{$comment}' WHERE id=".$id;
if ($dbConn->prepare($sql)) {
$id =($dbConn);
$saved_comment = '<div class="comment_box">
<span class="delete" data-id="' . $id . '" >delete</span>
<span class="edit" data-id="' . $id . '">edit</span>
<div class="display_name">'. $name .'</div>
<div class="comment_text">'. $comment .'</div>
</div>';
echo $saved_comment;
}else {
echo "Error: ". ($dbConn);
}
exit();
}
// Retrieve comments from database
$sql = "SELECT * FROM comments";
$result = $dbConn->prepare($sql);
$comments = '<div id="display_area">';
while($row = $result->fetch(PDO::FETCH_ASSOC)) {
$comments .= '<div class="comment_box">
<span class="delete" data-id="' . $row['id'] . '" >delete</span>
<span class="edit" data-id="' . $row['id'] . '">edit</span>
<div class="display_name">'. $row['name'] .'</div>
<div class="comment_text">'. $row['comment'] .'</div>
</div>';
}
$comments .= '</div>';
?>
You used ->prepare(), but did not use ->execute().
Documentation:
http://php.net/manual/en/pdostatement.execute.php
Related
I'm making a quiz. I displayed Q/A from db and the correct answer. How to see the answer of the specific question on clicking the Check Answer button.
<?php
if (isset($_GET['pageno'])){
$pageno = $_GET['pageno'];
} else {
$pageno = 1;
}
$no_of_records_per_page = 1;
$offset = ($pageno - 1) * $no_of_records_per_page;
$conn = mysqli_connect("localhost", "root", "", "quizdb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
die();
}
$total_pages_sql = "SELECT COUNT(*) FROM entry1";
$result = mysqli_query($conn, $total_pages_sql);
$total_rows = mysqli_fetch_array($result)[0];
$total_pages = ceil($total_rows / $no_of_records_per_page);
$sql = "SELECT * FROM entry1 LIMIT $offset, $no_of_records_per_page";
$res_data = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($res_data)) {
include('server1.php');
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'quizdb';
$con = mysqli_connect($host, $user, $pass, $db);
$qno = $row["qno"];
$question = $row["question"];
$optiona = $row["optiona"];
$optionb = $row["optionb"];
$optionc = $row["optionc"];
$optiond = $row["optiond"];
$ans = $row["ans"];
echo '<br>Q ' . $qno . '. ';
echo '' . $question . '<br>';
echo '<input type="radio" name="options" value="optiona"></button>' . $optiona . '<br>';
echo '<input type="radio" name="options" value="optionb"></button>' . $optionb . '<br>';
echo '<input type="radio" name="options" value="optionc"></button>' . $optionc . '<br>';
echo '<input type="radio" name="options" value="optiond"></button>' . $optiond . '<br>';
echo '<form action="practice.php" method="post">
<input type="submit" name="submitans" value="Check Answer"></form>';
if (isset($_POST['submitans'])) {
echo '' . $ans . '<br>';
}
}
mysqli_close($conn);
?>
<ul class="pagination">
<li>First</li>
<li class="<?php if ($pageno <= 1) {
echo 'disabled';
} ?>">
<a href="<?php if ($pageno <= 1) {
echo '#';
} else {
echo "?pageno=" . ($pageno - 1);
} ?>">Prev</a></li>
<li class="<?php if ($pageno >= $total_pages) {
echo 'disabled';
} ?>">
<a href="<?php if ($pageno >= $total_pages) {
echo '#';
}
else {
echo "?pageno=" . ($pageno + 1);
} ?>">Next</a>
</li>
<li>Last</li>
</ul>
</body>
</html>
Expected Result - When I click next and I see another question, I click on Check Answer, then I see the answer of that question.
Actual Result - When I click next and I see another question, I click on Check Answer, then I go back to the first page and its answer is shown
I had set a search button in my website. It works fine if there's a result but if there's none, it doesn't show the "no results.....".
What's wrong with my code?
<html !DOCTYPE HTML>
<body>
<?php
$title = "DenTEETH";
include('header.html');
//connect to database
$db = mysqli_connect("127.0.0.1", "root", "", "authentication");
if(isset($_GET['q']) && $_GET['q'] !== '')
{
$searchq = $_GET['q'];
$sql = "SELECT * FROM search WHERE keyword LIKE '%$searchq%' OR title LIKE '%$searchq%'";
$output='';
$results = mysqli_query($db, $sql);
if (count($results) == 0){
$output .= 'No search results for <b>"' . $searchq . '"</b>';
}
else{
while ($row = mysqli_fetch_array($results)){
$id = $row['search_id'];
$title = $row['title'];
$desc = $row['description'];
$link = $row['link'];
$img = '<img src="images/thumbnail/'.$row['search_id'].'.jpg" class="thumbnail">';
$output .= '<div class="search_thumb">
<p class="search_cap">' . $img . '<h3>' . $title . '</h3>' . $desc .
'<div class="clear"></div></p></div>';
}
}
}
else{
header("location: ./");
}
print($output);
?>
<div class="row">
</div>
<?php
include('footer.html');
?>
</body>
</html>
Use mysqli_num_rows() try this
<html !DOCTYPE HTML>
<body>
<?php
$title = "DenTEETH";
include('header.html');
//connect to database
$db = mysqli_connect("127.0.0.1", "root", "", "authentication");
if(isset($_GET['q']) && $_GET['q'] !== '')
{
$searchq = $_GET['q'];
$sql = "SELECT * FROM search WHERE keyword LIKE '%$searchq%' OR title LIKE '%$searchq%'";
$output='';
$results = mysqli_query($db, $sql);
if (mysqli_num_rows($results ) == 0){
$output .= 'No search results for <b>"' . $searchq . '"</b>';
}
else{
while ($row = mysqli_fetch_array($results)){
$id = $row['search_id'];
$title = $row['title'];
$desc = $row['description'];
$link = $row['link'];
$img = '<img src="images/thumbnail/'.$row['search_id'].'.jpg" class="thumbnail">';
$output .= '<div class="search_thumb">
<p class="search_cap">' . $img . '<h3>' . $title . '</h3>' . $desc .
'<div class="clear"></div></p></div>';
}
}
}
else{
header("location: ./");
}
print($output);
?>
<div class="row">
</div>
<?php
include('footer.html');
?>
</body>
</html>
im struggling with php while loop. The goal is to get the quote from the database and display it with 3 columns on each row. As it look now the while loop is displaying one column each row. How should i correct this problem?
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$row = $ip['id'];
$row = $ip['quote'];
$row = $ip['topic'];
$row = $ip['author'];
$nr = 0;
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc() ) {
$nr++;
echo
"<div class='container row'>
<div class='col s12 m6 l4 z-depth-1'>
<div class='card-panel grey darken-4 white-text center'><h5>Citat: ". $row["id"] ."</h5></div> <pre class='flow-text black-text' wrap='soft'>" ."<p class=''>Författare: ". $row["author"] ."</p>"
. "<p class=''>Citat: ". $row["quote"] ."</p>" . $row["topic"] ."</pre>
<div class='content_wrapper'>
<h4>Vote </h4>
<div class='voting_wrapper' id='". $row["id"] ."'>
<div class='voting_btn'>
<div class='up_button'> </div><span class='up_votes'>0</span>
</div>
<div class='voting_btn'>
<div class='down_button'> </div><span class='down_votes'>0</span>
</div>
<br>
</div>
</div>
</div>
</div>";
}
}else {
echo "0 results";
}
$conn->close();
?>
You could do something like this:
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//DO YOU NEED THESE VARIABLES? I DON'T SEE THEIR USE HERE... BESIDES, $row DOES NOT EXIST YET...
$row = $ip['id'];
$row = $ip['quote'];
$row = $ip['topic'];
$row = $ip['author'];
$nr = 0;
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$output = "";
while($row = $result->fetch_assoc() ) {
$topic = trim($row["topic"]);
$quote = trim($row["quote"]);
$author = trim($row["author"]);
$id = trim($row["id"]);
$output .= injectNColumnWrapper(3, $nr, "container row", $nr);
$output .="<div class='col s12 m6 l4 z-depth-1'>";
$output .="<div class='card-panel grey darken-4 white-text center'>";
$output .=" <h5>Citat: {$id}</h5>";
$output .="</div>";
$output .="pre class='flow-text black-text' wrap='soft'>";
$output .="<p class='flow-text-p author'>Författare: {$author}</p>";
$output .="<p class='flow-text-p citat'>Citat: {$quote}</p>";
$output .="<p class='flow-text-p topic'>{$topic}</p>";
$output .="</pre>";
$output .="<div class='content_wrapper'>";
$output .="<h4>Vote </h4>";
$output .="<div class='voting_wrapper' id='vote-{$id}'>";
$output .="<div class='voting_btn'>";
$output .="<div class='up_button'> </div>";
$output .="<span class='up_votes'>0</span>";
$output .="</div>";
$output .="<div class='voting_btn'>";
$output .="<div class='down_button'> </div>";
$output .="<span class='down_votes'>0</span>";
$output .="</div>";
$output .="<br>";
$output .="</div>";
$output .="</div>";
$output .="</div>";
$nr++;
}
$output .= "</div>";
echo $output;
}else {
echo "0 results";
}
$conn->close();
function injectNColumnWrapper($cols_per_row, $closePoint, $cssClass="container row", $nthElem=""){
$blockDisplay = "";
if( ($closePoint == 0) ){
$blockDisplay = "<div class='" . $cssClass . " container_nr_" . $nthElem . "'>" . PHP_EOL;
}else if( ($closePoint % $cols_per_row) == 0 && ($closePoint != 0) ){
$blockDisplay = "</div><div class='" . $cssClass . " container_nr_" . $nthElem . "'>" . PHP_EOL;
}
return $blockDisplay;
}
?>
You should have 3 Columns per Row like so:
<div class="container">
<div class="col s12 m6 l4 z-depth-1">Column 1</div>
<div class="col s12 m6 l4 z-depth-1">Column 2</div>
<div class="col s12 m6 l4 z-depth-1">Column 3</div>
</div>
I hope this helps a little bit...
Try it:-
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$row = $ip['id'];
$row = $ip['quote'];
$row = $ip['topic'];
$row = $ip['author'];
$nr = 0;
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10";
$result = $conn->query($sql);
$chngrow=0;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc() ) {
$nr++;
$chngrow = $chngrow + 1;
echo
"<div class='container row'>
<div class='col s12 m6 l4 z-depth-1'>
<div class='card-panel grey darken-4 white-text center'><h5>Citat: ". $row["id"] ."</h5></div> <pre class='flow-text black-text' wrap='soft'>" ."<p class=''>Författare: ". $row["author"] ."</p>"
. "<p class=''>Citat: ". $row["quote"] ."</p>" . $row["topic"] ."</pre>
<div class='content_wrapper'>
<h4>Vote </h4>
<div class='voting_wrapper' id='". $row["id"] ."'>
<div class='voting_btn'>
<div class='up_button'> </div><span class='up_votes'>0</span>
</div>
<div class='voting_btn'>
<div class='down_button'> </div><span class='down_votes'>0</span>
</div>
<br>
</div>
</div>
</div>
</div>";
$mod = ($chngrow % 3);
echo ($mod==0) ? "<br>" : "";
}
}else {
echo "0 results";
}
$conn->close();
?>
Elaborating #RuchishParikh comment, which already contains the core of the solution:
$nr = 0;
while ($row = $result->fetch_assoc()) {
$nr++;
if ($nr % 3 == 0) {
echo "<div class='container row'>\n"; # start of row
}
echo "<div class='col s4 m6 l4 z-depth-1'>\n"; # start of column
echo " ...\n";
echo "</div>\n"; # end of column
if ($nr % 3 == 0) {
echo "</div>\n"; # end of row
}
}
Try like this,
$nr =0;
while($row = $result->fetch_assoc() ) {
$nr++;
if(($count-1)%3==0) echo '<div class="row">';
//Add your content units here.
if(($count)%3==0) echo '</div>';
}
increment a counter variable for every loop. open table tag and tr tag outside of the loop. the while loop should have td tag alone. if count%3==0 then close the tr tag and open a new tr tag.
$i=0
?><table><tr><?
while(condition)
{
$i++;
if($i%3==0)
{
?></tr><tr><?
}
?><td>your data</td><?
}
?></tr></table><?
You messed up with the variables.
Don't need to declare $row below:
$row = $ip['id'];
$row = $ip['quote'];
$row = $ip['topic'];
$row = $ip['author'];
As stated here Why shouldn't I use mysql_* functions in PHP? don't use mysql_* functions.
You need to fetch 3 rows and place them inside one container.
<?php
$servername = "localhost";
$username = "";
$password = "";
$dbname = "";
$db = new PDO("mysql:host=$servername;dbname=$dbname;charset=UTF-8",
$username
$password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT * FROM quotes ORDER BY date DESC limit 10";
$nr = 0;
$stmt = $db->query('SELECT * FROM table');
while($row1 = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row2 = $stmt->fetch(PDO::FETCH_ASSOC);
$row3 = $stmt->fetch(PDO::FETCH_ASSOC);
$rows[] = $row1;
if ($row2) $rows[] = $row2;
if ($row3) $rows[] = $row3;
echo "<div class='container row'>\n"
foreach($rows as $row) {
$nr++;
$id_ = $row["id"];
$author_ = $row["author"];
$quote_ = $row["quote"];
$topic_ = $row["topic"];
echo
"<div class='col s12 m6 l4 z-depth-1'>
<div class='card-panel grey darken-4 white-text center'><h5>Citat:$id_ </h5></div>
<pre class='flow-text black-text' wrap='soft'>
<p class=''>Författare: $author_</p>
<p class=''>Citat: $quote_</p>
$topic_
</pre>
<div class='content_wrapper'>
<h4>Vote </h4>
<div class='voting_wrapper' id='$id_'>
<div class='voting_btn'>
<div class='up_button'> </div><span class='up_votes'>0</span>
</div>
<div class='voting_btn'>
<div class='down_button'> </div><span class='down_votes'>0</span>
</div>
<br />
</div>
</div>
</div>";
}
echo "</div>\n";
$rows = null;
}
if ($nr == 0){
echo "0 results";
}
?>
Try this
$i=0
?><table><tr><?
while(condition)
{
$i++;
if($i%3==0)
{
?></tr><tr><?
}
?><td>your data</td><?
}
?></tr></table><?
I'm working on a real basic chat that is mostly php powered. I'd like to use jQuery to check for new messages and update the #cbox div every few seconds. So far I have tried accomplishing that using the code below. For a frame of reference, this is my first time including jQuery into any of my scripts, so the problem is likely a very simple error that I am overlooking in my newbishness.
The problem I'm running into is the #cbox div displays blank, it doesn't seem to be calling to chat_post.php at all. I will post that code as well, in case the problem is with that and not with my jQuery. To fix, I tried also including <div id='cbox'> in chat_post.php, but that yielded no results. At this point, I'm pretty much grasping at straws.
<div id='sb_content'>
<center><div id='chat'>
<div id='ribbon' style='position: relative; margin-top:-50px; margin-left:-32px;'><center><span class='ribbon'>chat box</span></center></div>
<div style='margin-top: -20px;'><center><span style='text-shadow: 0 0 0.2em #000;' class='admin'>admin</span> || <span style='text-shadow: 0 0 0.2em #000;' class='mod'>mod</span></center></div>
<div id="cbox">
<script>
$(document).ready(function() {
setInterval(function(){getUpdates()}, 2000);
});
function getUpdates() {
$("#cbox").load("chat_post.php");
}
</script>
</div>
<form name="message" method='post' action="chat_post.php" id="cbox_input">
<input name="usermsg"id='usermsg' type="text" size="63" maxlength="255" />
</form>
</div></center>
</div>
chat_post.php
<div id='cbox' align='left'>
<?php
$username = $_SESSION['login'];
$ug = $_SESSION['user_group'];
// Display messages
$sql = <<<SQL
SELECT *
FROM `chat_entries`
ORDER BY `ts` DESC
LIMIT 0,50
SQL;
$result = $db->query($sql);
$count = $result->num_rows;
if ($count != 0){
while ($row = mysqli_fetch_array($result)) {
$c_name = $row['author'];
$c_text = $row['text'];
$c_ts = $row['ts'];
$c_id = $row['id'];
$sqlm = <<<SQL
SELECT *
FROM `users`
WHERE username = '$c_name'
SQL;
$resultm = $db->query($sqlm);
$countm = $resultm->num_rows;
if ($count != 0){
while ($rowm = mysqli_fetch_array($resultm)) {
$c_level = $rowm['user_group'];
}
}
if ($c_level == 'mod') {
echo "
<a href='/user/" . $c_name . "' class='mod'>" . $c_name . "</a>
";
}
if ($c_level == 'admin') {
echo "
<a href='/user/" . $c_name . "' class='admin'>" . $c_name . "</a>
";
}
if ($c_level == 'member') {
echo "
<a href='/user/" . $c_name . "' class='member'>" . $c_name . "</a>
";
}
if ($c_level == 'guest') {
echo "
<i>" . $c_name . "</i>
";
}
echo "
: " . $c_text . "<div id='cbox_div'>";
echo "<span style='float:left;'><i>" . $c_ts . "</i></span>";
echo "<span style='float:right;'>";
if ($ug == 'mod' || $ug == 'admin'){
echo " <a href='#'>Delete</a> || <a href='#'>Block</a> ||";
}
if ($_SESSION['login']) {
echo "Report</span></div>
";
}
}
}
?>
After removing the extra id on chat_post.php, my code worked just fine. Funny how something so simple can really mess things up. (: Thank you everyone for your help!
I am developing a comment box for my website. When a message is posted on the website and another user comes and wants to reply, the previous message message should display below it.
I am showing the message in a <ul>. Each UL child (which is LI), contains a table that shows the message.
Link to image
Comments Showing
Suppose these are the comments showing:
##############################Comment One By David
################################################################ Reply of David
########################## Another Reply of David
########################### Comment Two By Jhon
My messages are showing using AJAX and PHP.
An AJAX script sends data, which goes to a PHP script and then after verification goes to a database and in the mean time it's also updated on the screen.
My problem is that if I want to reply to a message at the end, or want to add a new message it works fine, but when I want to reply to a message which is previously added I do not know how to put it in between html code.
Problem
Suppose I want to reply to "David", when I submit the comment it goes below the last message not between the messages.
HTML
<div id="add-comment" title="Comment">
<ol class="timeline" id="update">
<?
$retrieve = $con->select1("*", "`comments`", "page_id=" . $page_id);
$confirm_author = 0;
while ($row = mysql_fetch_array($retrieve)) {
echo'<table class="shw-comment" id="show-comment-table" ><tbody><tr>';
$name = $con->verify_author($row['name'], $row['email'], $row['website']);
echo'<td align="left" colspan="9" id="name-td">' . $name;
$niceDay = $con->perfect_date_format($row['date_and_time']);
echo'<div align="right" id="comment-date">' . $niceDay . '</div></td></tr><tr>';
echo'<td align="left" id="user-icon-td">';
if ($name == "Author") {
echo '<div class="author" id="user-icon"></div>';
} else {
$hash = md5(strtolower(trim($row['email'])));
$default_usr = urlencode('http://localhost/king-of-developers/images/user-icon.png');
echo "<div class=\"default-user\" id=\"user-icon\"><img src=\"http://www.gravatar.com/avatar/$hash.'.jpg?s=45&d=$default_usr'\" /></div>";
}
echo '</td>';
echo'<td colspan="8" id="user-comments-td" valign="top">' . $row['user_comments'] . '</td>';
echo'</tr><tr>';
echo'<td align="right" colspan="9" id="reply-td"><input type="button" class="reply" name="reply" value="reply" title="reply"/></td>';
echo'<tr>
<td align="left" colspan="9">
<input id="comment-id' . $row['id'] . '" type="hidden" value="' . $row['id'] . '"/>';
echo'</tr>';
echo'</tbody></table></li>';
if($row['respond'] == 1){
$retrieve2 = $con->select1("*", "`comment_respond`", "comment_id=" . $row['id']);
$confirm_author = 0;
while ($row2 = mysql_fetch_array($retrieve2)) {
echo'<table class="shw-comment" id="comment-reply" ><tbody><tr>';
$name = $con->verify_author($row2['name'], $row2['email'], $row2['website']);
echo'<td align="left" colspan="9" id="name-td">' . $name;
$niceDay = $con->perfect_date_format($row2['date_and_time']);
echo'<div align="right" id="comment-date">' . $niceDay . '</div></td></tr><tr>';
echo'<td align="left" id="user-icon-td">';
if ($name == "Author") {
echo '<div class="author" id="user-icon"></div>';
} else {
$hash = md5(strtolower(trim($row2['email'])));
$default_usr = urlencode('http://localhost/king-of-developers/images/user-icon.png');
echo "<div class=\"default-user\" id=\"user-icon\"><img src=\"http://www.gravatar.com/avatar/$hash.'.jpg?s=45&d=$default_usr'\" /></div>";
}
echo '</td>';
echo'<td colspan="8" id="user-comments-td" valign="top">' . $row2['user_comments'] . '</td>';
echo'</tr><tr>';
echo'<td align="right" colspan="9" id="reply-td"><input type="button" class="reply" name="reply" value="reply" title="reply"/></td>';
echo'<tr>
<td align="left" colspan="9">
<input id="comment-id' . $row['id'] . '" type="hidden" value="' . $row['id'] . '"/>';
echo'</tr>';
echo'</tbody></table></li>';
}
}
}
?>
</ol>
Ajax code
$(".submit-comment").click(function(){
var a="",b=0;
var n=$("#your-name").val();
var e=$("#your-email").val();
var w=$("#your-website").val();
var c=$("#comments").val();
var pg=$("#page-no").val();
var rp=$("#respond").val();
var ch=$("[name=recaptcha_challenge_field]").val();
var re=$("[name=recaptcha_response_field]").val();
var confirmAuthor=0;
n=$.trim(n);
e=$.trim(e);
w=$.trim(w);
c=$.trim(c);
var h="name="+n+"&email="+e+"&web="+w+"&comment="+c+"&challenge="+ch+"&response="+re+"&respond="+rp+"&page_id="+pg;
document.getElementById("recaptcha_reload_btn").click();
if(n==""||e==""||c==""||$.trim(re)==""){
a+="\n Please Write Your 'Name' , 'Email' , 'Comments' and 'Captcha' Before Submiting. ";
b++;
}else{
var i=/[-_#'$&`~;?%^)*(#!0-9]/;
var temp=n;
temp.toLowerCase();
if(temp=="author"){
a+="\nInvalid User Name";
b++;
}
if(i.test(n)){
a+="\nPlease Write a Correct Name ! ";
b++;
}
i=/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/;
if(!i.test(e)){
a+="\nPlease Write Valid Email Address ! ";
b++;
}
}
if(b>=1){
alert(a);
}
if(b==0){
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loading.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');
$.ajax({
type:"POST",
url:"admin/include/ajax-comments.php",
data:h,
cache:false,
success:function(a){
$("ol#update").append(a);
$("ol#update li:last").fadeIn("slow");
document.getElementById("your-email").value="";
document.getElementById("your-name").value="";
document.getElementById("your-website").value="";
document.getElementById("comments").value="";
document.getElementById("respond").value="";
$("#recaptcha_reload_btn").click();
$("#your-name").focus();
$("#flash").hide();
}
})
}
return false;
});
PHP Code
<?php
require_once('recaptchalib.php');
$privatekey = "64444444444444";
$resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["challenge"], $_POST["response"]);
if (!$resp->is_valid) {
//What happens when the CAPTCHA was entered incorrectly
die("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
}
else
{
// Your code here to handle a successful verification
require_once '../config.php';
$con = new config();
if ($_POST) {
$name = $_POST['name'];
$email = $_POST['email'];
$web = $_POST['web'];
$comment = $_POST['comment'];
$respond = $_POST['respond'];
$page = $_POST['page_id'];
$name = $con->clean_input($name);
$email = $con->clean_input($email);
$web = $con->clean_input($web);
$comment = $con->clean_input($comment);
$name = $con->sanitizeHTML($name);
$email = $con->sanitizeHTML($email);
$web = $con->sanitizeHTML($web);
$comment = $con->sanitizeHTML($comment);
$con->validateNull($name, "Please Enter Your Name ");
$con->validateEmail($email, "Please Enter Your Valid Email");
$con->validateNull($comment, "Please Don't Leave Empty Comments");
if ($con->errorCounter == 0) {
$name = ucwords(strtolower($name));
$comment = ucfirst(strtolower($comment));
$con->setTime_zone();
$comment_time = date('Y-m-d H:i:s', time());
$comment_time = $con->perfect_date_format($comment_time);
$ip = $con->getIP();
if ($respond >= 1) {
$col[0] = "comment_id";
$col[1] = "name";
$col[2] = "email";
$col[3] = "website";
$col[4] = "user_comments";
$col[5] = "user_ip";
$col[6] = "date_and_time";
$data[0] = "'" . $respond . "'";
$data[1] = "'" . $name . "'";
$data[2] = "'" . $email . "'";
$data[3] = "'" . $web . "'";
$data[4] = "'" . $comment . "'";
$data[5] = "'" . $ip . "'";
$data[6] = "'" . $comment_time . "'";
$con->insert("`comment_respond`", $col, $data);
$con->update("`comments`", "`respond`= 1","`id`='".$respond."'");
}
if ($respond == 0) {
$col[0] = "page_id";
$col[1] = "respond";
$col[2] = "name";
$col[3] = "email";
$col[4] = "website";
$col[5] = "user_comments";
$col[6] = "user_ip";
$col[7] = "date_and_time";
$data[0] = "'" . $page . "'";
$data[1] = "'" . $respond . "'";
$data[2] = "'" . $name . "'";
$data[3] = "'" . $email . "'";
$data[4] = "'" . $web . "'";
$data[5] = "'" . $comment . "'";
$data[6] = "'" . $ip . "'";
$data[7] = "'" . $comment_time . "'";
$con->insert("`comments`", $col, $data);
$comment_id = mysql_insert_id();
}
} else {
$arraysize = count($con->errorMsg);
for ($i = 0; $i < $arraysize; $i++) {
echo $con->errorMsg[$i] . "<br>";
}
}
$confirm_author = 0;
$con->close_connection();
}
}
?>
<li>
<?php
if ($respond >= 1){
echo '<table class="shw-comment" id="comment-reply">';
}
if ($respond == 0){
echo '<table class="shw-comment" id="show-comment-table">';
}
?>
<tbody>
<?
$name = $con->verify_author($name, $email, $web);
?>
<tr>
<td align="left" colspan="9" id="name-td">
<? echo $name; ?>
<div align="right" id="comment-date">
<? echo $comment_time; ?>
</div>
</td>
</tr>
<tr>
<td align="left" id="user-icon-td">
<?
if ($name == "Author") {
echo '<div class="author" id="user-icon"></div>';
} else {
$hash = md5(strtolower(trim($email)));
$def_usr = urlencode('http://www.kingofdevelopers.com/images/user-icon.jpg');
echo "<div class='default-user' id=\"user-icon\"><img src=\"http://www.gravatar.com/avatar/$hash.'.jpg?s=45&d=$def_usr'\" /></div>";
}
?>
</td>
<td colspan="8" id="user-comments-td" valign="top">
<? echo $comment; ?>
</td>
</tr>
<tr>
<td align="right" colspan="9" id="reply-td">
<input type="button" class="reply" name="reply" value="reply" title="reply" />
</td>
</tr>
<tr>
<td align="left" colspan="9">
<?
if($respond >= 1){
$conct ='comment-id'.$respond;
echo "<input id='$conct' type='hidden' value=''/>";
}
if($respond == 0){
$conct ='comment-id'.$comment_id;
echo "<input id='$conct' type='hidden' value=''/>";
}
?>
</td>
</tr>
</tbody>
</table>
If one were to tag each comment with a unique ID, then reference this ID in your AJAX response.
Once the response is received simply find the matching ID and insert HTML comment snippet accordingly.