PHP搜索中的表单字段为空

时间:2016-11-04 11:09:55

标签: php html sql forms prepared-statement

我有一个带有文本框和组合框的html表单。

  • 如果我在文本框上写一些内容,则会过滤搜索。
  • 如果我在文本框上写东西并在组合框中选择一个项目,那么 搜索已过滤。
  • 如果我将文本框和组合框留空,搜索会带给我所有结果。

但是,

  • 如果我在文本框中留空,并在组合框中选择一个项目,则搜索将获取所有结果(而不仅仅是组合框的选定项目)

我想要,如果所有元素都为空,搜索会返回所有结果。但是如果tetxbox是空的而其他人被选中,那么不要把我带回来。

index.html (仅限<form>

<form action="index.php" method="post"> 
<input type="text" name="input" placeholder="Ricerca Ordini"> <br><br>
<label for="selectmenu">Tipo:</label>
<select id="selectmenu" name="tipo">
    <option>C1</option>
    <option>CR</option>
    <option>F1</option>
    <option>FP</option>
    <option>FPE</option>
    <option selected="selected">All Type</option>
</select>
<label for="spinner">ID:</label>
<input id="spinner" name="id"> <br><br>
<label for="from">From</label>
<input type="text" id="from" name="from">
<label for="to">to</label>
<input type="text" id="to" name="to"> <br><br>
<input type="submit" name="search">
</form>

index.php (仅限重要部分)

<?php
define ('DBNAME',"./DinamicoWeb.mdb"); // Definisce il nome del database
define ('DBTBL',"Ordini"); // Definisce il nome della tabella
define ('PKNAME',"Id Ord"); // Definisce il nome della chiave primaria
define ('PKCOL',0); // Definisce la posizione della chiave primaria
define ('LINKPK',true); // Abilita i link alla PK per modifica-cancella

$con = new COM("ADODB.Connection");
$conStr = "DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=".
            realpath(DBNAME).";";
$con->open($conStr);

$input=$_POST['input'];
$id=$_POST['id'];
$tipo=$_POST['tipo'];
$numero=$_POST['numero'];


$sql="SELECT [Id Ord] AS [ID], [Tipo Ord] AS [Tipo], [N Ord] AS [Numero], [Data Ord] AS [Data], [Ragione Sociale], [Indirizzo], [TotImp] AS [IMPORTO TOTALE], [TotIva] AS [IMPORTO IVA] FROM [Ordini] WHERE [Indirizzo] LIKE '%$input%' OR [Ragione Sociale] LIKE '%$input%' OR [Id Ord] LIKE '$id' OR [Tipo Ord] LIKE '$tipo' OR [N Ord] LIKE '$numero'";

$rs = $con->execute($sql);


if($rs === false) {
  trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $con->ErrorMsg(), E_USER_ERROR);
} else {
  $rows_returned = $rs->RecordCount();
}

$numFields = $rs->Fields->count;

// Print Table...

Index.html的片段

&#13;
&#13;
<!doctype html>
<html lang="it">
<head>
<meta charset="utf-8">
<title>Ricerca Ordini</title>
<link href="jquery-ui.css" rel="stylesheet">
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    var dateFormat = "mm/dd/yy",
      from = $( "#from" )
        .datepicker({
          defaultDate: "+1w",
          changeMonth: true,
          changeYear: true,
          numberOfMonths: 1
        })
        .on( "change", function() {
          to.datepicker( "option", "minDate", getDate( this ) );
        }),
      to = $( "#to" ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        changeYear: true,
        numberOfMonths: 1
      })
      .on( "change", function() {
        from.datepicker( "option", "maxDate", getDate( this ) );
      });
 
    function getDate( element ) {
      var date;
      try {
        date = $.datepicker.parseDate( dateFormat, element.value );
      } catch( error ) {
        date = null;
      }
 
      return date;
    }
  } );
  </script>
	<style>
	body{
		font-family: "Trebuchet MS", sans-serif;
		margin: 50px;
	}
	.demoHeaders {
		margin-top: 2em;
	}
	#dialog-link {
		padding: .4em 1em .4em 20px;
		text-decoration: none;
		position: relative;
	}
	#dialog-link span.ui-icon {
		margin: 0 5px 0 0;
		position: absolute;
		left: .2em;
		top: 50%;
		margin-top: -8px;
	}
	#icons {
		margin: 0;
		padding: 0;
	}
	#icons li {
		margin: 2px;
		position: relative;
		padding: 4px 0;
		cursor: pointer;
		float: left;
		list-style: none;
	}
	#icons span.ui-icon {
		float: left;
		margin: 0 4px;
	}
	.fakewindowcontain .ui-widget-overlay {
		position: absolute;
	}
	select {
		width: 200px;
	}
	</style>
	
</head>

<body>
<h1>Ricerca Ordini</h1>
<form action="index.php" method="post"> 
<input type="text" name="input" placeholder="Ricerca Ordini"> <br><br>
<label for="selectmenu">Tipo:</label>
<select id="selectmenu" name="tipo">
	<option>C1</option>
	<option>CR</option>
	<option>F1</option>
	<option>FP</option>
	<option>FPE</option>
	<option selected="selected">All Type</option>
</select>
<label for="spinner">ID:</label>
<input id="spinner" name="id"> <br><br>
<label for="from">From</label>
<input type="text" id="from" name="from">
<label for="to">to</label>
<input type="text" id="to" name="to"> <br><br>
<input type="submit" name="search">
</form>

<script src="external/jquery/jquery.js"></script>
<script src="jquery-ui.js"></script>
<script>

$( "#accordion" ).accordion();



var availableTags = [
	"ActionScript",
	"AppleScript",
	"Asp",
	"BASIC",
	"C",
	"C++",
	"Clojure",
	"COBOL",
	"ColdFusion",
	"Erlang",
	"Fortran",
	"Groovy",
	"Haskell",
	"Java",
	"JavaScript",
	"Lisp",
	"Perl",
	"PHP",
	"Python",
	"Ruby",
	"Scala",
	"Scheme"
];
$( "#autocomplete" ).autocomplete({
	source: availableTags
});



$( "#button" ).button();
$( "#button-icon" ).button({
	icon: "ui-icon-gear",
	showLabel: false
});



$( "#radioset" ).buttonset();



$( "#controlgroup" ).controlgroup();



$( "#tabs" ).tabs();



$( "#dialog" ).dialog({
	autoOpen: false,
	width: 400,
	buttons: [
		{
			text: "Ok",
			click: function() {
				$( this ).dialog( "close" );
			}
		},
		{
			text: "Cancel",
			click: function() {
				$( this ).dialog( "close" );
			}
		}
	]
});

// Link to open the dialog
$( "#dialog-link" ).click(function( event ) {
	$( "#dialog" ).dialog( "open" );
	event.preventDefault();
});



$( "#datepicker" ).datepicker({
	inline: true
});



$( "#slider" ).slider({
	range: true,
	values: [ 17, 67 ]
});



$( "#progressbar" ).progressbar({
	value: 20
});



$( "#spinner" ).spinner();



$( "#menu" ).menu();



$( "#tooltip" ).tooltip();



$( "#selectmenu" ).selectmenu();


// Hover states on the static widgets
$( "#dialog-link, #icons li" ).hover(
	function() {
		$( this ).addClass( "ui-state-hover" );
	},
	function() {
		$( this ).removeClass( "ui-state-hover" );
	}
);
</script>
</body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

是的,您可以按如下方式检查空白值:

if(!strlen($_POST['search']) || $_POST['search'] == ''){
 //use query without where clause
}else{
 //use query with where clause
}

答案 1 :(得分:1)

WHERE [Indirizzo] LIKE '%$input%' OR [Ragione Sociale] LIKE '%$input%' 为空字符串时

if (empty($input)) {
    // query without [Indirizzo] LIKE '%$input%' OR [Ragione Sociale] LIKE '%$input%'
} else {
    // query with [Indirizzo] LIKE '%$input%' OR [Ragione Sociale] LIKE '%$input%'
}

表示&#34;我想选择所有行&#34;。因此,首先检查它是否为空,如果它不符合标准,否则将其删除。

package learn;

import java.awt.event.*;
import javax.swing.*;  
import javax.swing.JOptionPane;
import javax.swing.JFrame;
import java.sql.*;
import javax.swing.JPanel;
import java.awt.BorderLayout;


public class TestGUI3 extends JFrame implements ActionListener
{  
    JRadioButton rb1, rb2, rb3;
    JFrame f;  
    JButton b;
    JPanel myFirstPanel;
    public TestGUI3()
    {  
        f = new JFrame("Welcome to Ballon d'or , created by Darren Estcourt");  
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        myFirstPanel = new JPanel();
        f.add(myFirstPanel);
        rb1 = new JRadioButton("Start New Game");  
        rb2 = new JRadioButton("Load Game");
        rb3 = new JRadioButton("Quit");

        myFirstPanel.add(rb1);
        myFirstPanel.add(rb2);
        myFirstPanel.add(rb3);

        ButtonGroup bg=new ButtonGroup();  
        bg.add(rb1);
        bg.add(rb2);
        bg.add(rb3);  

        b = new JButton("OK");
        myFirstPanel.add(b);

        b.addActionListener(this);





        f.setLayout(new BorderLayout());  
         f.pack();
        f.setVisible(true);  
    }  
          @Override public void actionPerformed(ActionEvent e)
            {  
                if(rb1.isSelected())
                {
                    f.dispose();


                  ManagerName test = new ManagerName();
                    test.getFrame().setVisible(true);

                }  
                if(rb2.isSelected())
                {
                    JOptionPane.showMessageDialog(f,"Load Game");  
                } 
                if(rb3.isSelected())
                {
                    System.exit(0);
                }  

            }

            public static void main(String[] args) 
            {  
                try
                {
                    String myDriver = "org.gjt.mm.mysql.Driver";
                    String myUrl = "jdbc:mysql://localhost:3306/ballondor?autoReconnect=true&useSSL=false";
                    Class.forName(myDriver);
                    Connection conn = DriverManager.getConnection(myUrl, "root", "Lucia290907");

                    String query = "SELECT * FROM clubInfo";

                    Statement st = conn.createStatement();

                    ResultSet rs = st.executeQuery(query);

                    while (rs.next())
                        {
                            int TeamID = rs.getInt("TeamID");
                            String TeamName = rs.getString("TeamName");
                            // print the results
                            System.out.format("%s, \n",  TeamName);
                        } // end while loop

                                    st.close();
                } // end try
    catch (Exception e)
    {
      System.err.println("Got an exception! ");
      System.err.println(e.getMessage());
    }

              SwingUtilities.invokeLater(new Runnable() 
              {
                  public void run() 
                  {
                  TestGUI3 test = new TestGUI3();
                  test.setVisible(true); 

                  }
              });
            }



}