Is there a better way to do this? Thanks in advance.

	// SELECT age
	if ($_POST['age'] == 'Tender'){
		$sreq4 = "AND age BETWEEN 18 AND 21";
	} else if ($_POST['age'] == 'Tasty'){
		$sreq4 = "AND age BETWEEN 21 AND 30";
	} else if ($_POST['age'] == 'Prime'){
		$sreq4 = "AND age BETWEEN 30 AND 40";
	} else {
		$sreq4 = "AND age BETWEEN 40 AND 110";
	}
	/////////////

    You could also do this:

    $query = "SELECT name FROM my_table 
              WHERE cheese = 'cheddar' AND age BETWEEN ? AND ?";
    switch ($_POST['age']) {
        case 'Tender':
            $params = array(18, 20);
        case 'Tasty':
            $params = array(21, 29);
        case 'Prime':
            $params = array(30, 39);
        default:
            $params = array(40, 110);
    }
    $stmnt = $pdo->prepare($query);
    $stmnt->execute($params);
    
    // or
    $stmnt = mysqli_prepare($conn, $query);
    mysqli_stmt_bind_param($stmt, 'ii', $params[0], $params[1]);

    Reasons

    Your "age" parameters overlapped. "30" would match both "Tasty" and "Prime".

    The "if...elseif...else" and "switch...case" constructs are equivalent and mostly a matter of preference.

      Installer wrote:

      You could also do this:

      Provided you remember to put in the break statements 🙂

        Ha! 🙂 I thought that looked too clean, and didn't even realize why.

          You could pack that switch down tighter, too, by folding the relationship between 'age' and age into the data.

          $age_pairs = array(
              'Tender' => array(18,20),
          ...
          );
          if(isset($_POST['age']) && isset($age_pairs[$_POST['age']]))
          {
              $range = $age_pairs[$_POST['age']];
          }
          else
          {
              $range = array(40,110);
          }
          

          After that I guess the next step would be to turn that array into a database table and so move all this work into the query.

            6 days later

            thanks weedpacket - I appreciate the response. Works great

              Write a Reply...