How to prepare a MySQL query using a variable length parameter list in PHP -
i've got simple php script queries mysql database basic user info based on data fetched html form.
<?php $age = $_post['age']; $gender = $_post['gender']; $dbc = mysqli_connect('localhost', 'root', 'abc123', 'mydb') $query = "select * users age='$age' , gender='$gender'"; $result = mysqli_query($dbc, $query) or die('querying db failed'); mysqli_close($dbc); ?>
the problem user doesn't have pick gender or age , result query doesn't succeed. in other words i'm looking this:
//(in pseudocode) if (only $age exists) then: $query = "select * users age='$age' if (only $gender exists) then: $query = "select * users gender='$gender' if (both $age , $gender exist) then: $query = "select * users age='$age' , gender='$gender'"; otherwise: $query = "select * users"
how should this? (in actual script there way more variables age , gender).
dynamically build list of placeholders , 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 field'; } etc... $sql = "select ..."; // basic query, without clause if (count($opts) > 0) { $sql .= ' ' . implode(',', $opts); // add in dynamic options } $stmt = $mysqli->prepare($sql); $result = $stmt->execute($values); // pass in values ? placeholders
Comments
Post a Comment