我正在尝试为我的网站数据库做一个基本的搜索功能。我想使用Wordpress和WPDB搜索自定义数据库表中的文本内容。
出于某种原因,搜索没有从数据库返回任何内容,但我也没有收到任何错误消息。这是我的代码:
第页。php:
<form class="searchCV_form" role="form" action="">
<div>
<input type="text" id="search_text" name="search_text" class="cv__text">
<span class="input-group-btn">
<button type="submit" class="btn btn-default btn-primary cv__button search--form-btn">SUBMIT</button>
</span>
</div>
</form>
<div id="search_results"></div>
<script>
// wrap everything in a closure
(function($){
// get our references
var $form = $(\'form.searchCV_form\'),
$search_field = $(\'#search_text\'),
$results = $(\'#search_results\');
// AJAX search call
function do_search() {
// grab the query value from the search field
var search_text = $search_field.val();
// do a POST ajax call
$.ajax({
type: "POST",
url: \'<?php echo admin_url(\'admin-ajax.php\'); ?>\',
data: ({
action: "search_cv",
search_text: search_text
}),
success: function (response){
console.log(response);
$results.html(response);
}
});
}
// on submit, do the search but return false to stop page refresh
$form.submit(function(e) {
do_search();
return false;
});
})(jQuery);
</script>
功能。php:
function search_cv()
{
// get the search query
$search_text = ($_POST["search_text"]);
// clean it up
$search_text = sanitize_text_field( $search_text);
// ... do stuff with it
global $wpdb;
$result = $wpdb->get_results( $wpdb->prepare( "SELECT b, c, v, t FROM myTableName WHERE t like %s", $search_text), ARRAY_A );
//output the HTML which will be consumed by $.html()
?><div>You searched for <?php echo $search_text; ?> and we found... <?php
foreach ($result as $row) {
echo $row->t;
}
?></div><?php
// stop doing stuff
die();
}
add_action( \'wp_ajax_search_cv\', \'search_cv\' );
add_action( \'wp_ajax_nopriv_search_cv\', \'search_cv\' );
我怀疑这个错误是在我使用$wpdp->prepare或SQL查询时出现的,但我不知道那里会出什么问题。