Alexander Norton Alexander Norton - 26 days ago 7
CSS Question

Checking if searched item exists in database - PHP won't output anything but will still add item to the database

I'm learning PHP and am looking to solve my PHP, JS and SQL issue.

If necessary, to ensure you understand exactly what the issue is, you may need you to set up the HTML, CSS, PHP and JS to work with your SQL database. I ask of your time only if you have it.

As you can probably tell, I have a search bar. The user types their interest into the search bar and it adds that interest to the database. If their interest exists in the database (as in someone else has the same interest) it uses an if statement to say so. However, for some reason it will not do anything if an interest is found (not even that test alert). It will however insert something into the database (in this case the number of other existing interests) which is very strange. I have inserted comments in the PHP file to explain what is happening and where the issue is.

Here is the PHP, JS, CSS and HTML respectively:



<?php
error_reporting(E_ALL ^ E_NOTICE);//TO REMOVE THE ANNOYING KEYWORD ERRORS
function connect() {
return new PDO('mysql:host=localhost;dbname=mysite', 'username', 'pw', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}

//GET THE USERS IP
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else{
$ip=$_SERVER['REMOTE_ADDR'];
}

$pdo = connect();

//OUTPUT THE SEARCHBAR SUGGESTIONS (OBTAIN SUGGESTIONS FROM DATABASE)
$testing = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM interests WHERE interestName LIKE (:testing) ORDER BY id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':testing', $testing, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
$interestName = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['interestName']);
$interestlist = '<li onclick="set_item(\''.str_replace("'", "\'", $rs['interestName']).'\')">'.$interestName.'</li>';
if (strlen($_POST['keyword']) > 0){
echo $interestlist; //THIS IS THE SUGGESTION BAR OUTPUT WITH THE SUGGESTIONS
}
}
//EVERYTHING ABOVE THIS WORKS.. THIS IS THE ISSUE HOWEVER:

if(isset($_POST['counter'])=="counter"){
//INSERT THE INTEREST INTO THE DATABASE, WITH THE USER'S IP.
$interestid=$_POST['interestinput'];
$insertion = "INSERT INTO users (ipaddress, interest)
VALUES ('$ip', '$interestid')";
$pdo->query($insertion);
//INSERTION WORKS. NOW I WANT TO CHECK IF INTEREST EXISTS. IF IT DOES EXIST, PRINT 'Users exist!':
$item ="SELECT * FROM `users` WHERE interest LIKE '$interestid'";
$result = $pdo->query($item)->fetchAll();
$counted = count($result); //COUNT NUMBER OF RESULTS, THEN INSERT IT AS A TEST.
$insertion = "INSERT INTO users (ipaddress, interest)
VALUES ('$ip', '$counted')";
if (count($result) > 1) {
$pdo->query($insertion); //TEST IF IT WORKS -- THIS INSERTS THE TOTAL NUMBER OF SAME INTERESTS. IT WORKS!
//BUT..
echo ("Users exist!"); //THIS DOES NOTHING? <--------- THE ISSUE
echo "<script> alert('Test'); </script>"; //THIS ALSO DOES NOTHING (as a test)
}
}
?>







//THIS FUNCTION IS CALLED WHEN THE USER HITS ENTER:
function enterPressed(e, field) {
if (e.keyCode == 13) {
var tb = document.getElementById("searchbox");
if (field.value.length > 0) {
document.getElementById('searching').style.display='block';
document.getElementById('searchdisappear').style.display='none';
$.ajax({
type: 'POST',
url: './php/phprefresh.php',
data: {interestinput: field.value, counter: "counter"},
});
}
}
}

//THIS FUNCTION GIVES INTEREST SUGGESTIONS (PULLED FROM THE DATABASE):
function autocomplet() {
var workchecker = 0
var min_length = 1;
var keyword = $('#searchbox').val();
if (keyword.length == min_length) {
$.ajax({
url: './php/phprefresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#interest_list_id').show();
$('#interest_list_id').html(data);
}
});

} else {
$('#interest_list_id').hide();
}
}

//THIS FUNCTION SETS THE SUGGESTION INTO THE SEARCH BOX WHEN CLICKED
function set_item(item) {
$('#searchbox').val(item);
$('#interest_list_id').hide();
}

/*Input*/
input.interestsearch {
margin: auto;
margin-top: 30px;
width: 540px;
height: 30px;
font-size: 22px;
display: block;
padding: 2px 2px 2px 8px;
outline: none;
}

.input_container {
padding: auto;
margin: auto;
margin-top: -10px;
width: 520px;
display: block;
outline: none;
font-size: 20px;
}

.input_container ul {
list-style: none;
border-radius: 15px;
padding: 5px;
color: black;
}

.input_container ul li:hover {
border: 1px solid black;
border-radius: 15px;
cursor: pointer;
width: 500px
}

<!DOCTYPE html>

<html lang = "en">

<head>
<title>Testsite</title>
<link rel="stylesheet" type="text/css" href="./css/main.css">
<script src ="./js/search.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>

<body">


<!-- SEARCH BAR -->
<div id="searchdisappear" style="display:block;">
<center><h1> INTEREST SEARCH </h1></center>
<input class="interestsearch" id="searchbox" maxlength="200" type="text" title="Search for an interest" onkeyup="autocomplet();" autocomplete="off" onkeypress="enterPressed(event, searchbox);" placeholder="Search for an interest.."/>
<div class="input_container">
<ul id="interest_list_id"></ul>
</div>
</div>

<!-- CONNECTING PEOPLE WITH SAME INTEREST-->
<div id="searching" style="display:none;">
<center> <p>Finding people..</p></center>
</div>

</html>





Do not hesitate to ask any questions about the code. I am happy to answer anything!

I really appreciate anyone's time. It has been driving me crazy for far too long.

Answer

Add a

<div id="response"></div>

to your HTML which will display the result then add a success: argument in the enterPressed function. ie.

function enterPressed(e, field) {
    if (e.keyCode == 13) {
        var tb = document.getElementById("searchbox");
        if (field.value.length > 0) {
            document.getElementById('searching').style.display='block';
            document.getElementById('searchdisappear').style.display='none';
            $.ajax({
                type: 'POST',
                url: './php/phprefresh.php',
                data: {interestinput: field.value, counter: "counter"},
                success: function() { 
                    $("#response").html("<p>User Exists</p>");  
                }
            });
        }
    }
}

If you want to display echo text (in HTML form) from phprefresh.php change the success: to

success: function(data) { 
    $("#response").html(data);     
}
Comments