sql checkbox and mulit select filtering - php

i'm having some problems filtering my users when a search is run.
It has to be possible to select more than one region and gender.
gender is checkboxes and region is a select multiple selector.
In my project all content is dynamic, but thats to much to show here.
the form:
<form action="" method="get">
<input type="checkbox" name="gender[]" value="1"> <!-- male -->
<input type="checkbox" name="gender[]" value="2"> <!-- female -->
<select name="region[]" multiple>
<option value="1">North</option>
<option value="2">East</option>
<option value="3">West</option>
<option value="4">South</option>
</select>
<input type="submit" name="submitSearch" value="Filter">
</form>
The filter function:
<?php
if(isset($_GET['submitSearch']){
user_filter($db);
}
function user_filter($db){
$gender = $_GET['gender'];
$region = $_GET['region'];
$sql = "SELECT name, region, img FROM users WHERE true $gender AND $region";
$stmt = $db->prepare($sql);
$stmt->execute();
$res = $stmt->fetchAll();
return $res;
}
?>
Not sure if i have do a loop with the arrays and there is a problem with WHERE true if nothing is set
hope somebody can help me
Thanks

Change your code like this
if(isset($_GET['submitSearch']){
user_filter($db);
}
function user_filter($db){
$gender = implode(",",$_GET['gender']); //Change array to comma separated string so easy to pass in mysql using IN keyword
$region = implode(",",$_GET['region']);
$sql = "SELECT name, region, img FROM users WHERE gender IN($gender) AND region IN ($region)";
$stmt = $db->prepare($sql);
$stmt->execute();
$res = $stmt->fetchAll();
return $res;
}
Updated code for conditions
function user_filter($db){
if(isset($_GET['gender']) && $_GET['gender'] !=''){
$gender = implode(",",$_GET['gender']); //Change array to comma separated string so easy to pass in mysql using IN keyword
}
if(isset($_GET['region']) && $_GET['region'] !=''){
$region = implode(",",$_GET['region']);
}
$genderSql = "";
$regionSql = "";
$where = "";
$sql = '';
$sql .="SELECT name, region, img FROM users";
if(isset($_GET['gender']) && $_GET['gender'] !=''){
$genderSql =" gender IN($gender)"; //Note Space at start
}
if(isset($_GET['region']) && $_GET['region'] !=''){
if(isset($_GET['gender']) && $_GET['gender'] !=''){
$regionSql =" AND region IN ($region)"; //Note Space at start
} else {
$regionSql =" region IN ($region)"; //Note Space at start
}
}
if((isset($_GET['gender']) && $_GET['gender'] !='') || (isset($_GET['region']) && $_GET['region'] !='')){
$where =" Where";
$sql .=$where.$genderSql.$regionSql;
}
$stmt = $db->prepare($sql);
$stmt->execute();
$res = $stmt->fetchAll();
return $res;
}

Related

Adding values into database with the use of primary and foreign keys

Im trying to add the chosen values from my drop down menu into my database by using primary and foreign keys. Im trying to figure out how when the customer selects the drop down box option, the VALUE is entered into sql, which is the same number as room table primary. Would i somehow post the drop down box select id = rooID? Can anyone please help me with this.
Below is my makeabookingphp code:
<!DOCTYPE HTML>
<html><head><title>Make a Booking</title> </head>
<body>
<?php
//function to clean input but not validate type and content
function cleanInput($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
//the data was sent using a formtherefore we use the $_POST instead of $_GET
//check if we are saving data first by checking if the submit button exists in the array
if (isset($_POST['submit']) and !empty($_POST['submit']) and ($_POST['submit'] == 'Book')) {
//if ($_SERVER["REQUEST_METHOD"] == "POST") { //alternative simpler POST test
include "config.php"; //load in any variables
$DBC = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);
//prepare a query and send it to the server
$query = 'SELECT room.roomID, room.roomname, room.roomtype, booking.bookingID, booking.roomID, booking.roomname
FROM room
INNER JOIN booking
ON room.roomID = booking.roomID';
if (mysqli_connect_errno()) {
echo "Error: Unable to connect to MySQL. ".mysqli_connect_error() ;
exit; //stop processing the page further
};
//validate incoming data - only the first field is done for you in this example - rest is up to you do
$error = 0; //clear our error flag
$msg = 'Error: ';
if (isset($_POST['roomname']) and !empty($_POST['roomname']) and is_string($_POST['roomname'])) {
$fn = cleanInput($_POST['roomname']);
$roomname = (strlen($fn)>50)?substr($fn,1,50):$fn;
//check length and clip if too big
//we would also do context checking here for contents, etc
} else {
$error++; //bump the error flag
$msg .= 'Invalid'; //append eror message
$roomname = '';
}
$roomname = cleanInput($_POST['roomname']);
$checkindate = cleanInput($_POST['checkindate']);
$checkoutdate = cleanInput($_POST['checkoutdate']);
$contactnumber = cleanInput($_POST['contactnumber']);
$bookingextras = cleanInput($_POST['bookingextras']);
//save the customer data if the error flag is still clear
if ($error == 0) {
$query1 = "INSERT INTO booking (roomname, checkindate, checkoutdate, contactnumber, bookingextras) VALUES (?,?,?,?,?)";
$stmt = mysqli_prepare($DBC,$query1); //prepare the query
mysqli_stmt_bind_param($stmt,'sssss', $roomname, $checkindate, $checkoutdate,$contactnumber,$bookingextras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>Booking saved</h2>";
} else {
echo "<h2>$msg</h2>".PHP_EOL;
}
mysqli_close($DBC); //close the connection once done
}
?>
<h1>Make A Booking</h1>
<h2><a href='menu.php'>[Return to the main page]</a></h2>
<form method = "post" action = "processbooking.php">
<p>
<label for = "rooID">Room: (name, type, beds): </label>
<select id = "rooID" name = "rooID" required>
<option name = "" value = "" disabled selected>Select</option>
<option name = "1" value = "1">Kellie, S, 5</option>
<option name = "2" value = "2">Herman, D, 2</option>
<option name = "3" value = "3">Scarlett, D, 2</option>
<option name = "4" value = "4">Jelani, S, 5</option>
<option name = "5" value = "5">Sonya, S, 4</option>
<option name = "6" value = "6">Miranda, S, 2</option>
<option name = "7" value = "7">Helen, S, 2</option>
<option name = "8" value = "8">Octavia, D, 3</option>
<option name = "9" value = "9">Bernard, D, 5</option>
<option name = "10" value = "10">Dacey, D, 1</option>
</select>
</p>
<p>
<label for="checkindate">Check in date: </label>
<input type="date" name="checkindate"required>
</p>
<p>
<label for="checkout">Check out date: </label>
<input type="date" name="checkoutdate"required>
</p>
<p>
<label for="contactnumber">Contact number: </label>
<input type="tel" name="contactnumber" required>
</p>
<p>
<label for="bookingextras">Booking extras: </label>
<input type="text" name="bookingextras" size="100" minlength="5" maxlength="200" required>
</p>
<input type="submit" name="submit" value="Book">
[Cancel]
</form>
</body>
</html>
Room table:
roomID (PK)
roomname
description
roomtype
beds
Booking table:
bookingID (PK)
roomname
checkindate
checkoutdate
contactnumber
bookingextras
roomID (FK)
I've rewritten your code - hope it helps
<?php
//function to clean input but not validate type and content
function cleanInput($data) {
return htmlspecialchars(stripslashes(trim($data)));
}
// STEP 1 -test if form has been submitted
if (isset($_POST['submit']) && ($_POST['submit'] == 'Book')) {
// STEP 2. process the inputs
// get inputs - clean or set a default if not supplied
$roomID = isset( $_POST['rooID'] ) ? cleanInput($_POST['rooID']) : -1;
$checkindate = isset( $_POST['checkindate'] ) ? cleanInput($_POST['checkindate']) : "";
$checkoutdate = isset( $_POST['checkoutdate'] ) ? cleanInput($_POST['checkoutdate']) : "";
$contactnumber = isset( $_POST['contactnumber'] ) ? cleanInput($_POST['contactnumber']) : "";
$bookingextras = isset( $_POST['bookingextras'] ) ? cleanInput($_POST['bookingextras']) : "";
// STEP 3 validate/clean the inputs (don't trust anything coming in)
// validate all the inputs according to business rules
$error = 0;
$errMsg = [];
if( roomID == -1 ) {
$error++;
$errMsg[] = "Room not selected";
}
// do all other inputs
// proceed if no errors
if( $error != 0 ) {
// STEP 4 connect to the database
// connect to the database
include "config.php"; //load in any variables
$DBC = mysqli_connect("127.0.0.1", DBUSER, DBPASSWORD, DBDATABASE);
if (mysqli_connect_errno()) {
echo "Error: Unable to connect to MySQL. ".mysqli_connect_error() ;
exit; //stop processing the page further
};
// STEP 5 check if the roomID is valid
// if roomID is valid then continue
$query = "SELECT roomID FROM roomTable WHERE roomID=".$roomID;
$result = $DBC->query( $query ); // ???? check the syntax of this line
if( $result ) { // something returned ???? check syntax
// STEP 5 update the relevant table(s)
$query1 = "INSERT INTO booking (roomID, checkindate, checkoutdate, contactnumber, bookingextras) VALUES (?,?,?,?,?)";
$stmt = mysqli_prepare($DBC,$query1); //prepare the query
mysqli_stmt_bind_param($stmt,'issss', $roomID, $checkindate, $checkoutdate,$contactnumber,$bookingextras);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo "<h2>Booking saved</h2>";
}
} else {
// STEP 3.1 show user messages of what went wrong
echo $errMsg;
}
mysqli_close($DBC); //close the connection once done
}
?>

Many values insertion from checkbox only last value is inserting in database

I need to insert many values from checkbox but only the last value is inserting to database.
HTML CODE:
<?php
$conn = mysqli_connect("localhost", "root", "", "fix_in_time");
$result = mysqli_query($conn, "SELECT * FROM `material` WHERE id > 0");
while($row = mysqli_fetch_assoc($result)):?>
<input type="checkbox" value="<?php echo $row['tipo'];?>" name="Tipo" id="Tipo"><label><?php echo $row['tipo'];?></label><br>
<?php endwhile;?>
There is the PHP CODE:
$Sala = mysqli_real_escape_string($conn, $_POST['Sala']);
$Descricao = mysqli_real_escape_string($conn, $_POST['Descricao']);
$Tipo = mysqli_real_escape_string($conn, $_POST['Tipo']);
$Data = date("d-m-Y H:i:s", strtotime('-1 hour'));
if(empty($_POST['Sala']) || empty($_POST['Descricao'])||
empty($_POST['Tipo'])){
echo"<script language='javascript' type='text/javascript'>alert('Por favor
preencha os campos!');window.location.href='../index.php';</script>";
exit();
}
if(isset($_POST['submit'])){
if (!empty($_POST['Tipo'])) {
foreach ((array)$Tipo as $Tipo) {
$query = "INSERT INTO `relatorios` (Data, Sala, Descricao, Tipo) VALUES ('$Data', '$Sala', '$Descricao', '$Tipo')";
mysqli_query($conn, $query);
}
}
}
In your html code change input tag to:
<input type="checkbox" value="<?php echo $row['tipo'];?>" name="Tipo[]">.
If you append tag name with [], then this post variable in php will be an array. I've removed tag id because it should be unique, not sure if you need it, but if you do, then make it unique.
And your php code should look something like this:
if(isset($_POST['submit'])) {
if (!empty($_POST['Tipo']) && is_array($_POST['Tipo'])) {
foreach ($_POST['Tipo'] as $Tipo) {
$TipoEscaped = mysqli_real_escape_string($conn, $Tipo);
$query = "INSERT INTO `relatorios` (Tipo) VALUES ('$TipoEscaped')";
$success = mysqli_query($conn, $query);
if (!$success) {
//handle mysql error
}
}
}
}

$_POST data from form being changed before entered into MySQL

So new here to stack exchange but here goes nothing. So when I send a form to my apache server my data is only showing up as ones and zeros. Using var_dump[_$POST]; shows all of my data is correct before passing to MySQL.
My html form:
<form method="POST" action="submit.php" class="subForm">
<input type="text" name = "item1" value="0">
<input type="text" name="item2" value="0">
<input type="text" name="item3" value="no">
<input type="text" name="item4" value="no">
<input type="text" name="item5" value="no">
<input type="text" name="item6" value="no">
<input type="submit" id = "form2">
</form>
my php:
$connect = mysqli_connect('*****','*****','*****','*****');
if(!$connect){
die('Could not Connect: ' . mysqli_error($connect));
}
$NoR = isset($_POST["item1"]);
$CC = isset($_POST["item2"]);
$SD = isset($_POST["item3"]);
$HD = isset($_POST["item4"]);
$pack1 = isset($_POST["item5"]);
$pack2 = isset($_POST["item6"]);
$sql = "INSERT INTO form_test (item_1,item_2,item_3,item_4,item_5,item_6) VALUES (".$NoR.",".$CC.",".$SD.",".$HD.",".$pack1.",".$pack2.")";
mysqli_query($connect, $sql);
mysqli_close($connect);
var_dump($_POST)
var_dumb shows all data input is correct but in the table itself everything shows as 1s and 0s. Any advice?
In php, isset will return a boolean value (true if it's set, false if not), and when you try to print a boolean in php, it will display as 1 or 0. I suggest using the ternary comparison in your code, it's shorter and more readable than having a ton of if statements:
$NoR = isset($_POST["item1"]) ? $_POST["item1"] : '';
$CC = isset($_POST["item2"]) ? $_POST["item2"] : '';
$SD = isset($_POST["item3"]) ? $_POST["item3"] : '';
$HD = isset($_POST["item4"]) ? $_POST["item4"] : '';
$pack1 = isset($_POST["item5"]) ? $_POST["item5"] : '';
$pack2 = isset($_POST["item6"]) ? $_POST["item6"] : '';
Add this in your HTML form
<input type="text" name="action" value="submit">
And PHP code will be
if (isset($_POST['action']) && ($_POST['action']) == 'submit') {
$NoR = mysqli_real_escape_string($_POST["item1"]);
$CC = mysqli_real_escape_string($_POST["item2"]);
$SD = mysqli_real_escape_string($_POST["item3"]);
$HD = mysqli_real_escape_string($_POST["item4"]);
$pack1 = mysqli_real_escape_string($_POST["item5"]);
$pack2 = mysqli_real_escape_string($_POST["item6"]);
$sql = "INSERT INTO form_test (item_1,item_2,item_3,item_4,item_5,item_6) VALUES (".$NoR.",".$CC.",".$SD.",".$HD.",".$pack1.",".$pack2.")";
mysqli_query($connect, $sql);
mysqli_close($connect);
//var_dump($_POST)
}
isset will only give you if value is set or not. 1 if set else 0.
Use
if(isset($_POST["item1"])){
$NoR = $_POST["item1"];`
}
Updated: I made code for you to make sude ISSET values only goto INSERT query!
$arrColumns = $arrValues = array();
foreach($_POST as $key=>$value){
$arrColumns[] = key($key);
$arrValues[] = $value;
}
if(is_array($arrValues)){
$sql = "INSERT INTO form_test (implode(',',$arrColumns))
VALUES(implode(',',$arrValues)";
mysqli_query($connect, $sql);
}
mysqli_close($connect);

Have 4 'ands' in a select statement

I have a search function on my website with 4 checkboxes. These are then pasted to the next page where I want to find all products which match the criteria of the check boxes.
As I have 4 check boxes I want to use 4 'ands' but I believe 3 is the max (?)
How can I get around this so it searches to see if all products are matched?
HTML Form
<div id = "search">
<form name = search action = "search.php" method = "POST">
<p class = "big"> Refine Menu </p>
<hr>
<input type = "text" name = "search" placeholder = "Search for an item" size = "12">
<input type = "submit" value = "Go">
<br><br>
<input type = "checkbox" name = "vegetarian"> Vegetarian
<br><input type = "checkbox" name = "vegan"> Vegan
<br><input type = "checkbox" name = "coeliac"> Coeliac
<br><input type = "checkbox" name = "nutFree"> Nut free
</form>
</div>
PHP
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = NULL;
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = NULL;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = NULL;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = NULL;
}
$sql = "SELECT * FROM products WHERE vegan = '$vegan' and nutFree = '$nutFree' and vegetarian = '$vegetarian' and coeliac = '$coeliac'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
I've tried a number of different thing but I don't know the correct syntax for the sql.
NOTE: In my database whether it meets the requierment on it is saved as either a 1 or 0 that is why I changed it from 'on' or 'off'
Rather than a large, unmaintainable chain of if statements, you might consider something similar to the following, which will dynamically build up your query depending on which of your required fields have been checked in your form:
<?php
$search_fields = array( 'vegetarian', 'vegan', 'nutFree', 'coeliac', ...);
$ands = array( '1' => '1');
foreach($search_fields as $req)
{
if(isset($_POST[$req]) && $_POST[$req] != '')
{
$ands[$req] = "$req = '1'";
}
}
$and_part = implode(" AND ", $ands);
$query = "select .... from ... WHERE $and_part ... ";
?>
I managed to solve my problem. I was mistaken when I posted the question because the reason I thought my sql statement wasn't working was because there were too many ands and I didn't see that rather my sql didn't do what I thought it should.
Here is what I changed it to or it has set values or the check boxes ticked but always the ones which aren't to be either or.
Thanks for everyone's help!
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = " ";
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = " " ;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = " " ;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = " ";
}
$sql = "SELECT * FROM products WHERE (vegan = '$vegan' or vegan = 1 xor 0) and (nutFree = '$nutFree' or nutFree = 1 xor 0) and (vegetarian = '$vegetarian' or vegetarian = 1 xor 0) and (coeliac = '$coeliac' or coeliac = 1 xor 0)";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
PHP's NULL have no significance when converted to a string (the SQL query), they will evaluate to empty and your query will look like nutFree = '' and vegetarian = '' and coeliac = ''.
If those fields are 0 in the database, you must set the variables to 0 then.
On a second case, if they are NULL in the database, you must change both your query and the way you define NULL here.
First, those string wrappers should go away. You don't need them for numbers anyway, those are supposed to wrap strings only:
$sql = "SELECT * FROM products WHERE vegan = $vegan and nutFree = $nutFree and vegetarian = $vegetarian and coeliac = $coeliac";
And then instead of setting the variables to NULL, you will set them to the string "NULL".
$nutFree = "NULL";
This will make NULL show on the SQL query as its expected to.

Only first entry in list enters mysql table PHP even though trim is used

I have this page of html
<html>
<body>
<form action="new_group.php" method="post">
<div>
<label for="group_name">Group Name: </label>
<input type="text" name="group_name" id="group_name" />
</div>
<div>
<label for="invites">Invite...</label>
<input type="text" name="invites" id="invites" />
</div>
<div>
<label for="description">Description: </label>
<textarea name="description" id="description"></textarea>
</div>
<div>
<input type="submit" value="Create" />
</div>
</form>
</body>
</html>
Which then has this PHP:
<?php
include "function_inc.php";
if(isset($_POST['group_name'], $_POST['description'], $_POST['invites'])){
$invites = explode(',', $_POST['invites']);
$user_id = $_SESSION['user_id']; //avoids issues with quotations (either invalid quotation for referring to PHP variable or repeated double quotes)
$result = mysqli_query($link, "SELECT `username` FROM `users` WHERE `user_id` = '$user_id'");
foreach($result as $resul){
foreach($resul as $resu){
$logged_in_username = $resu;
}}
if(in_array($logged_in_username, $invites)){
}else{
$invites[] = $logged_in_username;
}
foreach($invites as $invite) {
$invite = trim($invite);
echo $invite . '<br />';
$idres = mysqli_query($link, "SELECT `user_id` FROM `users` WHERE `username` = '$invite'");
if(mysqli_num_rows($idres) == 0) {
exit("1 or more of the users that you entered do(es) not exist!");
}
}
create_group($_POST['group_name'], $_POST['description'], $invites);
}
?>
and this is the create_group function:
function create_group($name, $description, $invites){
global $link;
$name = mysqli_real_escape_string($link, $name);
$description = mysqli_real_escape_string($link, $description);
$names = mysqli_query($link, "SELECT `group_name` FROM `groups` WHERE `group_name` = '$name'");
$descriptions = mysqli_query($link, "SELECT `group_description` FROM `groups` WHERE `group_description` = '$description'");
if(mysqli_num_rows($names) == 0 && mysqli_num_rows($descriptions) == 0) {
mysqli_query($link, "INSERT INTO `groups` (`group_name`, `group_description`) VALUES ('$name', '$description')");
} else {
echo 'Group with that name/description already exists.';
}
$result = mysqli_query($link, "SELECT `group_id` FROM `groups` WHERE `group_name` = '$name'");
foreach($result as $resul) {
foreach($resul as $resu) {
$group_id = $resu;
}
}
foreach($invites as $invite) {
$idres = mysqli_query($link, "SELECT `user_id` FROM `users` WHERE `username` = '$invite'");
foreach($idres as $idarr) {
foreach($idarr as $id) {
mysqli_query($link, "INSERT INTO `group_members` (`group_id`, `user_id`, `confirmed?`) VALUES ('$group_id', '$id', 0)");
}
}
}
echo 'Group created!';
}
What I am confused about is the following: if I create a group (for testing purposes) and include my (the current user logged on's) name, and have commas but no spaces in between, everything works fine. However, if I do the exact same thing, however I have spaces, only the first name in the array enters group_members. As you can see, there is a trim statement.
I have no idea why this is. Any help would be much appreciated as I am a beginner at PHP.
Thank you in advance
In the code:
foreach ($invites as $invite) {
$invite = trim($invite);
...
}
The variable $invite is separate from the array element. Assigning to that variable does not modify the contents of the array. You can fix this by using a reference:
foreach ($invites as &$invite) {
$invite = trim($invite);
...
}
The & prefix makes $invite a reference variable, i.e. an alias for the array element. Now, assigning to the variable updates the array element that it refers to.

Categories