Sam Black Sam Black - 2 years ago 108
SQL Question

Include and exclude a text in sql / php

Hi please help me with this
I dont know how to preform a search query to exclude a text from search .
I have 2 search fields .
include text1 /
exclude text 2 / &
search button

note : the second text field is optional

  1. I want a way to detect what fileld is entered with php and preform an action

  2. I dont know how to exclude something from sql query / PHP

Thank you !

Answer Source

Simple example

$link = mysqli_connect("localhost", "my_user", "my_password", "world");

$text1 = mysqli_real_escape_string($link, $_POST['text1']);
$sql = "SELECT * FROM mytable WHERE text1 = '$text1'";
$text2 = $_POST['text2'];
//modify sql only if text2 was filled out
if($text2) {
    $text2 = mysqli_real_escape_string($link, $text2);
    $sql .= " AND text2 = '$text2'";
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download