M
M
MRcracker2020-04-14 11:30:18
PHP
MRcracker, 2020-04-14 11:30:18

How to check if a field is empty?

How to make a check if the field is empty, then it is not taken into account in the search?

<form action="index.php" method="POST" enctype="multipart/form-data">
    <p>имя</p><input type="text" name="name_form"><br>
    <p>возраст</p><input type="text" name="age_form"><br>
    <input type="submit" name="submit">
  </form>

$name_form = $_POST['name_form'];
$age_form = $_POST['age_form'];
$name = "SELECT * FROM users WHERE name = $name_form AND age = $age_form";
$result2 = mysqli_query($conn, $name);

$a = array();

if(mysqli_num_rows($result2) > 0 ) {
  
  while($row = mysqli_fetch_assoc($result2)) {
    $a[] = $row;
  }
} else {
  echo "0 results";
}

print_r($a);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FanatPHP, 2020-04-14
@MRcracker

Considering your previous question, you are unlikely to master it, but in general, the search for optional conditions is done like this :

$conditions = [];
$parameters = [];

// conditional statements
if (!empty($_GET['name']))
{
    // here we are using LIKE with wildcard search
    // use it ONLY if really need it
    $conditions[] = 'name LIKE ?';
    $parameters[] = '%'.$_GET['name']."%";
}

if (!empty($_GET['age']))
{
    // here we are using equality
    $conditions[] = 'age = ?';
    $parameters[] = $_GET['age'];
}

$sql = "SELECT * FROM users";

// a smart code to add all conditions, if any
if ($conditions)
{
    $sql .= " WHERE ".implode(" AND ", $conditions);
}

// the usual prepare/bind/execute/fetch routine
$stmt = $mysqli->prepare($sql);
$stmt->bind_param(str_repeat("s", count($parameters)), ...$parameters);
$stmt->execute();
$b = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
if($b) {
    print_r($b);
} else {
  echo "0 results";
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question