How to use ng-change in select dropdown with population functionality - php

I'm newbie to angular js, I'm building an ionic app in which, I'm trying to populate the select option depends upon first select option, but the variable which is selecting in first select option is not able to process for getting second select option
here is my service.js
cityFunction: function(bookUser) {
var link = 'http://localhost/endpoints/citydetails.php';
return $http.post(link);
},
selectedsitesFunction: function(bookUser) {
var data = { selectedCity1: bookUser.selectedCity1};
var link = 'http://localhost/endpoints/selectedSites.php';
return $http.post(link, data);
}
controller.js
$scope.bookUser.city = city;
$scope.bookUser.selectedCity = "";
$scope.bookUser.selectedCity1 = "";
$scope.bookUser.site1 =[];
$scope.bookUser.selectedSite1 = "";
$scope.getOptions2 = function(bookUser){
$scope.bookUser.selectedCity1 = $scope.bookUser.selectedCity.Id;
AllServices.selectedsitesFunction(bookUser)
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
});
};
here is html page
<label class="item item-input item-select item-stacked-label">
<span class="input-label">City</span>
<select name="city" ng-model="bookUser.selectedCity" ng-options="item.City for item in bookUser.city" ng-change="getOptions2(bookUser)">
<option value="">-- select city --</option>
</select>
</label>
<label class="item item-input item-select item-stacked-label">
<span class="input-label">sites</span>
<select name="site1" ng-model="bookUser.selectedSite1" ng-options="option for option in bookUser.site1">
<option value="">--select site--</option>
</select>
</label>
and this is .php code
<?php
include 'connection.php';
$data = json_decode(file_get_contents("php://input"));
$selectedCity1 = $data->$selectedCity1;
$selectedSites = $db->query("SELECT Sites, Id from sitemaster where City = :selectedCity1 ");
$selectedsites = $selectedSites->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($selectedsites);
?>
whenever I'm trying to access this selectedCity1 variable, the console shows the error
Notice: Undefined variable: selectedCity1 in C:\xampp\htdocs\endpoints\selectedSites.php on line 4
Fatal error: Cannot access empty property in C:\xampp\htdocs\endpoints\selectedSites.php on line 4

<?php
include 'connection.php';
$data = json_decode(file_get_contents("php://input"));
$selectedCity1 = $_POST['selectedCity1'];
$query = mysql_query("select Sites, Id from sitemaster where City = "+$selectedCity1+"");
while ($fetch = mysql_fetch_array($query)) {
$output[] = array("site" => $fetch[0],"id" => $fetch[1];
}
echo json_encode($output);
?>
Hope this helps you :) Thanks

<?php
include("connection.php");
$data = json_decode(file_get_contents("php://input"));
$selectedCity1 = $data->selectedCity1;
$selectedSites = $db->query("SELECT Id, Sites FROM sitemaster WHERE City ='$selectedCity1' ");
$selectedSites = $selectedSites->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($selectedSites);
?>

Related

How to update a field on the form based on a select option

I have a PHP form with the following select list;
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)"
<?php
$MC = $_SESSION["MatchCapt"];
player_load($MC);
?>
>
</select>
I also have a text field ;
Telephone Number: </b> <?php echo $_SESSION["TeleNo"]; ?></p>
The PHP function called by the onchange command is ;
function findTeleNo($MatchCaptain){
$db_handle = mysqli_connect(DB_SERVER, DB_USER, DB_PASS );
$database = "matchmanagementDB";
$db_found = mysqli_select_db($db_handle, $database);
if ($db_found) {
$SQL = "SELECT * FROM `playerstb` ORDER BY `Surname` ASC, `FirstName` ASC";
$result = mysqli_query($db_handle, $SQL);
$ufullName = split_name($MatchCaptain);
while ( $db_field = mysqli_fetch_assoc($result) ) {
$uName = $db_field['FirstName'];
$uName = trim($uName);
$Surname = $db_field['Surname'];
$Surname = trim($Surname);
$fullName = $uName." ".$Surname;
if ($fullName == $ufullName )
{
$_SESSION["TeleNo"] = $db_field['TeleNo'];
include "Match_sort.php";
break;
}
}
}
}
What I am trying to do is when the Match Captains name is changed in the SELECT dropdown list then I want the FUNCTION findTeleNo() to run. Which should then reload the form with the telephone number of the New Match Captain.
However, when I select a new Match Captain the onchange command is ignored.
As a Septuagenarian, just learning this language, I need some help!
Does onchange work in PHP? If not what should I use?
The onchange event is a javascript event, it cannot call your php function directly. You can create a javascript function that will be called when the selects value changes and then this can make an xhr(Ajax) request to a php file which will perform a database query and return what you need it to. You could then update the page with javascript.
PHP is a server side language, you need to use javascript for this.
this is example:
function findTeleNo (value) {
console.log(value);
$.ajax({
url: 'findTeleNo.php',
data: {
c_name: value
},
success: function (response) {
$('#cname').text(response.cname);
$('#teleno').text(response.teleno);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select id ="MatchCaptain" name="MatchCaptain" onchange="findTeleNo(this.value)">
<option>choose one</option>
<option value="A1">A1</option>
<option value="B2">B2</option>
<option value="C3">C3</option>
</select>
<div>
<div>
Captain Name is: <span id="cname">empty</span>
<div>
<div>
TeleNo is: <span id="teleno">empty</span>
<div>
and in file findTeleNo.php you print json has cname and teleno.

Getting Data Items from MySQL database using AJAX, PHP and JSON

I'm stuck getting my AJAX/PHP to work. I'd really appreciate it if someone can help me to spot the error(s) I'm making.
Here's an extract from my first file which successfully populates the select in the HTML:
<?php
include 'connect_db.php';
//get all period types data
$sql = "SELECT * FROM periodtypes ORDER BY period_type_id";
$result = mysqli_query($connect,$sql);
$rowCount = mysqli_num_rows($result);?>
The HTML/PHP for the select:
<select id="period_type_id" name="period_type_id" onchange="getNewP();">
<option value="">Select a Period Type</option>
<?php
if($rowCount>0){
while ($row=mysqli_fetch_assoc($result)){
echo '<option value="'.$row['period_type_id'].'">'.
$row['period_type_desc'].
' </option>';
}
}else{
echo '<option value="">Period type not available</option>';
}
?>
</select>
The HTML for the inputs I wish to update using the AJAX function below:
<label>Start Date (Auto-generated):</label>
<input type="text" id="start_date" name="start_date" value = "" readonly>
<br><br>
<label>End Date (Auto-generated):</label>
<input type="text" id="end_date" name="end_date" value = "" readonly>
And the AJAX function:
function getNewP(){
var id = $("#period_type_id").val();
alert(id); //This fires ok
if (id != '')
{
$.ajax({
url: "get_period_nbrs.php",
method:"POST",
data: { id : id },
dataType: "JSON",
success: function(output)
{
$('#start_date').text(output.start_date);
$('#end_date').text(output.end_date);
}
});
}else
{
alert("Please select a Period Type");
}
}
Finally, the main PHP script:
<?php
include 'connect_db.php';
if (isset($_POST['id']) && !empty($_POST['id'])){
//echo $_POST[id];
$sql = "SELECT SUBSTRING(MAX(period_nbr),5,2)+1 AS nxt_sfx,
MAX(start_date)+ 1 as start_date, MAX(end_date)+1 AS end_date
FROM periods AS p
INNER JOIN periodtypes AS pt on pt.period_type_id = p.period_type_id
WHERE p.period_type_id = '".$_POST['id']."'";
$result = mysqli_query($connect,$sql);
while($row=mysqli_fetch_array($result)){
if($result == true){
$start_date = $row['start_date'];
$end_date = $row['end_date'];
$period_nbr_nxt_sfx = $row['nxt_sfx'];
if ($period_nbr_nxt_sfx < 52 && $period_nbr_nxt_sfx != NULL){
$output['start_date'] = $row['start_date'];
$output['end_date'] = $row['end_date'];
echo json_encode($output);
}
}
}
}
?>
You're not using the right method to fill your inputs :
$('#start_date').text(output.start_date);
$('#end_date').text(output.end_date);
Should be :
$('#start_date').val(output.start_date);
$('#end_date').val(output.end_date);
JSON needs a root key, try this:
print_r( "{\"data\": ".json_encode($output)."}" );
instead of
echo json_encode($output);

how to convert multiple array to string in php

Hi All,
i'm getting all the data from database for array format i need to pass that data to second drop down list like (group option value),please any one help me.
This is my php code:
<?php
//error_reporting(0);
$servername = "localhost";
$username = "root";
$password = "";
$db = "essae";
$data = "";
$subcategory_id = "";
$subcategory_name = array();
$conn = mysqli_connect($servername, $username, $password,$db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$category= $_GET["category_id"];
$sql = "SELECT es_category.category_id,es_category_description.name FROM es_category INNER JOIN es_category_description ON es_category.category_id=es_category_description.category_id WHERE parent_id='$category'";
$result = $conn->query($sql);
if ($result->num_rows > 1){
$sql_getrec ="SELECT es_category.category_id AS sub_cat_id,es_category_description.name AS sub_cat_name FROM es_category INNER JOIN es_category_description ON es_category.category_id=es_category_description.category_id WHERE parent_id='$category'";
$sub_category= $conn->query($sql_getrec);
if ($sub_category->num_rows > 1){
while ($row=mysqli_fetch_array($sub_category)){
$subcategory_id = $row['sub_cat_id'];
//$subcategory_name['sub_category_name'][] = $row['sub_cat_name'];
$sql_getrec = "SELECT es_product_description.name AS prod_name FROM es_product_to_category LEFT JOIN es_product_description ON es_product_description.product_id=es_product_to_category.product_id LEFT JOIN es_product ON es_product_description.product_id = es_product.product_id WHERE es_product_to_category.category_id = $subcategory_id AND es_product.status=1";
$sub_product=$conn->query($sql_getrec);
while ($prow=mysqli_fetch_array($sub_product)){
$subcategory_name['sub_category_name'][$row['sub_cat_name']]['products_name'][] = $prow['prod_name'];
}
}
echo "<pre>";print_r($subcategory_name);
}
}
else {
$sql_getrec = "SELECT es_product_description.name FROM es_product_to_category LEFT JOIN es_product_description ON es_product_description.product_id=es_product_to_category.product_id LEFT JOIN es_product ON es_product_description.product_id = es_product.product_id WHERE es_product_to_category.category_id='$category' AND es_product.status=1";
$result_getrec=$conn->query($sql_getrec);
while ($row=mysqli_fetch_array($result_getrec)){
$data .= $row['name'].",";
}
$data = rtrim($data,",");
}
print_r($data);
?>
This is my Html code:
<php?
$decocedData1 = json_decode($str_json_format, TRUE);
//print_r($decocedData1);die;
$decode = $decocedData1;
?>
<div>
<select name="category" id="category" />
<option selected ="selected">Select category</option>
<?php foreach($decode as $key => $value) { ?>
<option value="<?php echo $value['category_id']; ?>"><?php echo $value['name']; ?></option>
<?php } ?>
</select>
</div>
<div><select name="category12" id="category12" />
</select>
</div>
this is my j query and ajax method code:
<script type="text/javascript">
$(document).ready(function(){
$('#category').change(function(){
var category_id=$('#category').val();
$.ajax({
type: "get",
url: 'data_product.php?category_id='+category_id,
success: function(data) {
var products = data.split(",");
state_html = '';
state_html = '<option>Please Select product</option>'
$.each(products, function (index, productName) {
state_html += "<option value='"+productName+"'>"+productName+"</option>";
});
$('#category12').html(state_html);
},
});
})
});
</script>
You may use Type Casting in php
Type casting in PHP works much as it does in C: the name of the
desired type is written in parentheses before the variable which is to
be cast.
<?php
$array = array("name", "age", "mobile", "email");
var_dump($array);
(string)$array;
var_dump($array);
?>
This is not your final answer but you can try below code and figure out your variable names
$('#category12').empty();
$.each(data, function (index) {
var optgroup = $('<optgroup>');
optgroup.attr('label',data[index].name);
$.each(data[index].children, function (i) {
var option = $("<option></option>");
option.val(i);
option.text(data[index].children[i]);
optgroup.append(option);
});
$("#category12").append(optgroup);
});
$("#category12").multiselect('refresh');
you can do a jquery each in the result of your ajax
$.each(products, function(key, value) {
$('#category12')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
$(function(){
//sample result, this will be your ajax result....
var products = ["Candy", "Cotton Candy", "Iced Candy"];
//clear again the select element.
$('#category12').empty();
$.each(products, function(key, value) {
$('#category12')
.append($("<option></option>")
.attr("value",value)
.text(value));
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="category12"></select>

Combine the results of several select boxes by using PHP and MySQL in WordPress

I have 4 dynamic dependent select boxes, now I want to combine the result of the 4 selects into a query. I have all the relative code below.
font-end part of the select boxes
<form class="select-boxes" action="<?php echo site_url("/part-search-result/"); ?>" method="POST" target="_blank">
<?php include(__DIR__.'/inc/part-search.php'); ?>
</form>
part-search.php
<?php
include( __DIR__.'/db-config.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" 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" 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" 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" 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" value="Search">
<script type="text/javascript">
jQuery(function($) {
$('#manufact').on('change',function(){
var manufactID = $(this).val();
if(manufactID){
$.ajax({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'manufact_id='+manufactID,
success:function(html){
$('#type').html(html);
$('#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({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'type_id='+typeID,
success:function(html){
$('#year').html(html);
$('#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({
type:'POST',
url:'<?php echo home_url('wp-content/themes/myTheme/inc/ajax-data.php') ?>',
data:'year_id='+yearID,
success:function(html){
$('#model').html(html);
}
});
}else{
$('#model').html('<option value="">Select Year First</option>');
}
});
});
</script>
ajax-data.php
<?php
include( __DIR__.'/db-config.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>';
}
}
?>
part-search-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 id="products" class="row list-group">
<?php while ( $rows = mysqli_fetch_array($result) ): ?>
<div class="item col-xs-12 col-sm-4 col-md-4 col-lg-4">
<div class="thumbnail">
<?php
echo '<img name="product-image" class="group list-group-image hvr-bob" src=' . $rows['image_url'] . ' width="400px" height="250px" alt="" />';
?>
<div class="caption">
<h4 class="group inner list-group-item-heading">
<?php
echo "Manufacturer:\t".$rows['manufacturer'].'<br>';
echo "Type:\t".$rows['type'].'<br>';
echo "Year:\t".$rows['year'].'<br>';
echo "Model:\t".$rows['model'].'<br>';
echo '<br>';
echo "Description:\t".$rows['description'].'<br>';
?>
</h4>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
<?php get_footer(); ?>
Now my problem is:
If only select the first one box, or select the first two boxes, and click the Search button, it successfully jumps to the result page. However, if continuously select the third box, the result page is gone and Chrome Console returns the error:
Failed to load resource: the server responded with a status of 404 (Not Found)
Let me ask you a question. You've tagged this as a WordPress website. Correct? Then why aren't you using the built-in database handler, $wpdb to both prepare and communicate with the database? It's the safest and fastest way for you to work with the database.
Revised Code
Here I've revised your code to do the following:
Use $wpdb->prepare to sanitize the $_POST values to protect the database from nefarious folks
Remove redundancies by looping through a list of column names and using the field naming pattern you specified by suffixing _text to the column name
Using $wpdb->get_results() to go fetch the results.
Here is the revised code:
/**
* Build the search's WHERE SQL from the form's $_POST fields.
*
* #since 1.0.0
*
* #return string
*/
function build_search_where_sql() {
global $wpdb;
$column_names = array(
'manufacturer',
'type',
'year',
'model',
);
$where_clauses = [];
foreach( $column_names as $column_name ) {
$post_key = $column_name . '_text';
if ( isset( $_POST[ $post_key ] ) && $_POST[ $post_key ] ) {
$where_clauses[] = $wpdb->prepare( "{$column_name} = %s", $_POST[ $post_key ] );
}
}
if ( empty( $where_clauses ) ) {
return '';
}
$where_sql = " WHERE " . join( ' AND ', $where_clauses );
return $where_sql;
}
/**
* Get the search results from the database. If the records
* do not exist or an error occurs, false is returned. Else,
* an array with stdClass objects for each record is returned.
*
* #since 1.0.0
*
* #return bool|array
*/
function get_search_database_results() {
$where_sql = isset( $_POST['search'] )
? build_search_where_sql()
: "WHERE manufacturer = ''";
if ( ! $where_sql ) {
return false;
}
global $wpdb;
$sql_query = "SELECT * FROM wp_products {$where_sql};";
$records = $wpdb->get_results( $sql_query );
if ( ! $records ) {
return false;
}
return $records;
}
UPDATE: Strategy for You
Now that I've seen the HTML code you are proposing as well as knowing you are learning about building websites, let's talk about a different architectural strategy for your project.
Don't use a custom database table.
Use a custom post type called products instead.
Use post metadata to set the attributes for each product, i.e. the manufacturer, model, year, type, etc.
Use a form plugin, such as Ninja Forms.
You can build the meta boxes yourself for the metadata, if you have the technical chops to do it. Else, you can use a third-party plugin such as CMB2 or ACF.
Custom Post Type
WordPress provides you the ability to add custom content. They provide built-in post types. We developers can add custom ones that are specific content context. Products is a good candidate for a custom post type.
You can generate the code on GenerateWP. It's literally a few lines of code to create it.
Where can you learn about Custom Post Types?
Well, there are plenty of tutorials. Codex gives you the documentation and examples. I teach it at Know the Code. Tuts+ has lots of tutorials. And many others....
Why Custom Post Type Instead of Custom Db Table?
Yes, you can build a custom database table. But it requires you to add the schema, seed the table, write the interface for admins to interact with the content, and then write and secure the interaction. To populate the options in the select, you'd have to query the database using $wpdb and then write a model to translate it into a view. Then you'd have to write the form processing to interact and save.
In other words, it's going to cost you time and money. Why? Because it's more code and not native to WordPress. You have to write, secure, test, and maintain it yourself.
If You Want to Stick With Your Current Strategy
If you prefer to stick with the custom database table strategy, then here are some suggestions to help you out:
You don't need the hidden input for each of the select elements. Why? When the form is posted, the option set for each select will post back to the server.
I'd change the select names to be an array, like this: name="part-select[manufacturer]" and then repeat for type, model, year, etc. Then you can grab the $_POST['part-select'] to get all of the values.
You are going to want to add nonce to protect the content. Make sure to pass it with the data packet when doing AJAX too.
Using AJAX, you can request the records from the database. You'll need to modify the code I gave to you in order to build the SQL query. Then loop through the results to build the HTML you want to send back to the front-end.
I like building the HTML markup on the server side and then sending that back to the front-end when doing AJAX.
Cheers.

insert value of select form into mysql

I have a form that adds vehicles to a database, there are 2 drop down select fields in the form, 'Make' and 'Model'
When I select an option from either one to insert it into the stock table in the database the make 'ID' or model 'ID' gets inserted into vehicle make / model rather than the name of the vehicle make, so '3' gets inserted instead of 'Volkswagen'
Here is some of my code
<form action="addstock.php" method="post" enctype="multipart/form-data">
<div class="make">
<div id="field1">Make:</div> <div id="field2">
<select name="mke" id="mke">
<?php
include 'includes/db2.php';
$SQL = "SELECT * FROM make";
$query = mysqli_query($con, $SQL);
while ($row = mysqli_fetch_array($query)) {
$res = "<option ";
$res .= "value='".$row['code']."'>";
$res .= $row['vehicle_make'];
$res .= '</option>';
echo $res;
}
?>
</select>
</div>
</div>
</div>
<script src="jquery/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$('#mke').change(function(){
var code = $(this).val();
var data = 'code='+code;
$.ajax({
type : "POST",
url : "fill.php",
data : data,
cache: false,
success: function(html)
{
$('#mdl').html(html);
}
});
});
});
</script>
Code for the model drop down option, the rest of the code for this is on another page (fill.php)
<div id="field1">Model:</div> <div id="field2">
<select name="mdl" id="mdl">
<option selected="selected">Model</option>
</select>
</div>
</div>
fill.php page
if(isset($_POST['code']))
{
$SQL = "SELECT * FROM model WHERE MakeCode = '".$_POST['code']."'";
$query = mysqli_query($con, $SQL);
if(mysqli_num_rows($query) == 0 )
{
echo '<option>No Results</option>';
} else {
while ($row = mysqli_fetch_array($query)) {
$res = "<option ";
$res .= "value='".$row['id']."' >";
$res .= $row['vehicle_model'];
$res .= "</option>";
echo $res;
}
}
} else {
echo '<option >error</option>';
}
?>
Back on the addstock.php page here is the insert code
<?php
if(isset($_POST['addstock'])){
$mke = $_POST['mke'];
$mdl = $_POST['mdl'];
$addstock = "insert into stock (veh_make,veh_model) values('$mke','$mdl')";
$addsto = mysqli_query($con, $addstock);
if($addsto){
echo "<script>alert('Vehicle has been added')</script>";
echo "<script>window.open('addstock.php','_self')</script>";
}
}
I'm fairly new to php and not sure how to insert the name instead of the id, as when I am trying to display a vehicle on another page the ID's show like 3 4, instead of Volkswagen Golf
Hope you understand what I mean
Any help is much appreciated!
You can insert the result of a SELECT statement that gets you the make and model:
"insert into stock (veh_make,veh_model) select make.vehicle_make, vehicle_model FROM make, model WHERE make.id=$mke AND model.id=$mdl"
But this is wrong DB design. stock should not contain make and model names, but rather IDs, references to rows in other tables, or Foreign Keys.

Categories