I am attempting to create a setInterval function to check for new comments, select and post them. So far, it is 'sort-of' working, but not how I want it to. What it is doing is every three seconds re-posting all of my comments instead of just refreshing them.
What am I doing wrong for this to not just refresh the comments?
HTML
<form action="" method="POST" id="comment-form">
<textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input id="comment-button" name="submit" type="submit" value="Post">
</form>
<div id="comment-container">
AJAX
function commentRetrieve(){
$.ajax({
url: "ajax-php/comment-retrieve.php",
type: "get",
success: function (data) {
// console.log(data);
if (data == "Error!") {
alert("Unable to retrieve comment!");
alert(data);
} else {
$('#comment-container').prepend(data);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
console.log("error"); //otherwise error if status code is other than 200.
}
});
}
setInterval(commentRetrieve, 300);
PHP
$user = new User();
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
//$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$select_comments_stmt->execute();
//$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img);
//$comment_array = array();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$comment_id = $row['id'];
$comment_user_id = $row['user_id'];
$comment_username = $row['username'];
$home_comments = $row['comment'];
$comment_date = $row['date'];
$commenter_user_id = $row['user_id'];
$commenter_img = $row['img'];
$commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
if ($home_comments === NULL) {
echo 'No comments found.';
} else {
echo '<div class="comment-post-box">';
echo $commenter_img;
echo '<div class="comment-post-username">'.$comment_username. '</div>';
echo '<div>'.$comment_date. '</div>';
echo '<div class="comment-post-text">'.$home_comments. '</div>';
echo '</div>';
}
}
}
It's because when you have comments you print new one. What i suggest to do is use JSON to get the comments array, pass an ID to each comment and check if the Id is allready present in the list. that way you only paste new comment, here's an example.:
html
<form action="" method="POST" id="comment-form">
<textarea id="home_comment" name="comment" placeholder="Write a comment..." maxlength="1000" required></textarea><br>
<input type="hidden" name="token" value="<?php echo Token::generate(); ?>">
<input id="comment-button" name="submit" type="submit" value="Post">
</form>
<div id="comment-container">
<div id="comment-1">bla bla bla</div>
</div>
js
function commentRetrieve(){
$.ajax({
url: "ajax-php/comment-retrieve.php",
type: "get",
success: function (data) {
// console.log(data);
if (data == "Error!") {
alert("Unable to retrieve comment!");
alert(data);
} else {
var array = JSON.parse(data);
$(array).each(function($value) {
if($('#comment-container').find('#comment-' + $value.id).length == 0) {
$('#comment-container').prepend($value.html);
}
});
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " | " + errorThrown);
console.log("error"); //otherwise error if status code is other than 200.
}
});
}
setInterval(commentRetrieve, 300);
PHP
$user = new User();
$select_comments_sql = "
SELECT c. *, p.user_id, p.img
FROM home_comments AS c
INNER JOIN (SELECT max(id) as id, user_id
FROM profile_img
GROUP BY user_id) PI
on PI.user_id = c.user_id
INNER JOIN profile_img p
on PI.user_id = p.user_id
and PI.id = p.id
ORDER BY c.id DESC
";
if ($select_comments_stmt = $con->prepare($select_comments_sql)) {
//$select_comments_stmt->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$select_comments_stmt->execute();
//$select_comments_stmt->bind_result($comment_id, $comment_user_id, $comment_username, $home_comments, $comment_date, $commenter_user_id, $commenter_img);
//$comment_array = array();
$rows = $select_comments_stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$comment_id = $row['id'];
$comment_user_id = $row['user_id'];
$comment_username = $row['username'];
$home_comments = $row['comment'];
$comment_date = $row['date'];
$commenter_user_id = $row['user_id'];
$commenter_img = $row['img'];
$commenter_img = '<img class="home-comment-profile-pic" src=" '.$commenter_img.'">';
if ($home_comments === NULL) {
echo 'No comments found.';
} else {
$html = "";
$html .= '<div class="comment-post-box">';
$html .= $commenter_img;
$html .= '<div class="comment-post-username">'.$comment_username. '</div>';
$html .= '<div>'.$comment_date. '</div>';
$html .= '<div class="comment-post-text">'.$home_comments. '</div>';
$html .= '</div>';
array('id' => $comment_id, 'html' => $html)
}
}
}
For better improvement, i would suggest looking into NodeJs socket for more realtime update. Here's a few link.
Official NodeJs Website
Official SocketIo Website
Chat tutorial with socketIo and Nodejs
Hope it helps!
Nic
Related
I possible to insert update.php?id=" . $row["id"] . " into AJAX url?
I'm trying to make async sql row updating via form. I don't have specific id, because id is called on click.
JS
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
$.ajax({
type: "POST",
url: 'update.php?id=" . $row["id"] . "',
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
PHP where update.php call is located
$sql3 = "
SELECT id, potnik_id, ura, naslov
FROM prevoznik
ORDER BY HOUR(ura), MINUTE(ura) ASC;
";
$result = $conn->query($sql3);
$potnik = $row["potnik"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
//Spremenjena oblika datuma
$date = date_create($row["ura"]);
$ura_pobiranja = date_format($date,"H:i");
echo "<div class=\"row list divider-gray\">
<div class=\"col-1 fs-09 fw-600\">" . $row["id"] . " </div>
<div class=\"col-3 flex-vcenter-items fw-600 fs-09\">" . $row["naslov"] . " </div>
<div class=\"col-1 flex-vcenter-items fw-600 fs-09\">$ura_pobiranja</div>
";
if ($row["naslov"] !== null) {
echo " <div class=\"col-6 flex-vcenter-items fs-1\">Nastavi uro<form id='form' action='update.php?id=" . $row["id"] . "' method='POST'><input id='id' name='potnik' value='".$row["id"]."' type='hidden' /> <input id='cas' class=\"form-control fancy-border\" type=\"text\" name=\"posodobljeni_cas\"/><input id='submit' type='submit' value='Posodobi'> <label id=\"info\"></label></form></div>";
echo " </div>";
}
else {
echo " </div>";
}
}
} else {
echo "<div class=\"col flex-vcenter-items fw-100 fs-1\"><i class=\"far fa-frown-open pr-3\"></i>Nimaš še nobenih opravil
</div>";
}
First, you will want to fix a lot of your HTML. You have many repeating ID attributes for various HTML elements. This will cause many JavaScript issues and is incorrect syntax for HTML.
$html = ""
$id = $row['id'];
if ($row["naslov"] !== null) {
$html .= "<div class='col-6 flex-vcenter-items fs-1'>\r\n";
$html .= "\tNastavi uro\r\n";
$html .= "\t<form id='form-$id' action='update.php?id=$id' method='POST' data-id='$id'>\r\n";
$html .= "\t\t<input id='cas-$id' class='form-control fancy-border' type='text' name='posodobljeni_cas' />\r\n";
$html .= "\t\t<input id='submit-$id' type='submit' value='Posodobi'> <label id='info-$id'></label>\r\n";
$html .= "\t</form>\r\n</div>\r\n";
$html .= "</div>";
echo $html;
} else {
echo " </div>";
}
You can see a lot being done here. First we create a $html and $id variable to just make things easier. Now when we enter String data into the $html variable, if we're using " (double quote) for wrapping, we can just use $id directly in the string. We will also use ' (single quote) for wrapping all the HTML Element attributes.
Try this for your jQuery:
$(function(){
$("form[id|='form']").on('submit', function(e) {
e.preventDefault();
var form = $(this);
var id = form.data("id");
var cas = $("inptu[id|='cas']", form);
var info = $("input[id|='info']", form);
if(validate()) {
$.ajax({
type: "POST",
url: form.attr("action"),
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
});
More Info on the selector: https://api.jquery.com/attribute-contains-prefix-selector/
Unable to test this as you have not provided a testing area. Hope it helps.
You can assign the PHP $row['id']; variable to a local JS variable and append it to the URL as shown below -
submit.on('click', function(e) {
e.preventDefault();
if(validate()) {
var id=<?=$row['id'];?>;
$.ajax({
type: "POST",
url: 'update.php?id='+id,
data: form.serialize(),
dataType: "json"
}).done(function(data) {
if(data.success) {
id.val('');
cas.val('');
info.html('Message sent!').css('color', 'green').slideDown();
} else {
info.html('Could not send mail! Sorry!').css('color', 'red').slideDown();
}
});
}
});
here in my code i am trying to fetch and display the data after selecting a option from the dropdown using onChange, fetching data from a PHP file and via ajax displaying it in textarea in same select.php file but unfortunately it is not working out for me am quit confused were i made a mistake, please help me out on this.
select.php
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#channel").change(function(){
$.post("ajax.php", { channel: $(this).val() })
.success(function(data) {
$(".result").html(data);
});
});
});
</script>
</head>
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" id = 'channel' name="ProductCategoryID" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="1234">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group result"></div>
ajax.php
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode = '$channel' ";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
while($row = mysql_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
Try using:
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
May be it would help
replace,
$.post("ajax.php", { channel: $(this).val() })
with
$.post("ajax.php", { 'channel': $(this).val() })
$.post("ajax.php", { channel: $(this).val() },function(data) {
$(".result").html(data);
});
Please remove .success(function(data){ }) from the code and it will work :)
Try to initiate $msg first and use mysqli module.
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode =$channel";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
UPDATE
Update your post request with:
$.post("ajax.php",
{ channel: $(this).val() },
function(data) {
$(".result").html(data);
}
);
OR
$.post("ajax.php",
{ channel: $(this).val() },
successCallback
);
function successCallback(data){
//process data..
}
see https://api.jquery.com/jquery.post
I have currently implemented a live search (search as you type) function on text fields. The flow is something like this.
Call a .js file inside the page.
Set the id of the text field to "client-search".
Inside the .js file it is currently listening for on key up events of the "client-search" text field.
If the on key up event is fired, the .js file calls a PHP file that searches the database and returns the output as a list item in an unordered list underneath the "client-search" text field.
This setup currently works but how do implement it in multiple fields inside a single page, since it works using "id" and obviously I can't have multiple IDs in a single page.
HTML:
<div class="input-group">
<input type="text" id="client-search" class="form-control" placeholder="Search for manager...">
<ul class="livesearch" id="client-result" onclick="clickResult()"></ul>
</div>
JS
/* JS File */
// Start Ready
$j(document).ready(function() {
// Icon Click Focus
$j('div.icon').click(function(){
$j('input#client-search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#client-search').val();
$j('b#search-string').text(query_value);
if(query_value !== ''){
$j.ajax({
type: "POST",
url: "clientsearch.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#client-result").html(html);
}
});
}return false;
}
$j("input#client-search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$j("ul#client-result").fadeOut();
}else{
$j("ul#client-result").fadeIn();
$j(this).data('timer', setTimeout(search, 100));
};
});
});
PHP:
<?php
$serverName = "(local)";
$connectionInfo = array( "Database"=>"CMS");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
} else {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$html = '';
$html .= '<li value="myLi" class="myLi">';
$html .= '<small>nameString</small>';
$html .= '<small></small>';
$html .= '</li>';
$search_string = $_POST['query'];
//$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$sql = "SELECT TOP 10 ClientName FROM Client WHERE ClientName LIKE '%" . $search_string . "%'";
$params = array($search_string);
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results_array[] = $row;
}
if (isset($results_array)) {
foreach ($results_array as $result) {
$display_function = $result['ClientName'];
$display_name = $result['ClientName'];
$output = str_replace('nameString', $display_name, $html);
//$output = str_replace('functionString', $display_function, $output);
echo($output);
}
}else{
$output = str_replace('nameString', '<b>No Results Found.</b>', $html);
$output = str_replace('functionString', 'Sorry :(', $output);
echo($output);
}
}
?>
My delete function isn't working.
This is my table with the delete button.
// retrieve table contents
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
//creating new table row per record
echo "<tr>";
echo "<td class='text-align-center'><input type='checkbox' name='item[]' class='checkboxes' value='{$employeeid}' /></td>";
echo "<td>{$name}</td>";
echo "<td>{$title}</td>";
echo "<td>{$phone}</td>";
echo "<td>{$supplier_name}</td>";
echo "<td>{$created}</td>";
echo "<td>";
// update record
echo "<a href='update_product.php?employeeid={$employeeid}' class='btn btn-info margin-right-1em'>";
echo "<span class='glyphicon glyphicon-edit'></span> Rediger";
echo "</a>";
// delete record
echo "<a delete-employeeid='{$employeeid}' delete-file='delete_product.php' class='btn btn-danger delete-object'>";
echo "<span class='glyphicon glyphicon-remove'></span> Slet";
echo "</a>";
echo "</td>";
echo "</tr>";
}
//end table<br>
echo "</table>";
This is my delete function
// delete single record
$(document).on('click', '.delete-object', function(){
// php file used for deletion
var delete_file = $(this).attr('delete-file');
var id = $(this).attr('delete-id');
var q = confirm("Are you sure?");
if (q == true){
$.post(delete_file, {
object_id: id
}, function(data){
location.reload();
}).fail(function() {
alert('Unable to delete.');
});
}
return false;
});
I got the code from a tutorial that I modified a lot. Everything else is working, except the delete function.
PHP CODE
<?php
// check if value was posted
if($_POST){
// include database and object file
include_once 'config/database.php';
// delete query
$query = "DELETE FROM employeestest WHERE employeeid = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_POST['object_employeeid']);
if($stmt->execute()){
// redirect to read records page and
// tell the user record was deleted
echo "Medarbejderen er slettet.";
}else{
echo "Medarbejderen kunne ikke slettes.";
}
}
?>
Change
var id = $(this).attr('delete-Id');
to
var id = $(this).attr('delete-employeeid');
And, Change $.post to $.ajax as i've given
<script>
$(document).on('click', '.delete-object', function(){
var delete_file = $(this).attr('delete-file');
var id = $(this).attr('delete-employeeid');
var q = confirm("Are you sure?");
if (q == true)
{
$.ajax({url:delete-file,cache:false,success:function(result){
alert('Successfully Deleted');
}});
}
return false;
});
</script>
Maybe you just made grammar mistake
'delete-id' => 'delete-employeeid'
I have a Ajax PHP Show More feature like youtube and Live search scripts but I can't get them to work together. For example my live search works but then the show more feature doesn't work with it on the search results and when I use the show more then the live search doesn't work.
They don't seem to be messing with each other. Can anyone help me out? I am new to this website so I will try my best to show my code and explain it.
INDEX.PHP
<?php
include_once("connect.php");
$sql = "SELECT COUNT(*) FROM database";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
$item_per_page = 3;
$total_rows = mysqli_fetch_array($query);
$pages = ceil($total_rows[0]/$item_per_page);
?>
<!DOCTYPE html>
<head>
<script type="text/javascript">
// Show More Scripted
$(document).ready(function() {
var track_click = 0;
var total_pages = <?php echo $pages; ?>;
$('#news-table-wrap').load("showmore_search.php", {'page':track_click}, function() {track_click++;});
$(".load_more").click(function (e){
$(this).hide();
$('.animation_image').show();
if(track_click <= total_pages){
$.post(showmore_search.php',{'page': track_click}, function(data) {
$(".load_more").show();
$("#news-table-wrap").append(data);
$("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 500);
$('.animation_image').hide();
track_click++;
}).fail(function(xhr, ajaxOptions, thrownError){
alert(thrownError);
$(".load_more").show();
$('.animation_image').hide();
});
if(track_click >= total_pages-1){
$(".load_more").attr("disabled", "disabled");
}
}
});
});
// Live Search Script
function searchNews(value) {
$.post("showmore_search.php", {newsResult:value}, function(data){
$("#news-table-wrap").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="search" id="search" class="search-box" onKeyUp="searchNews(this.value)" placeholder="Search News">
<table id="news-table-wrap" class="news-table-wrap" cellpadding="0" cellspacing="0">
</table>
<div align="center">
<div class="load_more" id="load_more_button">Show More</div>
<div class="animation_image" style="display:none;"><img src="/files/ajax-loader.gif"></div>
</div>
</body>
</html>
SHOWMORE_SEARCH.php
<?php
include_once("connect.php");
$newsResult = $_POST['newsResult'];
$item_per_page = 3;
$page_number = $_POST["page"];
$position = ($page_number * $item_per_page);
$sql = "SELECT * FROM database WHERE headline LIKE '%$newsResult%' OR post LIKE '%$newsResult%' ORDER BY date DESC LIMIT $position, $item_per_page";
$query = mysqli_query($connect,$sql) or die (mysqli_error());
while ($row = mysqli_fetch_array($query)){
$headline = $row['headline'];
$author = $row['author'];
$date = $row['date'];
$post = $row['post'];
$name = $row['name'];
echo "<tr class='news-preview-wrap'>";
echo "<td><div class='news-preview-content'><div class='news-preview-headline'><a href='news_post?name=".$name."'>".$headline."</a></div>
<div class='news-preview-date'>Written by ".$author." on ".$date."</div>
<div class='news-preview-post'>".$post."</div></div>
<div class='news-more'><a href='news_post?name=".$name."'>Read More</a></div></td>";
echo "</tr>";
} else {
echo "<div class='search-error'>No search results were found...</div>";
}
?>
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
})
;
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}