如果用户搜索我没有编写规则的内容,我想显示错误消息。这就是我的意思。
用户将拥有一个带有提交按钮的搜索栏。他会输入一个单词并点击提交。 我已经为四个特定的单词写了规则。他们为这个词分配一个值。
<?php
$search = $_POST['search'];
$search ['A'] = "32";
$search ['B'] = "30";
$search ['C'] = "34";
$search ['D'] = "53";
if ($_POST['search'] == A)
{print 'A has a value of ' . $search['A'] . ' dollars.';}
等......为B,C和D编写了类似的规则。
现在我需要的代码会在用户搜索除A,B,C或D以外的任何内容时显示错误消息。我编写了以下代码行,但它不起作用。它每次都显示消息,即使用户搜索A B C或D。
if ($search != 'A' or 'B' or 'C' or 'D')
{print $_POST['search'] . ' was not found in our database.';}
如果用户搜索不是A B C或D的任何内容,我想要一行显示消息的代码。
答案 0 :(得分:2)
试试这个
if ($search != 'A' && $search != 'B' && $search != 'C' && $search != 'D')
答案 1 :(得分:2)
我所知道的最佳方式是:
switch ($_POST['search']) {
case 32:
//do something
break;
case 30:
//do something
break;
case 34:
//do something
break;
case 53:
//do something
break;
default:
//They enetered something else, do something
}
或者你可以这样做:
$values = array('A' => 32, 'B' => 30, 'C' => 34, 'D' => 53);
然后:
if (!in_array($_POST['search'], $values) {
// they entered something else
} else {
switch ($_POST['search']) {
case 32: //do something
case 30: //do something else
ETC...
}
}
答案 2 :(得分:0)
也许你可以用switch语句尝试这样的东西:
$search = $_POST['search'];
$num = 0;
switch ($search) {
case 'A':
$num = 32;
break;
case 'B':
$num = 30;
break;
case 'C':
$num = 34;
break;
case 'D':
$num = 53;
break;
default:
$num = 0;
}
if ($num) {
echo 'A has a value of ' . $num . ' dollars.';
} else {
echo $_POST['search'] . ' was not found in our database.';
}
答案 3 :(得分:0)
您可以在此轻松使用jquery ajax / post。 例如:你的jquery代码:
("#sub_btn").click(function(){
var url = 'http://localhost/example/test';// ur method url
var search_str = $("#seach_txt").val(); // seach text box id
if(search_str == '' || search_str == 'undefined' )
{
$("#msg").html("Please enter value "); //
}else{
$.post(url,{data:search_str},function(responses){
$("#msg").html(responses); //div with id msg
});
}
});
//ur php code
function test(){
$search ['A'] = "32";
$search ['B'] = "30";
$search ['C'] = "34";
$search ['D'] = "53";
if( $_POST['data'] == 'A' || $_POST['data'] == 'B' || $_POST['data'] == 'C' || $_POST['data'] == 'D' ){
if(array_key_exists($_POST['data'],$search)){
echo $_POST['data'].' has a value of ' . $search['.$_POST['data'].'] . ' dollars.';exit;
}else{
echo $_POST['data'].' not found in our database';exit;
}
}
}
//ur html
<div id="msg"></div>
<input type="text" id="search_txt" />
<input type="button" id ="sub_btn" value="Submit">
希望这对你有用!! 谢谢。