Skip to content

Instantly share code, notes, and snippets.

@smwhr
Last active October 25, 2018 08:44
Show Gist options
  • Select an option

  • Save smwhr/e83cc5e6a67513a8e09ac525754faf8b to your computer and use it in GitHub Desktop.

Select an option

Save smwhr/e83cc5e6a67513a8e09ac525754faf8b to your computer and use it in GitHub Desktop.
SQL Query Builder v1
<?php
// spoiler !
abstract class SQLQuery{}
$sql = "SELECT * FROM user "
. " WHERE sex = :sex "
. " AND age < :age"
;
$parameters = [
"sex" => "f",
"age" => "50"
];
$columns = ["sex", "age", "height", "weight"];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Form</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row">
<div class="col">
<form method="POST">
<?php foreach($columns as $col):?>
<div class="form-row">
<div class="col">
<input type="checkbox" name="<?php echo $col?>_check">
<select name="<?php echo $col?>_operator">
<option>=</option>
<option><</option>
<option>></option>
<option><=</option>
<option>>=</option>
</select>
<input type="text"
name="<?php echo $col?>_value"
placeholder="<?php echo $col?>">
</div>
</div>
<?php endforeach;?>
<div class="form-row">
<div class="col">
<label>Sort by</label>
<select name="<?php echo $col?>_operator">
<option>No</option>
<?php foreach($columns as $col):?>
<option value="<?php echo $col;?>"><?php echo $col;?></option>
<?php endforeach;?>
</select>
</div>
</div>
<div class="form-row">
<div class="col">
<input type="submit" value="Search" class="btn btn-primary">
</form>
</div>
</div>
</form>
</div>
</div>
<p>
<strong>Consigne</strong>:
<ul>
<li>Si des cases sont cochées : on ne SELECT que ces colonnes</li>
<li>Si aucune case n'est cochée : on SELECT *</li>
<li>Si un champs est rempli : on WHERE avec l'opérateur et la valeur</li>
<li>Si un tri est sélectionné : on ORDER BY la colonne</li>
<li>Afficher la requête générée correspondante ci-dessous</li>
</ul>
</p>
<div class="alert alert-dark" role="alert">
<?php echo $sql;?>
</div>
<div class="alert alert-dark" role="alert">
<?php print_r($parameters);?>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment