I've got a simple PHP script which queries a mysql database for basic user info based on the data fetched from an HTML form.
<?php
$age = $_POST['age'];
$gender = $_POST['gender'];
$dbc = mysqli_connect('localhost', 'root', 'abc123', 'mydb')
$query = "SELECT * FROM users WHERE AGE='$age' AND GENDER='$gender'";
$result = mysqli_query($dbc, $query) or die('Querying the db failed');
mysqli_close($dbc);
?>
The problem is that the user doesn't always have to pick a gender or age and as a result the query doesn't always succeed. In other words I'm looking for something like this:
//(In pseudocode)
if (only $age exists) then:
$query = "SELECT * FROM users WHERE AGE='$age'
if (only $gender exists) then:
$query = "SELECT * FROM users WHERE GENDER='$gender'
if (both $age and $gender exist) then:
$query = "SELECT * FROM users WHERE AGE='$age' AND GENDER='$gender'";
otherwise:
$query = "SELECT * FROM users"
How should I do this? (in the actual script there are way more variables than just age and gender).
Dynamically build your list of placeholders and values:
$opts = array();
$values = array();
if (isset($_POST['age']) && (strlen($_POST['age']) > 0)) {
$opts[] = 'AGE = ?';
$values[] = $_POST['age'];
}
if (isset($_POST .... etc...) {
$opts[] = 'somefield = ?';
$values[] = 'value for this field';
}
etc...
$sql = "SELECT ..."; // basic query, WITHOUT where clause
if (count($opts) > 0) {
$sql .= ' WHERE ' . implode(',', $opts); // add in dynamic where options
}
$stmt = $mysqli->prepare($sql);
$result = $stmt->execute($values); // pass in the values for the ? placeholders
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.