search
HomeBackend DevelopmentPHP TutorialPHP+Mysql+jQuery查询和列表框选择操作实例讲解_PHP

本文讲解如何通过ajax查询mysql数据,并将返回的数据显示在待选列表中,再通过选择最终将选项加入到已选区,可以用在许多后台管理系统中。本文列表框的操作依赖jquery插件。

HTML

<form id="sel_form" action="post.php" method="post"> 
  <p><input type="text" name="keys" id="keys" value="输入姓名或手机号码" onclick="this.value=''" /> 
  <input type="button" id="searchOption" value="搜索" /> <span id="msg_ser"></span></p> 
  <div id="sel"> 
  <select name="liOption[]" id='liOption' multiple='multiple' size='8'> 
  </select> 
  </div> 
  <input type="submit" value="提 交" /> 
</form> 

说明,HTML内容是一个表单,里面放置有一个查询输入框,和一个列表框,以及相关按钮。

MYSQL数据表结构

CREATE TABLE IF NOT EXISTS `t_mult` ( 
 `id` int(11) NOT NULL auto_increment, 
 `username` varchar(32) NOT NULL, 
 `phone` varchar(20) NOT NULL, 
 PRIMARY KEY (`id`) 
) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

表t_mult是一张联系人资料表,包括姓名和手机号码字段。

CSS

<link rel="stylesheet" type="text/css" href="jquery.multiselect2side.css" /> 

本例中只加载了Multiselect插件所需的样式文件,其他CSS大家可以自行设计。
JAVASCRIPT
首先需要引用本例所需的两个js文件。

 
 
<link rel="stylesheet" type="text/css" href="jquery.multiselect2side.css" /> 

接着我们来调用Multiselect插件。

$("#liOption").multiselect2side({ 
  selectedPosition: 'right', 
  moveOptions: false, 
  labelsx: '待选区', 
  labeldx: '已选区' 
}); 

然后我们来写搜索按钮进行Ajax查询数据的操作。

$("#searchOption").click(function(){ 
  var keys=$("#keys").val(); 
  $.ajax({ 
     type: "POST", 
     url: "action.php", 
     data: "title="+keys, 
     success: function(msg){ 
      if(msg==1){ 
        $("#msg_ser").show().html("没有记录!"); 
      }else{ 
        $("#liOptionms2side__sx").html(msg); 
        $("#msg_ser").html(""); 
      } 
     } 
  }); 
  $("#msg_ser").ajaxSend(function(event, request, settings){ 
    $(this).html(""); 
  }); 
}); 

说明,当点击搜索按钮时,进行的是Ajax异步操作,JAVASCRIPT将获取的搜索框的输入值,以POST方式传递给后台程序action.php处理,处理后,返回不同的结果给JAVASCRIPT,如果返回1,HTML页面会提示“没有记录”,反之,则将结果输出给左边列表框(待选区):liOptionms2side__sx。注意关键的地方到了,为什么列表框不是XHTML离的liOption,而变成了liOptionms2side__sx了呢?这个要从Multiselect插件说起,Multiselect插件其实就是将一个列表框装换成左右两个列表框,已供相关操作,通过查看其插件代码不难发现,左边的列表框名为:liOptionms2side__sx,右边列表框(已选区)名为:liOptionms2side__dx,后面会用到。

PHP

首先来看action.php的处理。
第一步是连接数据库。

$conn=mysql_connect("localhost","root",""); 
mysql_select_db("demo",$conn); 
mysql_query("SET names UTF8"); 

第二步读取数据,并输出。通过检测搜索框传来的值,构造不同的SQL语句,并将数据返回输出,代码如下:

$keys=trim($_POST['title']); 
$keys=mysql_real_escape_string($keys,$conn); 
if(!empty($keys)){ 
   $sql="select * from t_mult where username like '%$keys%' or phone='$keys'"; 
}else{ 
   $sql="select * from t_mult"; 
} 
$query=mysql_query($sql); 
$count=mysql_num_rows($query); 
if($count>0){ 
  while($row=mysql_fetch_array($query)){ 
    $str.="<option value='".$row['id']."'>".$row['username']."-".$row['phone']."</option>"; 
  } 
  echo $str; 
}else{ 
  echo "1"; 
} 

最后还有一个提交操作,后台post.php程序来获取最终提交的项的值。

$selID=$_POST['liOptionms2side__dx']; 
if(!empty($selID)){ 
  $str=implode(",",$selID); 
  echo $str; 
}else{ 
  echo "没有选择任何项目!"; 
} 

注意,我们获取的是右边列表框liOptionms2side__dx的值,而不是liOption的值。
一个查询、操作的例子实现了,但是还有一点点瑕疵,在待选区往已选区添加项目时,如何判断控制已经添加过的项目不能重复添加,这个就留给大家思考吧,试一试有什么好的解决方式。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools