Link Dropdown List with HTML+PHP+MySQL - php

I want to know how I can link three dropdown lists together. I want to let user select the country, then select the state and then select the city. Actually I tried multiple methods but What I have done is as bellow:
<div class="row">
<div class="col-sm-4"><div class="form-group">
<label for="countries">Country</label>
<select class="form-control" id="countries">
<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "countries";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM countries";
$result = $conn->query($sql);
//echo "<select id='countries'>";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
//echo "</select>";
$conn->close();?>
</select>
</div></div>
<div class="col-sm-4"><div class="form-group">
<label for="countries">State</label>
<select class="form-control" id="states">
<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "countries";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($_POST['submit'] && $_POST['submit'] != 0)
{
$countries=$_POST['countries'];
}
//echo "Connected successfully";
$sql = "SELECT * FROM regions where country_id = $countries";
$result = $conn->query($sql);
//echo "<select id='states'>";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
//echo "</select>";
$conn->close();?>
</select>
</div></div>
</div>
What I need to do is to make three dropdown lists (2 of them are shown above) to let the users select country first, then the second dropdown shows the states/regions based on user selection and finally select city based on selected state.Please show me the solution to do this.

I had written the code for this sometime last year, what you need is to use ajax, have on change event.
Please not I had written my solution using PDO I know yours requires mysqli, but however I don't have much of a time to re write the whole
thing to mysqli
But I hope you will see the logic on how to do this and hopefully you will be able to convert it to mysqli by yourself with no hustle.
my index file
<script src="jquery.min.js"></script>
<?php require 'db_config.php';?>
<script type="text/javascript">
$('#country').on('change', function() {
var countryID = $(this).val();
if (countryID) {
$.ajax({
type: 'POST',
url: 'locations.php',
data: 'country_id=' + countryID,
success: function(html) {
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
} else {
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
$(this).remove('has-errors');
});
$('#state').on('change', function() {
var stateID = $(this).val();
if (stateID) {
$.ajax({
type: 'POST',
url: 'locations.php',
data: 'state=' + stateID,
success: function(html) {
$('#city').html(html);
}
});
} else {
$('#city').html('<option value="">Select city first</option>');
}
});
</script>
<form method="POST" action="" id="reg_form">
<select name="country" id="country" class="input">
<option value="0">Select country</option>
<?php
$stmt= $dbh->Prepare("SELECT countryID, countryName FROM countries ORDER BY countryName ASC");
$stmt->execute();
$results= $stmt->Fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
foreach($results as $row){
echo '<option value="'.$row['countryID'].'">'.$row['countryName'].'</option>';
}
}else{
echo '<option value="">country not available</option>';
}
?>
</select>
<select name="state" id="state" class="input">
<option value="">Select country first</option>
</select>
<select name="city" id="city" class="input">
<option value="">Select state first</option>
</select>
</form>
locations.php
<?php
/**
* Created by PhpStorm.
* User: Masivuye
* Date: 2016/12/19
* Time: 11:27 AM
*/
require 'db_config.php';
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
$sql=$dbh->prepare("SELECT DISTINCT states.stateID,states.stateName from states INNER JOIN countries ON states.countryID = ? ");
$sql->bindValue(1,$_POST['country_id']);
$sql->execute();
$results =$sql->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
echo '<option value="0">Select state</option>';
foreach($results as $row){
echo '<option value="'.$row['stateID'].'">'.$row['stateName'].'</option>';
}
}else{
echo '<option value="">state not available</option>';
}
}
if(isset($_POST["state"]) && !empty($_POST["state"])){
$sql=$dbh->prepare("SELECT DISTINCT cities.cityID,cities.cityName,cities.stateID from cities INNER JOIN states ON cities.stateID= ? ");
$sql->bindValue(1,$_POST['state']);
$sql->execute();
$results =$sql->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
echo '<option value="0">Select City</option>';
foreach($results as $row){
echo '<option value="'.$row['cityID'].'">'.$row['cityName'].'</option>';
}
}else{
echo '<option value="">city not available</option>';
}
}
?>
db_config.php
<?php
$servername = "localhost";
$username = "hidden";
$password = "hidden";
$dbname = "mytestDB";
try {
$dbh= new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Could not connect".$e->getMessage();
error_log($e);
}
?>
my tables
CREATE TABLE IF NOT EXISTS `states` (
`stateID` int(6) NOT NULL AUTO_INCREMENT,
`stateName` varchar(255) NOT NULL,
`countryID` int(6) NOT NULL,
PRIMARY KEY (`stateID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `states`
--
INSERT INTO `states` (`stateID`, `stateName`, `countryID`) VALUES
(3, 'Western Cape', 2),
(4, 'Eastern Cape', 1),
(5, 'North West', 2),
(6, 'Northen Cape', 2);
--
-- Table structure for table `cities`
--
CREATE TABLE IF NOT EXISTS `cities` (
`cityID` int(6) NOT NULL AUTO_INCREMENT,
`cityName` varchar(255) NOT NULL,
`stateID` int(6) NOT NULL,
PRIMARY KEY (`cityID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cities`
--
INSERT INTO `cities` (`cityID`, `cityName`, `stateID`) VALUES
(1, 'Cape Town', 3),
(2, 'East London', 4);
-- --------------------------------------------------------
--
-- Table structure for table `countries`
--
CREATE TABLE IF NOT EXISTS `countries` (
`countryID` int(6) NOT NULL AUTO_INCREMENT,
`countryName` varchar(255) NOT NULL,
PRIMARY KEY (`countryID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;
--
-- Dumping data for table `countries`
--
INSERT INTO `countries` (`countryID`, `countryName`) VALUES
(1, 'South Africa'),
(2, 'Zambia'),
(3, 'Zimbabwe '),
(4, 'Uganda'),
(5, 'USA'),
(6, 'Brazil'),
(7, 'India'),
(8, 'Austrilia'),
(9, 'Ghana');
-- --------------------------------------------------------
NB: use your own characterset on the tables, you may use utf-8
Hope this will point you to the correct direction, hoping also other SO users will help where I missed something.

You can achieve what you want a multiple ways, but you have to make many improvements on your code.
For eg. you could just make connection on top of your script rather than multiple times (wherever you need). Also you could fetch the data from database tables on top of your script like this.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM countries";
$result = $conn->query($sql);
$countries = $result->fetch_all(MYSQLI_ASSOC);
$sql = "SELECT * FROM regions";
$result = $conn->query($sql);
$regions = $result->fetch_all(MYSQLI_ASSOC);
?>
Then add your html codes below.
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="countries">Country</label>
<select class="form-control" id="countries" onchange="refreshPage(this)">
<option value=""> Select Country</option>
<?php foreach($countries as $country): ?>
<option value="<?= $country['id'] ?>" ><?= $country['name'] ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="regions">Region</label>
<select class="form-control" id="regions">
<option value=""> Select Region</option>
<?php foreach($regions as $region): ?>
<option value="<?= $region['id'] ?>"><?= $region['name'] ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
You want the countries and regions related, for which you can use javascript or even jQuery (if you want) to fetch regions separately. Or just refresh the page when country is selected, like. (Mind the refreshPage() Method on countries select box above. )
<script>
function refreshPage(object)
{
var country_id = object.options[object.selectedIndex].value;
if (country_id != '') {
window.location.href = '?country_id='+country_id;
}
}
</script>
Now you have to just take the country_id value from $_GET to filter regions. The complete code looks like this.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM countries";
$result = $conn->query($sql);
$countries = $result->fetch_all(MYSQLI_ASSOC);
$where = "";
if (isset($_GET['country_id']) && $_GET['country_id'] != '') {
$where = " WHERE country_id = '{$_GET['country_id']}'";
}
$sql = "SELECT * FROM regions {$where}";
$result = $conn->query($sql);
$regions = $result->fetch_all(MYSQLI_ASSOC);
?>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="countries">Country</label>
<select class="form-control" id="countries" onchange="refreshPage(this)">
<option value=""> Select Country</option>
<?php foreach($countries as $country): ?>
<option value="<?= $country['id'] ?>" <?php echo isset($_GET['country_id']) && $_GET['country_id'] == $country['id'] ? 'selected' : ''; ?> ><?= $country['name'] ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="regions">Region</label>
<select class="form-control" id="regions">
<option value=""> Select Region</option>
<?php foreach($regions as $region): ?>
<option value="<?= $region['id'] ?>"><?= $region['name'] ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
<script>
function refreshPage(object)
{
var country_id = object.options[object.selectedIndex].value;
if (country_id != '') {
window.location.href = '?country_id='+country_id;
}
}
</script>
The main problem with this code is that, it is not preventing any SQL injection and is vulnerable in many ways. You have to use PDO instead of mysqli and use prepared statement to filter the regions.

In this case you should use AJAX. Onchange (select) you can send a xmlhttprequest (JS) to a separate php file, which returns the data you need (for example as JSON), and insert it into your website with JS.
Example:
<script type="text/javascript">
function filtern()
{
region = document.getElementById("feld1").value;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if(xhr.readyState==4 && xhr.status==200)
{
filtered_region = JSON.parse(xhr.responseText);
document.getElementById("select1").innerHTML = "";
for(i=0;i<filtered_region.length;i++)
{
document.getElementById("select1").innerHTML += "<option>"+filtered_region[i]+"</option>";
}
}
}
xhr.open("GET","get_your_data.php?region="+region,true);
xhr.send();
}
</script>
<form>
<p>Feld1: <input type="text" name="feld1" id="feld1" onchange="filtern()" /></p>
<select name="select1" id="select1"></select>
</form>
get_your_data.php returns the data you want to display.

Related

Populating Second Dropdown Based on first dropdown from the database table without using javascript

I am trying to create a form for the admin of an e-commerce site and the admin should be able to create a category and add new products.
I have two tables in my database from where I want to populate the dropdown list. I want the second dropdown to populate as I select the first drop-down value but I have to do it without the submit button.
This is the code for the form with two drop-downs:-
<form method="post" action="add_category.php">
<h4>Choose the root level:</h4>
<select name="rootLevel">
<?php
$conn = mysqli_connect("localhost","root","","store")
or die("Error in Connection on add_category");
$query = "SELECT * FROM root_category";
$result = mysqli_query($conn,$query) or die("Query failed add_category");
$id=1;
//echo $id;
//echo "Hello";
while($row = mysqli_fetch_assoc($result)){
global $id;
//echo "<h1>$id</h1>";
$id = $row['id'];
echo "<option name='rootLevel' value=$id>".$row['Name']."</option>";
//echo "<option>$id</option>";
}
?>
</select>
<br><br>
<h4>Choose the Level 1 Category:</h4>
<select name="level1">
<?php
global $id;
//echo "<option>".$_POST['rootLevel']."</option>";
$query_level1 = "Select * from level1_category Where P_id = $id";
$result1 = mysqli_query($conn,$query_level1) or die("Query failed level 1");
while($row = mysqli_fetch_assoc($result1)){
$id1 = $row['P_id'];
echo "<option name='level1' value=$id1>".$row['Name']."</option>";
}
?>
</select>
I have successfully populated the first drop-down and now I want to fetch the $id in 'resultValue' without the submit button.
You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you
https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php
OR
https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "states.php",
data: { country : selectedCountry }
}).done(function(data){
$("#states").html(data);
});
});
});
</script>
</head>
<body>
<div class="form-group">
<label for="country" class="input__label">Country</label>
<select id="country" onchange="states(this.value);" name="country" class="country form-control login_text_field_bg input-style">
<option selected>Choose...</option>
<?php
$sql= $cnn->prepare("SELECT key_iso_code FROM country");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
?>
<option><?php echo $key_iso_code ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState" class="input__label">State/Province</label>
<select id="states" name="state" class="form-control input-style">
<option selected>Choose...</option>
</select>
</div>
</body>
<?php
include("PDOConnection.php");
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Display city dropdown based on country name
if($country !== 'Shoose...'){
$sql= $cnn->prepare("SELECT state.key_name FROM country INNER JOIN state ON country.key_id = state.key_country_id WHERE country.key_iso_code like '$country'");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
echo "<option>". $key_name . "</option>";
}
}
}
?>

Insert values into database from form with drop downs

I am trying to insert values input from the user in a form into my database.
I have 2 drop down lists for a blood test and then category. E.g user first selects drop down 1 'Thyroid' (Category) and then drop down 2 displays 'FT4,FT3 TSH' (blood test) etc and the user makes their selection.
Then they input the date and the value.
In my insert I need to insert into my database the user_id(established after login with session variables, bloodtest_id(from drop down 2), date, value.
I can't get my SQL query right for the insert in general and need some help please.
Drop down 2 (blood test) is in a seperate php file and I'm not sure how to tell the SQL query how to find that value to use either?
The addBlood.php is below. This is the page the form is on
<?php
session_start();
include('dbConnect.php');
$queryStr=("SELECT * FROM category");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<html>
<head>
<TITLE>Category and Test</TITLE>
<head>
<!-- Help for code to create dynamic drop downs -->
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
function getTest(val) {
$.ajax({
type: "POST",
url: "get_test.php",
data:'category_id='+val,
success: function(data){
$("#test-list").html(data);
}
});
}
function selectCategory(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
</head>
<body>
<div class="frmDronpDown">
<div class="row">
<label>Category:</label><br/>
<select name="category" id="category-list" class="demoInputBox" onChange="getTest(this.value);">
<option value="">Select Category</option>
<?php
foreach($results as $category) {
?>
<option value="<?php echo $category["category_id"]; ?>"><?php echo $category["category_name"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="row">
<form action="addBlood.php" method="post">
<label>Test:</label><br/>
<select name="test" id="test-list" class="demoInputBox">
<option value="">Select Test</option>
</select>
</div>
</div>
<label>Result:</label><input class="input" name="result" type="text"><br>
<label>Date:</label><input class="input" name="date" type="date"><br>
<input class="submit" name="submit" type="submit" value="Submit">
</form>
<?php
if(isset($_POST['submit'])){
//$currentBloodTest=$test["bloodtest_id"];
$currentUser=$_SESSION["currentUserID"];
$value = $_POST['result'];
$date = $_POST['date'];
//$query = $db->prepare("INSERT INTO results (user_id, bloodtest_id,date,value)values ($currentUser,$currentBloodTest, $date , $value)");
$dbParams = array();
$query->execute($dbParams);
echo "<br><br><span>Data Inserted successfully...!!</span>";
}
?>
</body>
</html>
Below is the getTest.php which gets all the blood tests.
<?php
include('dbConnect.php');
if(!empty($_POST["category_id"])) {
$queryStr=("SELECT * FROM bloodtests WHERE category_id = '" . $_POST["category_id"] . "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
?>
<option value="">Select Test</option>
<?php
foreach($results as $test) {
?>
<option value="<?php echo $test["bloodtest_id"]; ?>"><?php echo $test["test_name"]; ?></option>
<?php
}
}
?>
If this is where you are having some troubles, and are unsure how to proceed:
//$query = $db->prepare("INSERT INTO results (user_id, bloodtest_id,date,value)
// VALUES ($currentUser,$currentBloodTest, $date , $value)");
$dbParams = array();
$query->execute($dbParams);
Then this may help you out (you were very close):
$currentUser = $_SESSION["currentUserID"];
$currentBloodTest = $_POST['test']; // name of the 'select' element
$value = $_POST['result'];
$date = $_POST['date'];
$query = $db->prepare("INSERT INTO results (user_id, bloodtest_id, date, value)
VALUES (?, ?, ?, ?)");
$query->execute( array($currentUser, $currentBloodTest, $date, $value) );
Also, this part you have in the ajax lookup:
$queryStr=("SELECT * FROM bloodtests WHERE category_id = '" . $_POST["category_id"] . "'");
$dbParams=array();
// now send the query
$results = $db->prepare($queryStr);
$results->execute($dbParams);
Really should be written as:
$queryStr = "SELECT * FROM bloodtests WHERE category_id = ?";
$results = $db->prepare($queryStr);
$results->execute( array($_POST["category_id"]) );

Integrating dynamic dependent select box into WordPress

I want to add part search into a website powered by WordPress. I have currently achieved the function, but I have trouble of integrating it into WordPress. I tried several ways but the dynamic dependent select box still not working.
I followed this tutorial: Dynamic Dependent Select Box using jQuery, Ajax and PHP
Below are my code which works well outside WordPress.
index.php
<head>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="js/ajax-ps.js"></script>
</head>
<body>
<form class="select-boxes" action="ps-result.php" method="POST">
<?php
include('dbConfig.php');
$query = $db->query("SELECT * FROM ps_manufact WHERE status = 1 ORDER BY manufact_name ASC");
$rowCount = $query->num_rows;
?>
<select name="manufacturer" id="manufact" class="col-md-2 col-sm-2 col-xs-10" onchange="manufactText(this)">
<option value="">Select Manufacturer</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['manufact_id'].'">'.$row['manufact_name'].'</option>';
}
}else{
echo '<option value="">Manufacturer Not Available</option>';
}
?>
</select>
<input id="manufacturer_text" type="hidden" name="manufacturer_text" value=""/>
<script type="text/javascript">
function manufactText(ddl) {
document.getElementById('manufacturer_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="type" id="type" class="col-md-2 col-sm-2 col-xs-10" onchange="typeText(this)">
<option value="">Select Manufacturer First</option>
</select>
<input id="type_text" type="hidden" name="type_text" value=""/>
<script type="text/javascript">
function typeText(ddl) {
document.getElementById('type_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="year" id="year" class="col-md-2 col-sm-2 col-xs-10" onchange="yearText(this)">
<option value="">Select Type First</option>
</select>
<input id="year_text" type="hidden" name="year_text" value=""/>
<script type="text/javascript">
function yearText(ddl) {
document.getElementById('year_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<select name="model" id="model" class="col-md-2 col-sm-2 col-xs-10" onchange="modelText(this)">
<option value="">Select Year First</option>
</select>
<input id="model_text" type="hidden" name="model_text" value=""/>
<script type="text/javascript">
function modelText(ddl) {
document.getElementById('model_text').value = ddl.options[ddl.selectedIndex].text;
}
</script>
<input type="submit" name="search" id="search" class="col-md-2 col-sm-2 col-xs-10" value="Search">
</form>
</body>
ajax-ps.js
$(document).ready(function(){
$('#manufact').on('change',function(){
var manufactID = $(this).val();
if(manufactID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'manufact_id='+manufactID,
success:function(type_data){
$('#type').html(type_data);
$('#year').html('<option value="">Select Type First</option>');
}
});
}else{
$('#type').html('<option value="">Select Manufact First</option>');
$('#year').html('<option value="">Select Type First</option>');
}
});
$('#type').on('change',function(){
var typeID = $(this).val();
if(typeID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'type_id='+typeID,
success:function(year_data){
$('#year').html(year_data);
$('#model').html('<option value="">Select Year First</option>');
}
});
}else{
$('#year').html('<option value="">Select Type First</option>');
$('#model').html('<option value="">Select Year First</option>');
}
});
$('#year').on('change',function(){
var yearID = $(this).val();
if(yearID){
$.ajax({
cache: false,
type:'POST',
url:'ajax-data.php',
data:'year_id='+yearID,
success:function(model_data){
$('#model').html(model_data);
}
});
}else{
$('#model').html('<option value="">Select Year First</option>');
}
});
});
ajax-data.php
include('dbConfig.php');
if(isset($_POST["manufact_id"]) && !empty($_POST["manufact_id"])){
$query = $db->query("SELECT * FROM ps_type WHERE manufact_id = ".$_POST['manufact_id']." AND status = 1 ORDER BY type_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Type</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['type_id'].'">'.$row['type_name'].'</option>';
}
}else{
echo '<option value="">Type Not Available</option>';
}
}
if(isset($_POST["type_id"]) && !empty($_POST["type_id"])){
$query = $db->query("SELECT * FROM ps_year WHERE type_id = ".$_POST['type_id']." AND status = 1 ORDER BY year_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Year</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['year_id'].'">'.$row['year_name'].'</option>';
}
}else{
echo '<option value="">Year Not Available</option>';
}
}
if(isset($_POST["year_id"]) && !empty($_POST["year_id"])){
$query = $db->query("SELECT * FROM ps_model WHERE year_id = ".$_POST['year_id']." AND status = 1 ORDER BY model_name ASC");
$rowCount = $query->num_rows;
if($rowCount > 0){
echo '<option value="">Select Model</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['model_id'].'">'.$row['model_name'].'</option>';
}
}else{
echo '<option value="">Model Not Available</option>';
}
}
Now the problem is, when select the first box, the second one becomes empty, nothing is returned from the database:
Capture - After select the first box
Really appreicate Christos Lytras to help me solve the previous problem.
I have a new problem with action="ps-result.php" in the line <form class="select-boxes" action="ps-result.php" method="POST">.
ps-result.php
<?php
if (isset($_POST['search'])) {
$clauses = array();
if (isset($_POST['manufacturer_text']) && !empty($_POST['manufacturer_text'])) {
$clauses[] = "`manufacturer` = '{$_POST['manufacturer_text']}'";
}
if (isset($_POST['type_text']) && !empty($_POST['type_text'])) {
$clauses[] = "`type` = '{$_POST['type_text']}'";
}
if (isset($_POST['year_text']) && !empty($_POST['year_text'])) {
$clauses[] = "`year` = '{$_POST['year_text']}'";
}
if (isset($_POST['model_text']) && !empty($_POST['model_text'])) {
$clauses[] = "`model` = '{$_POST['model_text']}'";
}
$where = !empty( $clauses ) ? ' where '.implode(' and ',$clauses ) : '';
$sql = "SELECT * FROM `wp_products` ". $where;
$result = filterTable($sql);
}
else {
$sql = "SELECT * FROM `wp_products` WHERE `manufacturer`=''";
$result = filterTable($sql);
}
function filterTable($sql) {
$con = mysqli_connect("localhost", "root", "root", "i2235990_wp2");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$filter_Result = mysqli_query($con, $sql);
return $filter_Result;
}
?>
<?php get_header(); ?>
<div class="container">
...
</div>
<?php get_footer(); ?>
Now when I click Search, it returns
Fatal error: Call to undefined function get_header() in /Applications/MAMP/htdocs/wordpress/wp-content/themes/myTheme/inc/ps-result.php on line 42.
The proper way to do this, is to create a wordpress shortcode and then use that shortcode wherever you want, page or post, but if you want to create something more specific, then you should create a small wordpress plugin. I won't get into this, but it’s really not a big deal to create a simple wordpress plugin having such functionality. I’ll go through the steps on how you can have this working in wordpress with the files and the code you already have.
I assume you already have the tables of your example created. My tables are like this:
wp_citytours_dynsel_cities
wp_citytours_dynsel_states
wp_citytours_dynsel_countries
I have imported some data and I have all those tables filled with proper data. I can provide some sql files if you like, but I assume you already have your tables filled with the proper data for each table.
My test theme root directory is:
/wp-content/themes/citytours/
I have created the directory under my theme root directory and I have included all the code files there, so we have 3 files:
/wp-content/themes/citytours/dynsel/index-partial.php
<?php
//Include database configuration file
include('dbConfig.php');
//Get all country data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_countries WHERE status = 1 ORDER BY country_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="country" id="country">
<option value="">Select Country</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<select name="state" id="state">
<option value="">Select country first</option>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
</select>
<script type="text/javascript">
jQuery(function($) {
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>',
data:'country_id='+countryID,
success:function(html){
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
/wp-content/themes/citytours/dynsel/dbConfig.php
<?php
//db details
$dbHost = 'localhost';
$dbUsername = 'xxxx';
$dbPassword = 'xxxx';
$dbName = 'xxxx';
//Connect and select the database
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
?>
/wp-content/themes/citytours/dynsel/ajaxData.php
<?php
//Include database configuration file
include('dbConfig.php');
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get all state data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display states list
if($rowCount > 0){
echo '<option value="">Select state</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get all city data
$query = $db->query("SELECT * FROM wp_citytours_dynsel_cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//Display cities list
if($rowCount > 0){
echo '<option value="">Select city</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
As you can see, the index-partial.php now contains only needed code, without <body>, <head> and script files included. Wordpress already includes jQuery to the application for most themes, but you should always check that.
Now, you can add the functionality wherever you want, even at the theme index.php file, but always with caution. I have used theme's single post template file, which is single-post.php. I have included the example code, under the main post body inside a div. I just include the index-partial.php like this:
<div class="<?php echo esc_attr( $content_class ); ?>">
<div class="box_style_1">
...
</div><!-- end box_style_1 -->
<div class="box_style_1">
<?php include(__DIR__.'/dynsel/index-partial.php'); ?>
</div>
</div><!-- End col-md-9-->
I also have used the wordpress home_url function, to have a proper url rooted for the ajaxData.php file like this:
url:'<?php echo home_url('wp-content/themes/citytours/dynsel/ajaxData.php') ?>'
Now, if you have followed all these steps, then you should have your code example working at under each post. You can now included it wherever you want by using that line of code <?php include(__DIR__.'/dynsel/index-partial.php'); ?>.
Please let me know if that worked for you.

Creating a search function

I have multiple fields in my search form and my query works for individual fields. what i'm trying to achieve is
1- query should work if search is based on 1 field
2- query should work if search is based on multiple fields entry
my form
<form class="sidebar-search jumbro-search container list-inline center-block" method="get" action="search.php">
<div class="form-group col-md-2">
<input list="location" name="location" class="form-control" placeholder="Location">
<datalist id="location">
<?php
$loc="select * from locations";
$results=mysqli_query($dbc,$loc);
while($row_loc=mysqli_fetch_array($results)){
echo '<option value='.$row_loc['region'].'>'.$row_loc['region'].'</option>';
}
?>
</datalist>
</div>
<div class="form-group col-md-2">
<select class="form-control" name="category">
<option selected>Category</option>
<?php
$cat="select * from property_type order by type_name asc";
$results=mysqli_query($dbc,$cat);
while($row_cat=mysqli_fetch_array($results)){
echo '<option value='.$row_cat['type_name'].'>'.$row_cat['type_name'].'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-2">
<select class="form-control" name="status">
<option selected>Status</option>
<?php
$status="select * from property_status order by status_name asc";
$results=mysqli_query($dbc,$status);
while($row_status=mysqli_fetch_array($results)){
echo '<option value='.$row_status['status_name'].'>'.$row_status['status_name'].'</option>';
}
?>
</select>
</div>
<div class="form-group col-md-2">
<input type="text" name="price-max" value="999999999999" class="form-control" placeholder="Max Price">
</div>
<div class="form-group col-md-2">
<button class="btn btn-primary form-control">Search</button>
</div>
and my php script looks like this
// getting user data from search form
$location=$_GET['location'];
$category=$_GET['category'];
$status=$_GET['status'];
//scripts
if($location!="location" && $category!="category" && $status!="status"){
$query="select * from properties where `property_type` like '%$category%' && `location` like '%$location%' && `status` like '%$status%' ";
}
$query="select * from properties where `property_type` like '%$category%' or `location` like '%$location%' or `status` like '%$status%'";
$result=mysqli_query($dbc,$query);
if(mysqli_query($dbc,$query)) {
$num_rows=mysqli_num_rows($result);
} else {
echo 'Query failed';
}
$num_rows=mysqli_num_rows($result);
if($num_rows!=0){
echo '<h3 class="page-header text-center">'.$num_rows.' Match Found</h3>';
while ($row=mysqli_fetch_array($result)) {
<?php
}//end while
}else{
echo '<h3 class="page-header text-center">No Match Found, try adjusting your search criteria.</h3>';
include 'functions/latest-sc.php';
}
Well, okay, I have several ideas about what you should change in your code.
I strongly recommend you to separate representative logic (html and echoing variables) from functionality like defining variables and handling database queries. It will help you a lot in future.
You can use default option in your selects with empty value
<option value="">Select none</option>
It will simplify your code in checks:
Instead of:
if($location!="location" && $category!="category" && $status!="status")
Can use:
if($location && $category && $status)
Read about escaping
On your main question - you can create query by concatenation. I give you example and you can replace it with 'OR' or 'AND' for your needs:
$sql = 'SELECT * FROM properties WHERE ';
$scopes = [];
foreach([$location,$category,$status] as $column => $condition) {
if ($condition) {
$scopes[] = $column.' LIKE \'%.$condition.'%\'';
}
}
$scopes = implode(' AND ',$scopes);
$sql .= $scopes.';';
// ...do what you need
There is a lot more advices for coding but maybe you just present it like dead-simple example, so I skip it.
OK I think what you are asking is a SELECT based on multiple columns in a table. Below is a script from my application that selects records from a table that checks for a hometeam and an away team:-
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "localdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT hometeam FROM stats WHERE hometeam = 'Man City' AND awayteam = 'Sunderland'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['hometeam'];
}
} else {
echo "0 results";
}
$conn->close();
?>
This should work:
$data = [
'property_type' => 'category_value', //$_GET['location']
'category' => 'location_value', //$_GET['category']
'status' => 'status_value' //$_GET['status']
];
$select = "";
$params = 0;
foreach($data as $k => $v){
if($params > 0){
$select .= " or ";
}
//add some better conditions
if(strlen($v) > 0){
$select .= "`$k` LIKE %$v%";
$params++;
}
}
$query = "select * from properties where " . $select;
print_r($query);

php - Drop Down Executes Query On Post?

I've looked online and most drop down tutorials are for ratings e.g. matching the drop down value with a rating. I need to execute a query which corresponds to a number in the dropdown and the results to display once a user clicks submit, I don't want to use javascript. In my HTML :
<form action="" method="post" enctype="multipart/form-data" name="form1" id="genericForm">
<fieldset>
<p>Filter Rating</p>
<select name="value">
<option value="1">One Star</option>
<option value="2">Two Stars</option>
<option value="3">Three Stars</option>
<option value="4">Four Stars</option>
<option value="5">Five Stars</option>
</select>
</div>
<input type="submit" name="Submit" value="Submit"><br />
</form>
The php :
<?php
$Link = mysql_connect($Host, $User, $Password);
if($_POST['value'] == '1') {
// query to get all 1 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='1'";
}
elseif($_POST['value'] == '2') {
// query to get all 2 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='2'";
}
elseif($_POST['value'] == '3') {
// query to get all 3 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='3'";
}
elseif($_POST['value'] == '4') {
// query to get all 4 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='4'";
}
elseif($_POST['value'] == '5') {
// query to get all 5 star ratings
$query = "SELECT * FROM films WHERE genre='action' AND rating='5'";
}
WHILE($board = mysql_fetch_array($result)):
$title = $board['title'];
$studio = $board['studio'];
$language = $board['language'];
$certification = $board['certification'];
echo '
Title : '.$title.'<br />
Studio : '.$studio.'<br />
Language : '.$language.'<br />
Certification : '.$certification.'<br />
;
endwhile;
?>
Try it this way, assuming you're already connected and have selected DB and that you're using your entire code inside the same file, since you are using action=""; this denotes executing as "self".
You also are not executing mysql_query() which I have added below.
Be sure to change xxx below with your DB credentials and your_db to your database's name.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$Host = "xxx";
$User = "xxx";
$Password = "xxx";
$Link = mysql_connect($Host, $User, $Password);
$db_selected = mysql_select_db('your_db', $Link);
if (!$db_selected) {
die ('Can\'t use that DB : ' . mysql_error());
}
if(isset($_POST['Submit'])){
if($_POST['value'] == '1') {
// query to get all 1 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='1'");
}
elseif($_POST['value'] == '2') {
// query to get all 2 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='2'");
}
elseif($_POST['value'] == '3') {
// query to get all 3 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='3'");
}
elseif($_POST['value'] == '4') {
// query to get all 4 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='4'");
}
elseif($_POST['value'] == '5') {
// query to get all 5 star ratings
$query = mysql_query("SELECT * FROM films WHERE genre='action' AND rating='5'");
}
WHILE($board = mysql_fetch_array($query)){
$title = $board['title'];
$studio = $board['studio'];
$language = $board['language'];
$certification = $board['certification'];
echo '
Title : '.$title.'<br />
Studio : '.$studio.'<br />
Language : '.$language.'<br />
Certification : '.$certification.'<br />';
}
} // brace for if(isset($_POST['Submit']))
?>
</div>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="genericForm">
<fieldset>
<p>Filter Rating</p>
<select name="value">
<option value="1">One Star</option>
<option value="2">Two Stars</option>
<option value="3">Three Stars</option>
<option value="4">Four Stars</option>
<option value="5">Five Stars</option>
</select>
</div>
<input type="submit" name="Submit" value="Submit"><br />
</form>
Note:
This enctype="multipart/form-data" isn't required if it's not going to be used to upload files.
If im not mistaken this is what you want? you just need to loop through the row in the tables and fetch it.
<div class="form">
<?php
$Link = mysql_connect($Host, $User, $Password);
$Query = "select * from books where product = 'hannibal' AND book = '1'";
$result = mysql_query($Query);
while ($row = mysql_fetch_array($result)) {
$subject = $row['subject'];
$username = $row['username'];
$date = $row['date'];
$comments = $row['comments'];
?>
<h1>Subject : <?php echo $subject;?>
Posted by <?php echo $username;?> on <?php echo $date;?></h1><br />
<?php echo $comments;?>'; <br />
<?php
}
?>
</div>

Categories