检查数据库中是否存在搜索项 - PHP不会输出任何内容,但仍会将项添加到数据库

时间:2016-11-06 04:58:47

标签: javascript php html css

我正在学习PHP,并希望解决我的PHP,JS和SQL问题。

如有必要,为了确保您确切了解问题所在,您可能需要设置HTML,CSS,PHP和JS以使用SQL数据库。只有你拥有它,我才会问你的时间。

你可以说,我有一个搜索栏。用户在搜索栏中键入他们感兴趣的内容,并将该兴趣添加到数据库中。如果他们的兴趣存在于数据库中(就像其他人有相同的兴趣一样),它会使用if语句来表达。但是,出于某种原因,如果找到兴趣(甚至不是测试警报),它将不会做任何事情。然而,它会在数据库中插入一些东西(在这种情况下是其他现有兴趣的数量),这是非常奇怪的。我在PHP文件中插入了注释,以解释发生了什么以及问题出在哪里。

分别是PHP,JS,CSS和HTML:



<?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)
	}
}
?>
&#13;
&#13;
&#13;

&#13;
&#13;
//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();
}
&#13;
/*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
}
&#13;
<!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>
&#13;
&#13;
&#13;

不要犹豫,询问有关代码的任何问题。我很乐意回答任何问题!

我非常感谢任何人的时间。它让我疯狂了很长时间。

1 个答案:

答案 0 :(得分:1)

添加

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

到将显示结果的HTML,然后在enterPressed函数中添加success:参数。即

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>");  
                }
            });
        }
    }
}

如果要从phprefresh.php显示回显文本(以HTML格式),请将成功更改为

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