How can I add a reply function to comments? - javascript

I've created a comment function to my website. I would like to add a reply function to it, but I'm not sure how to do it.
I am able to post comments and retrieve them on the website.
I would like to do a reply function which uses it's "parents" id to show up underneath it.
Desired output:
First Comment
First reply
Second reply
Second Comment
First reply
Second reply
My program looks like this:
<html>
<form action="" method ="POST">
Namn: <br>
<input type="text" name ="name"><br>
Kommentar: <br>
<textarea name="comment" rows="10" cols="20"> </textarea><br>
<input type ="submit" name ="submit" value="Skicka">
</form>
</html>
connectDB
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'com';
$connect = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname) or die(mysqli_error($connect));
?>
getComments
<?php
include ('connectDB.php');
if($connect){
mysqli_select_db($connect, "comments");
$query2 = "SELECT * FROM data ORDER BY `id` DESC";
$result = mysqli_query($connect, $query2);
$comments = array();
while($row = mysqli_fetch_array($result)){
$name = $row['Name'];
$comment = $row['Comment'];
$date = $row['Date'];
echo "
<div style='width:60%' class='col-lg-12'>
<div class='panel panel-default'>
<div class='panel-heading'>
<strong> $name </strong><span style='float:right'class='text-muted'>$date</span>
</div>
<div class='panel-body'>$comment
</div>
</div><!-- /panel panel-default -->
</div><!-- /col-sm-5 -->";
}
}
?>
StoreComments
<?php
if(isset($_POST['submit'])){
$name = htmlentities($_POST['name']);
$comment = htmlentities($_POST['comment']);
$date = date("Y-m-d");
$connect = mysqli_connect("localhost", "root", "");
if($connect){
mysqli_select_db($connect, "comments");
$query = "INSERT INTO data(Name, Comment, Date) VALUES (\"" . $name . "\", \"" . $comment . "\", \"" . $date . "\")";
if(mysqli_query($connect, $query)){
} else {
die ("Failed: " . mysqli_error($connect));
}
} else {
die("Failed to connect to mysql: " . mysqli_errno($connect));
}
}
}
?>

To prevent the N+1 queries problem, when for each comment you make another one query to find replies, you can use the Nested Set Model strategy, like described in this topic: php / Mysql best tree structure
See the post about Managing Hierarchical Data in MySQL.
[UPDATE]
Or if you dont care about performance you can follow this topic solution: Nested comments in PHP & MySQL

Related

How do get php array in javascript variable

I am using following code .
<?php
$dbhost = 'localhost';
$dbuser = '****';
$dbpass = '******';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM mytable';
mysql_select_db('sujeet_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['firstname']} <br> ".
"EMP NAME : {$row['lastname']} <br> ".
"EMP SALARY : {$row['doj']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
to get data from db . But I want to store these data in JavaScript variable for future use. Like var users=$row; but it is not working.
You can do this by putting your mysql result in json format and print it with script tag to use it in javascript like:
<script>
var result = '<?php echo json_encode($row);?>';
</script>
you could do this by assigning inside script tag here is how.
<script>
var spge = '<?php echo json_encode($row); ?>';
alert(spge);
console.log(spge);
</script>

How to link my simple jQuery Input with PHP script and Store data into a MYSQL DB?

What I'm trying to do is very simple.
Have a simple input, that allows me to input a name+link, add it to a list and save it to a DB so it's saved.
In my HTML file I currently have:
<form id="form">
<input id="create-input" type="text" placeholder="To do">
<input id="create-link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
In my JS file I have:
$(function(){
$('#submit').on('click', addListItem);
});
function addListItem() {
// Grab Input Data
var text = $('#create-input').val();
var link = $('#create-link').val();
// Creating To Do List
$('#todo').append('<li>' +text+' - '+link+ ' <button class="delete">Edit</button> <button class="delete">Delete</button> <button class="delete">Bukkaked!</button></li>');
$('#create-input').val('');
$('#create-link').val('http://');
}
In my PHP file (connecting to DB) I have:
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
// Check for Success
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Now I know I need to somehow pass the vars (text and link) through to the PHP file:
$sql = "INSERT INTO bucketlist (item, link) VALUES ('Thom', 'www.google.com')";
But I have no idea how.
Any tips?
Why do you need JQuery you can pass values using php only
here is a change in your code:-
<form id="form" method="post" action="process.php">
<input id="create-input" name="item" type="text" placeholder="To do">
<input id="create-link" name="link" type="text" placeholder="http://">
<button id="submit" type="button">Add Item</button>
</form>
<ul>
<?php include('conn.php');
$sql = "SELECT * FROM bucketlist";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo '<li>Item-'. $row["item"].' & Link-'. $row["link"].'</li>';
}
} else {
echo "<li>No List</li>";
}
?>
</ul>
conn.php
<?php
$servername = "localhost";
$database = "bucketlist";
$username = "bucketuser";
$password = "125632";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
process.php
<?php
include('conn.php');
$item = $_POST['item'];
$item = $_POST['link'];
$sql = "INSERT INTO bucketlist (item, link) VALUES ($item,$link)";
// Check for Success
if (mysqli_query($conn, $sql)) {
header('location:yourpage.php');
}
// Check for Fail
else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Hope this helps.
Use ajax to post the values of the item and link in your html form to your PHP script.
Something like :
var myItem = $('#create-input').html();
var myLink = $('#create-link').html();
$.ajax({
type: 'POST',
url: 'https://yoururl/api/post.php',
data: {item:myItem,link:myLink},
success: SuccessCall,
error : FailureCall,
cache:false,
async:true,
dataType: 'html'
});
function SuccessCall(data,status){
alert("response from server is "+data);
}
function FailureCall(data,status){
alert("Server connection error");
}
Use the PHP script posted by SYB to retrieve the values of item and link that were sent from your html form.

PHP Coding to Connect MYSQL Issues

I am creating a database to make my 'PHP' website but I couldn't do this. My website is cruzapp that is related to rideshare companies and changing it in to php to get details about our users. But I can't connect MYSQL by using the following PHP code:
?php
$username = "name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Not connected to MySQL");
echo "Connected to MySQL<br>";
//select a database to work with
$selected = mysql_select_db("examples",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT id, model,year FROM cars");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo "ID:"$row{'id'}." Name:".$row{'model'}."Year: ". //display the results
$row{'year'}.<br>";
}
//close the connection
mysql_close($dbhandle)
?>
Can anyone help me to debug this code?
I will be very thankful to you.
Try this one out. It uses MySQLi with error echoing.
<?php
$username = "name";
$password = "password";
$hostname = "host";
$database = "examples";
$con = mysqli_connect($hostname, $username, $password, $database);
if (!$con) {
exit("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($con, "SELECT id, model,year FROM cars");
if (mysqli_error($con)) {
exit("Error: " . mysqli_error($con));
}
while ($row = mysqli_fetch_array($result)) {
echo "ID:" . $row['id'] . " Name:" . $row['model'] . "Year: " . $row['year'] . "<br>";
}
mysqli_close($con);
First of all you should not use mysql because with PHP 7 mysql extension does not work anymore. so you must consider to change it to mysqli or PDO. PDO is recommended. Any how for a quick fix $selected = mysql_select_db($dbhandle,"examples") do this and also check all your values like hostname database name table name and make sure there are no mistakes.

Get the value of input field through ajax then pass it to php

I am new with ajax somebody help me I want to create a form that include input field.
Whenever I click the button I will get the value of input field and it declared it as data in AJAX and the value from ajax it pass to PHP script. It will display a table.
My question is how to get the value of input field and declared it as data in AJAX. After click the table will declared in success in AJAX Script that will show a table.
Thank you in advance
UPDATE:
#J_D, Here's my html code for my form:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<table cellpadding="15px">
<tr>
<td>Transmittal #</td>
<td><input type="text" class="form-control" style="padding-left:5px;" name="transmittal_number_inquiry" id="transmittal_number_inquiry" class="transmittal_number_inquiry" onKeyPress="return isNumberKey(event)" required></td>
</tr>
</table>
<div style="float:right; padding-right:110px; padding-top:10px;">
Inquire
<?php /*?><input type="submit" class="btn btn-info" data-toggle="modal" id="btn-inquire-transmittal-number" name="btn-inquire-transmittal-number" data-backdrop="false" value="Inquire"><?php */?>
<?php /*?><button type="submit" class="btn btn-info" data-toggle="modal" id="btn-inquire-transmittal-number" name="btn-inquire-transmittal-number" data-backdrop="false">Inquire</button><?php */?>
</div>
</form>
Here's my AJAX Code:
$(document).ready(function(){
$('.btn-inquire-traensmittal-number').click(function(){
$inputtextval = $('#transmittal_number_inquiry').val();
$.ajax({
type: 'POST',
url: getTransmittalNum.php,
data: {'transmittal_number_inquiry' : $inputtextval},
success: function(res){
}
});
});
});
Here's the getTransmittalNum.php code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "etransmittal";
$selectedTransmittal = $_GET['q'];
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['inquire-transmittal-number'])){
$query = "SELECT en.transid, en.transdate, CONCAT(userlist.lname, ', ', userlist.fname, ' ', userlist.mname) AS sender_name,
userlist.`department`, en.document_number, doctype.document_type, doctype.document_description, vendor.`vendor_name`, en.`remarks`,
en.status_id, stat.status_name, en.total_amount
FROM tbl_encode_transmittal en
LEFT JOIN tbl_vendor vendor ON vendor.`vendor_id` = en.vendor_id
LEFT JOIN tbl_doctype doctype ON doctype.`doc_id` = en.doctype_id
LEFT JOIN tbl_userlist userlist ON userlist.userid = en.sender_id
LEFT JOIN tbl_userlist userlist1 ON userlist1.userid = en.`receiver_id`
LEFT JOIN tbl_status stat ON stat.status_id = en.status_id
WHERE en.`transid` = '{$_POST['transmittal_number_inquiry']}'";
$result = mysqli_query($con, $query);
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
}
else{
echo 'MYSQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($con);
}
?>
Try following code :
$(document).ready(function(){
$('#btn-inquire-transmittal-number').click(function(){
$inputtextval = $('#transmittal_number_inquiry').val();
$.ajax({
type: 'POST',
url: 'getTransmittalNum.php', // wrap code with quote
data: {'transmittal_number_inquiry' : $inputtextval},
dataType : 'json', // expecting result type json
success: function(res){
// once you got result,
// populate table here
}
});
});
});
PHP
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "etransmittal";
//$selectedTransmittal = $_GET['q']; //<---- u need this?????
$con = mysqli_connect($servername,$username,$password,$dbname);
if(!$con){
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST['transmittal_number_inquiry'])){ // <-- check for existence
$query = "SELECT en.transid, en.transdate, CONCAT(userlist.lname, ', ', userlist.fname, ' ', userlist.mname) AS sender_name,
userlist.`department`, en.document_number, doctype.document_type, doctype.document_description, vendor.`vendor_name`, en.`remarks`,
en.status_id, stat.status_name, en.total_amount
FROM tbl_encode_transmittal en
LEFT JOIN tbl_vendor vendor ON vendor.`vendor_id` = en.vendor_id
LEFT JOIN tbl_doctype doctype ON doctype.`doc_id` = en.doctype_id
LEFT JOIN tbl_userlist userlist ON userlist.userid = en.sender_id
LEFT JOIN tbl_userlist userlist1 ON userlist1.userid = en.`receiver_id`
LEFT JOIN tbl_status stat ON stat.status_id = en.status_id
WHERE en.`transid` = '{$_POST['transmittal_number_inquiry']}'";
$result = mysqli_query($con, $query);
$rows = array();
if($result){
while($row = mysqli_fetch_assoc($result)){
$rows[] = $row;
}
}
else{
echo 'MYSQL Error: ' . mysqli_error();
}
$json = json_encode($rows);
echo $json;
mysqli_close($con);
}
?>

How to create search box in php?

I have implemented search box for my website by using php, html and jquery.
Firstly, I have created a database,
using php I have sorted the values and
using jquery and html I have shown the search result in a div below the search box.
My problem is that I am not able to select the result using down or up key, for this I also tried to make the result in list or drop box in php.
Please correct me if I am wrong some where. Below is the code which is I am using.
<body>
<h1>Search web page</h1>
<form action="search_demo.php" method="post" >
<input type="text" name="search" placeholder="search here" onkeydown="searchq();" />
<input type="submit" value=">>" />
<div id="output" style="z-index: 10; position: absolute ; background-color: yellow;">
</div>
<div id="stable" style="">
</div>
</form>
</body>
<script>
function searchq(){
var searchtxt = $("input[name='search']").val();
$.post("search_demo12.php", {searchval : searchtxt}, function(output) {
$("#output").html(output);
});
}
</script>
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['searchval'])){
$search = $_POST['searchval'];
// $search = preg_replace("#[^0-9a-z]#i","",$search);
$pieces = explode(" ", $search);
$pieces_count = count($pieces);
// $pieces[0] = preg_replace("#[^0-9a-z]#i"," ",$pieces[0]);
// $pieces[1] = preg_replace("#[^0-9a-z]#i"," ",$pieces[1]);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select * from search_demo where fname like '%$search%' or lname like '%$search%'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
}
echo ($output);
Do you mean you cannot select results using up and down keys?
I think it is because you are not wrapping options in select list . Do this
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
echo "<select>".$output."</select>";
In this case I think that it's better to use onkeyup() JavaScript function as you are implementing live search and need output to be changed dynamically..

Categories