21
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

MySQLからリアルタイムで補完のやつ

Posted at

ありがちなやつです。
備忘録というよりかは作ってみたのでメモ的なやつです。

jQueryの.autocomplete()を使いました。
Googleの検索みたいな感じのを目指しましたが、そんないいものではないです。

名前の検索でひらがな打ったら感じが出てくる的なものを作りたかったが、
とりあえずは、漢字で検索して漢字が出てくる的な感じです。(笑)

入力の手間を省くというだけです。
また補強して載せたいと思います。

index.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Welcome!</title>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>

<h1>Search Autocomplete</h1>
<form id="searchform" method="post">
<div>
	<label for="search_term">Search name</label>
  	<input type="text" name="search_term" id="search_term" />
    </div>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script><script type='text/javascript'>

$(document).ready(function(){
  $("#search_term").keyup(function(e){
    e.preventDefault();
    var search_val = $("#search_term").val();
    $.post("autocomplete.php", {search_term : search_val}, function(data){
      if(data.length>0){
        $("#search_term").autocomplete({
          source: data
        });
      }
    })
  });
});
</script>
</body>
</html>

autocomplete.php
<?php
define(HOST, "xxx");
define(USER, "xxx");
define(PW, "xxx");
define(DB, "xxx");

$connect = mysqli_connect(HOST,USER,PW) or die('Could not connect to mysql server.' );
mysqli_select_db($connect,DB) or die('Could not select database.');
mysqli_set_charset($connect, "utf8");

$term = strip_tags(substr($_POST['search_term'],0, 100));
$term = mysqli_real_escape_string($connect,$term);

$sql = "SELECT member_name FROM members where member_name like '%$term%' order by member_name asc";
$result = mysqli_query($connect,$sql);

if(mysqli_num_rows($result) > 0){
  while($row = mysqli_fetch_assoc($result)){
    $string[] = $row['member_name'];
  }
}

$words = array();
foreach($string as $word){
  if(mb_stripos($word, $term) !== FALSE){
    $words[] = $word;
  }
}

header("Content-Type: application/json; charset=utf-8");
echo json_encode($words);

21
20
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
20

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?