How to store POST elements in an array - php

It is for a "recipes personal website", I am stuck with the Search function.
First let me tell you how is the database :
1 table categories : the type of recipe
Link for image
1 table ingredients : all the ingredients used in the recipes
Link for image
1 table recettes : all recipes stored with a column for their categories
Link for image
1 table ingredient_recette : to link all ingredients and quantity that composed a specific recipe
Link for image
Here I would like to make a page where I can search for recipes that contain for example 1 or 2 special ingredients, and in which category I would like to search. Link for search page image
This is the search.php I've done for the moment... (you can see it on codeshare.io)
How can I proceed to search recipes that contain only selected
ingredients ?
<?php
include("cnx.php");
include("functions.php");
// Query pour les catégories
$rq_cat = "SELECT * FROM categories ORDER BY id_cat";
$result_cat = $mysqli->query($rq_cat);
if(isset($_POST["Recherche"]) AND $_POST["Recherche"] == "Go")
{
if($_POST["cat_recette"] == "") // Si aucune catégorie sélectionnée
{
echo "Aucune catégorie ";
$rq_recettes = "SELECT * FROM recettes";
$result_recettes = $mysqli->query($rq_recettes);
}
elseif($_POST["cat_recette"] == "Entrée") // Si catégorie Entrée sélectionnée
{
echo "Catégorie Entrée ";
}
elseif($_POST["cat_recette"] == "Plat") // Si catégorie Plat sélectionnée
{
echo "Catégorie Plat ";
$rq_recettes = "SELECT * FROM recettes WHERE cat_recette='Plat'";
$result_recettes = $mysqli->query($rq_recettes);
}
elseif($_POST["cat_recette"] == "Dessert") // Si catégorie Dessert sélectionnée
{
echo "Catégorie Dessert ";
$rq_recettes = "SELECT * FROM recettes WHERE cat_recette='Dessert'";
$result_recettes = $mysqli->query($rq_recettes);
}
elseif($_POST["cat_recette"] == "Soupe") // Si catégorie Soupe sélectionnée
{
echo "Catégorie Soupe ";
$rq_recettes = "SELECT * FROM recettes WHERE cat_recette='Soupe'";
$result_recettes = $mysqli->query($rq_recettes);
}
elseif($_POST["cat_recette"] == "Autre") // Si catégorie Autre sélectionnée
{
echo "Catégorie Autre ";
$rq_recettes = "SELECT * FROM recettes WHERE cat_recette='Autre'";
$result_recettes = $mysqli->query($rq_recettes);
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link href="https://fonts.googleapis.com/css?family=Quando&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/style.css">
<title>cooketal</title>
</head>
<body class="search">
<header>
<?php
include("nav.php");
?>
</header>
<div class="banner">
<h2>Recherche</h2>
</div>
<section class="all-recipes add left">
<div class="frigo-ing col-3">
<table>
<div class="contenu">
<form action="" method="POST">
<h1>Les ingrédients que je possède</h1>
<?php for ($i=1; $i < 10 ; $i++) { ?>
<table>
<th><span><?php echo $i ?></span></th>
<td>
<select name="ing<?php echo $i; ?>">
<option value="" selected>- - - -</option>
<?php
$rq_ingredients = "SELECT * FROM ingredients ORDER BY nom_ingredient ASC";
$result_ingredients = $mysqli->query($rq_ingredients);
while($row_ingredients = $result_ingredients->fetch_object()){ ?>
<option value="<?php echo $row_ingredients->id_ingredient; ?>"><?php echo $row_ingredients->nom_ingredient; ?></option>
<?php } ?>
</select>
</td>
</table>
<?php } ?>
<h1>Une catégorie en particulier ?</h1>
<select id="cat-recette" name="cat_recette">
<option value="">- - - -</option>
<?php
$rq_cat = "SELECT * FROM categories ORDER BY id_cat";
$result_cat = $mysqli->query($rq_cat);
while( $row_cat = $result_cat->fetch_object()){ ?>
<option value="<?php echo $row_cat->cat_recette; ?>" <?php if( isset( $_POST["cat_recette"]) AND $_POST["cat_recette"] == $row_cat->cat_recette){ echo "selected";} ?>><?php echo $row_cat->cat_recette; ?></option>
<?php } ?>
</select><br>
<input type="submit" name="Recherche" value="Go">
</form>
</div>
</table>
</div>
<div class="frigo-ing col-3">
<h1>Résultats</h1>
</div>
</section>

If suggest you to use ajax and make select in html and set the ajax call when the select's value has changed.Like this.
SELECT:
<select name='select' class='ingredient'>
<option value="" selected>- - - -</option>
<?php
$rq_ingredients = "SELECT * FROM ingredients ORDER BY nom_ingredient ASC";
$result_ingredients = $mysqli->query($rq_ingredients);
while($row_ingredients = $result_ingredients->fetch_object()){ ?>
<option value="<?php echo $row_ingredients->id_ingredient; ?>"><?php echo $row_ingredients->nom_ingredient; ?></option>
<?php } ?>
</select>
AJAX CALL:
$('.ingredient').change(function() {
var selected = $('.ingredient').val();
var data = "";
$.ajax({
type:"GET",
url : "search.php?ingredient='+selected+'',
data : "",
async: false,
success : function(response) {
//Here you get recipe name in response as return .. I hope it work.
},
error: function() {
alert('Error occured');
}
});
Make another page called search.php
Here you get recipe having ingredient
<?php
$id = $_GET["ingredient"];
$sql = "SELECT * FROM recettes WHERE cat_recette='$id'";
$result = $conn->query($statement);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "".$row["nom_recette"]."";
}
}
?>

Related

Displays the current value taken from ENUM in form

I have a field in the mysql database of type "ENUM",
the field is called "career_status" and these values are stored,
Active,
Retired,
Dead
I created a form for update, the one I would like and display the current value in the form.
Example:
if now it is stored Active displaying Active in the form, if nothing is empty etc ..
How to get these values from the field?
this is the code
<?php
require_once("connetti.php");
$actor_id = $_GET["id"];
$query = mysql_query("SELECT * FROM actor WHERE actor_id=" . (int)$actor_id) or die ("Error in query: " . mysql_error());
$row = mysql_fetch_array ($query);
$nome=$row['nome'];
$performer_aka=$row['performer_aka'];
$website=$row['website'];
$career_status=$row['career_status'];
$birthday=$row['birthday'];
$died=$row['died'];
$status=$row['status'];
?>
<div id="BioData" style="overflow: hidden;">
<center><h1><?php echo $nome;?> <span class="infoblock-pagetype">modifica dati</span></h1></center>
<form action="<?php echo $_SERVER['PHP_SELF'] . '?id=' . $actor_id; ?>" method="post">
<tr>
<td class="paramname">
<b>Career Status: </b> (<b><font color="red">selezionare il valore</font></b>)
</td>
<td class="paramvalue">
<select name="career_status" id="career_status"><?php echo $career_status;?>
<option value="1">Active</option>
<option value="2">Retired</option>
<option value="3">Dead</option>
<option value="0"> </option>
</select>
</td>
</tr>
<?php
if (isset($_POST['modifica']))
{
//include "connetti.php";
//$query = mysql_select_db("xxx", $db);
if ($query)
{
$nome=$_POST['nome'];
$performer_aka=$_POST['performer_aka'];
$website=$_POST['website'];
$career_status=$_POST['career_status'];
$birthday=$_POST['birthday'];
$died=$_POST['died'];
$status=$_POST['status'];
$query=mysql_query("UPDATE actor SET
nome='".$_POST['nome']."',
performer_aka='".$_POST['performer_aka']."',
website='".$_POST['website']."',
career_status='".$_POST['career_status']."',
birthday='".$_POST['birthday']."',
died='".$_POST['died']."',
status='".$_POST['status']."'
WHERE actor_id=". $actor_id);
if($query) echo "<h2>Congratulazioni! Dati inseriti.</h2>";
else echo "<h2>Attenzione! Dati non inseriti!</h2>";
} else echo "<h2>Errore! Database non selezionato.</h2>";
}
?>
If I understood correctly that you wish to indicate which career_status option is currently selected for the record then perhaps the following might help
<select name='career_status'>
<?php
/* possible options for career status */
$status=array(
0=>'',
1=>'Active',
2=>'Retired',
3=>'Dead'
);
for( $i=0; $i < count( $status ); $i++ ){
/* is this item selected? */
$selected = $i==$career_status ? ' selected' : '';
printf('
<option value="%d"%s>%s',
$i,
$selected,
$status[ $i ]
);
}
?>
</select>

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>";
}
}
}
?>

Request Dropdown list

I have a dropdown list with 5 elements (Volleyball, Handball, Rugby, Basketball, Autres)
I wish for example to select the element "Rugby" in my form, then confirm.
My problem is when I wish to change my old choice in my form (edit); the element "Rugby" is not the element which has been save previously.
By default I always have the element "VolleyBall".
[![<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>][1]][1]
[1]: https://i.stack.imgur.com/xQ83B.png
Here is my code.
<?php
// including the database connection file
include_once("config_bd.php");
if(isset($_POST['update']))
{
$pk_club = mysqli_real_escape_string($mysqli, $_POST['pk_club']);
$nom_club = mysqli_real_escape_string($mysqli, $_POST['nom_club']);
$type_club = mysqli_real_escape_string($mysqli, $_POST['type_club']);
// checking empty fields
if(empty($nom_club) || empty($type_club)) {
if(empty($nom_club)) {
echo "<font color='red'>Le nom du club est vide.</font><br/>";
}
if(empty($type_club)) {
echo "<font color='red'>Le type du club est vide.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE clubs SET nom_club='$nom_club',type_club='$type_club' WHERE pk_club=$pk_club");
//redirectig to the display page. In our case, it is index.php
header("Location: vue_club.php");
}
}
//getting id from url
$pk_club = $_GET['pk_club'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM clubs WHERE pk_club=$pk_club");
while($res = mysqli_fetch_array($result))
{
$nom_club = $res['nom_club'];
$type_club = $res['type_club'];
}
?>
<html>
<head>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Palais des Sports</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style/style1.css">
<body>
<div class="bandeau-bleu">
<h2>Palais des Sports</h2>
<i class="material-icons"></i>
<i class="material-icons"></i>
</div>
<div class="form_encodage">
<h3>Cliquez ici pour afficher les enregistrements</h3>
<br />
<h4> Editer un enregistrement</h4><br />
<form name="form1" method="post" action="edit_club.php">
<table border="0">
<tr>
<td>Nom du Club:</td>
<td><input type="text" name="nom_club" value="<?php echo $nom_club;?>"></td>
</tr>
<tr>
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>
</td></tr>
<td><input type="submit" name="update" class="bouton_bleu" value="Update"></td>
<td><input type="hidden" name="pk_club" value=<?php echo $_GET['pk_club'];?>></td>
</tr>
</table>
</form>
</div>
</body>
</html>
You can use selected property with options.
Below is updated code for dropdown you have put thin td.
Try this:
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option <?php if(isset($type_club) and $type_club=='Volley-Ball'){ echo 'selected'; }?>>Volley-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Hand-Ball'){ echo 'selected'; }?>>Hand-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Rugby'){ echo 'selected'; }?>>Rugby</option>
<option <?php if(isset($type_club) and $type_club=='Basket-Ball'){ echo 'selected'; }?>>Basket-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Autres'){ echo 'selected'; }?>>Autres</option>
</select>
</td>
Complete updated code:
<?php
// including the database connection file
include_once("config_bd.php");
if(isset($_POST['update']))
{
$pk_club = mysqli_real_escape_string($mysqli, $_POST['pk_club']);
$nom_club = mysqli_real_escape_string($mysqli, $_POST['nom_club']);
$type_club = mysqli_real_escape_string($mysqli, $_POST['type_club']);
// checking empty fields
if(empty($nom_club) || empty($type_club)) {
if(empty($nom_club)) {
echo "<font color='red'>Le nom du club est vide.</font><br/>";
}
if(empty($type_club)) {
echo "<font color='red'>Le type du club est vide.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE clubs SET nom_club='$nom_club',type_club='$type_club' WHERE pk_club=$pk_club");
//redirectig to the display page. In our case, it is index.php
header("Location: vue_club.php");
}
}
//getting id from url
$pk_club = $_GET['pk_club'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM clubs WHERE pk_club=$pk_club");
while($res = mysqli_fetch_array($result))
{
$nom_club = $res['nom_club'];
$type_club = $res['type_club'];
}
?>
<html>
<head>
</head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Palais des Sports</title>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style/style1.css">
<body>
<div class="bandeau-bleu">
<h2>Palais des Sports</h2>
<i class="material-icons"></i>
<i class="material-icons"></i>
</div>
<div class="form_encodage">
<h3>Cliquez ici pour afficher les enregistrements</h3>
<br />
<h4> Editer un enregistrement</h4><br />
<form name="form1" method="post" action="edit_club.php">
<table border="0">
<tr>
<td>Nom du Club:</td>
<td><input type="text" name="nom_club" value="<?php echo $nom_club;?>"></td>
</tr>
<tr>
<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option <?php if(isset($type_club) and $type_club=='Volley-Ball'){ echo 'selected'; } ?>>Volley-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Hand-Ball'){ echo 'selected'; } ?>>Hand-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Rugby'){ echo 'selected'; } ?>>Rugby</option>
<option <?php if(isset($type_club) and $type_club=='Basket-Ball'){ echo 'selected'; } ?>>Basket-Ball</option>
<option <?php if(isset($type_club) and $type_club=='Autres'){ echo 'selected'; }?>>Autres</option>
</select>
</td></tr>
<td><input type="submit" name="update" class="bouton_bleu" value="Update"></td>
<td><input type="hidden" name="pk_club" value=<?php echo $_GET['pk_club'];?>></td>
</tr>
</table>
</form>
</div>
</body>
</html>
You will need to query your database before loading your select form to get the previous save then build your list
$sqla= "SELECT * FROM `save_table` WHERE `id` = $id ";
$result = $conn->query($sqla);
if ($result->num_rows > 0) {
$save = $row['save'];
$select= ('<td>Type de Club:</td><td>
<select name="type_club" style="width:144px">
<option>');
$select.='$save';
$select.='</option> <option>Volley-Ball</option>
<option>Hand-Ball</option>
<option>Rugby</option>
<option>Basket-Ball</option>
<option>Autres</option>
</select>';
echo $select;
You can also use if statements to remove the second $save variable from the list before you build it so there is no repeat option in the list.

Dynamic Select Boxes work half

I have two fail for my script.
1.publicAdvart.php
<script type="text/javascript">
$(document).ready(function () {
$('#select_marka').change(function () {
$.post(
'modeli.php',
{id: $('#select_marka').val()},
function (res) {
$('#model').html(res);
}
);
});
});
</script>
<select class="form-control" name="marka" id="select_marka">
<option></option>
<?php
$sel = "SELECT * FROM marka";
$query = mysqli_query($conn, $sel);
while ($row = mysqli_fetch_array($query)) {
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['marka']; ?></option>
<?php
}
?>
</select>
2.modeli.php
<?php
if (isset($_POST['id']) && $_POST['id'] != '') {
$marka_id = $_POST['id'];
?>
<select id="select_marka" class="form-control">
<?php
$selModel = "SELECT * FROM marka_model WHERE marka_id='$marka_id'";
$queryModel = mysqli_query($conn, $selModel);
while ($rows = mysqli_fetch_array($queryModel)) {
?>
<option value="<?php echo $rows['model']; ?>"><?php echo $rows['model']; ?></option>
<?php
}
?>
</select>
<?php
}
?>
Where is a problem? These two script half work.
This is OK click "Opel" -> "meriva". http://i.stack.imgur.com/ma5XZ.jpg
Next step 2 is a problem, i want "name" marka and "name" model.
Problem this is here.I don't get "marka - id", i want "name" http://i.stack.imgur.com/Nm1Yk.jpg
Update:
step2.php
<?php
if (isset($_POST['submit'])) {
$marka = $_POST['marka'];
$model = $_POST['model'];
$_SESSION['marka'] = $marka;
$_SESSION['model'] = $model;
}
?>
<div class="col-md-12 well advertTittle">
<h4 class="well">
<?php echo $_SESSION['marka'] . '&nbsp' . $_SESSION['model'] . '&nbsp' . stripslashes($_SESSION['modify']); ?>
</h4>
<span><?php echo $_SESSION['price'] . ' лв.'; ?></span>
</div>
You forget to give the "name" attribute for yours "marka" select field:
<?php
...
?>
<select id="select_marka" class="form-control"> // <- here
<?php
$selModel = "SELECT * FROM marka_model WHERE marka_id='$marka_id'";
....
Should be something like this:
<?php
...
?>
<select id="select_model" class="form-control" name="model"> // <- here!!!
// "id" attribute also should be changed
<?php
$selModel = "SELECT * FROM marka_model WHERE marka_id='$marka_id'";
....
Also, yours step2.php should be like this:
<?php
if (isset($_POST['submit'])) {
$_SESSION['marka'] = $_POST['marka'];
$_SESSION['model'] = $_POST['model'];
}
function validData($data) {
return
isset($data['marka'])
&& isset($data['model'])
&& isset($data['price'])
;
}
if (validData($_SESSION)) {
$marka_id = intval($_SESSION['marka']);
$model_id = intval($_SESSION['model']);
$marka = mysqli_fetch_array(mysqli_query($conn, "SELECT name FROM marka where id = $marka_id"));
$model = mysqli_fetch_array(mysqli_query($conn, "SELECT name FROM marka_model WHERE id = $model_id"));
?>
<div class="col-md-12 well advertTittle">
<h4 class="well">
<?php echo $marka['name'] . '&nbsp' . $model['name'] . '&nbsp' . (isset($_SESSION['modify']) ? stripslashes($_SESSION['modify']) : ''); ?>***
</h4>
<span>
<?php echo $_SESSION['price'] . ' лв.'; ?>
</span>
</div>
<?php } else { ?>
Not all fields filled.
<?php } ?>

Why do my dropdowns show the message "array(1) ..." for each dependent drop down?

I am designing a page that gathers study abroad information from students at my university. Each time you select a country, the drop down will then say array(1) { ["country"]=> string(6) "France" } (or a similar country) before it says "State:". Why is this?
Below is my code minus the UUID and the database connection.
<!DOCTYPE html>
<head>
<link href="Page2.css" rel="stylesheet">
<style>
.error {
color: #FF0000;
}
</style>
<link href="styles.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.8.23/jquery-ui.min.js"></script>
<script type="text/javascript">
function go() {
var Count = document.getElementById("sa_yesno").options[document.getElementById("sa_yesno").selectedIndex].value;
if(Count==1) {
document.getElementById("info").style.display = 'none';
}
if(Count==2) {
document.getElementById("info").style.display = '';
}
}
$(document).ready(function(){
$("select#countryName").change(function() {
var country = $("select#countryName option:selected").attr('value');
//alert(country);
$("#state").html("");
$("#city").html("");
if (country.length > 0 ) {
//alert(country.length);
$.ajax({
type: "POST",
url: "fetch_state.php",
data: "country="+country,
cache: false,
success: function(html) {
$("#state").html( html );
}
//not sure about these last two parts
});//end ajax
}//end if
});//end countryName.change
});
</script>
<header>
<h1> University </h1>
<h2> Department </h2>
</header>
</head>
<?php
require 'dbc.php';
require 'uuid.php';
$countriesSQL = "SELECT DISTINCT Country FROM LOCATIONLOOKUP";
$countriesQuery = mysqli_query($conn, $countriesSQL);
while($countries[] = $countriesQuery->fetch_object());
array_pop($countries);
?>
<body>
<table><tr><td>
<div class="StyleDiv" >
<form action="Page3.php" method="post">
<p> Please share any of the information below that you are comfortable sharing about your study abroad experience, if applicable.</p>
<p> 1. Did you study abroad? </p>
<p><select onchange="go()" name="sa_yesno" id="sa_yesno">
<option value="1">No</option>
<option value="2">Yes</option>
</select></p>
<div class="styleDiv" id="info" style="display:none">
<p> 2. When did you study abroad? </p>
<p><select name="sa_term" id="sa_term">
<option value="Fall">Fall Semester</object>
<option value="Spring">Spring Semester</object>
<option value="J-term">J-Term</object>
<option value="Summer">Summer Term</object>
</select></p>
<p> Where did you study abroad?</p>
Country: <select name="countryName" id="countryName">
<option value="">Please Select</option>
<?php foreach($countries as $option) : ?>
<option value="<?php echo $option->Country; ?>"><?php echo $option->Country; ?></option>
<?php endforeach; ?>
</select></br>
<div id="state" class="cascade"></div>
<div id="city" class="cascade"></div>
<br/><br/>
<input type="submit" value="Continue" name="submit" id="submit" ONCLICK="window.location.href='Page3.php?'">
</div>
</form>
<?php
require 'dbc.php';
require 'uuid.php';
$studentID = $_SESSION["studentID"];
$studyid=null;
//can these be assigned values in the select tag above?
$countrySelected= $_POST["countryName"];
$stateSelected= $_POST["drop2"];
$citySelected= $_POST["drop3"];
//Select the locationID from the country, state, city that were specified
$sql2 = "SELECT LocID FROM LOCATIONLOOKUP WHERE Country = '" . $countrySelected . "'
AND StateProvince = '" . $stateSelected . "' AND City = '" . $citySelected . "';";
$result2 = mysqli_query($conn, $sql2);
if (!$result2) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query 2: ' . $query;
die($message);
echo "there was an issue";
}
while ($row = mysqli_fetch_assoc($result2)) {
$locationID = $row['LocID'];
}
$stmt = $conn->prepare(" INSERT INTO STUDYABROAD (Term, StudentID, LocID) VALUES ( ?, ?, ?, ?)");
$stmt->bind_param("ssss", $term, $studentID, $locationID);
$stmt->execute();
mysqli_close($conn);
?>
</body>
</html>
EDIT: Here is fetch_state.php
<?php
require 'dbc.php';
var_dump($_POST);
$country = trim(mysqli_escape_string($conn, $_POST["country"]));
$sql = "SELECT DISTINCT StateProvince FROM LOCATIONLOOKUP WHERE Country = '". $country ."' ORDER BY StateProvince";
$count = mysqli_num_rows( mysqli_query($conn, $sql) );
if ($count > 0) {
$query = mysqli_query($conn, $sql);
while($states[] = $query->fetch_object());
array_pop($states);
?>
<label>State:
<select name="state" id="drop2">
<option value="">Please Select</option>
<?php foreach($states as $option) : ?>
<option value="<?php echo $option->StateProvince; ?>"><?php echo $option->StateProvince; ?></option>
<?php endforeach; ?>
</select>
</label>
<?php
}
?>
<script src="jquery-1.9.0.min.js"></script>
<script>
$(document).ready(function(){
$("select#drop2").change(function(){
var state = $("select#drop2 option:selected").attr('value');
// alert(state_id);
if (state.length > 0 ) {
$.ajax({
type: "POST",
url: "fetch_city.php",
data: "state="+state,
cache: false,
success: function(html) {
$("#city").html( html );
}
});
} else {
$("#city").html( "" );
}
});
});
</script>

Categories