Can I insert php & html inside a multi line php variable? - javascript

So I'm a total beginner and I'm working on a project to create dynamic dropdown forms. I have written some code and am wondering now if I can insert php & html inside a multi line php variable. This code below is what I just tried[javascript not included here] but php shows error. Is this not possible at all or is it some error on my part? Thanks in advance.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<?php
$chooseroom=<<<HERE
<div class="select-boxes">
<?php
//Include database configuration file
include('dbConfig.php');
//Get all occupation data
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
}else{
echo '<option value="">occupation not available</option>';
}
?>
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
HERE;
echo $chooseroom;
</body>
</html>
OK AS REQUESTED BY SOME OF YOU HERE IS MY JAVASCRIPT:
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#occupation').on('change',function(){
var occupationID = $(this).val();
if(occupationID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'occupation_id='+occupationID,
success:function(html){
$('#specification').html(html);
$('#expertise').html('<option value="">Select specification first</option>');
}
});
}else{
$('#specification').html('<option value="">Select occupation first</option>');
$('#expertise').html('<option value="">Select specification first</option>');
}
});
$('#specification').on('change',function(){
var specificationID = $(this).val();
if(specificationID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'specification_id='+specificationID,
success:function(html){
$('#expertise').html(html);
}
});
}else{
$('#expertise').html('<option value="">Select specification first</option>');
}
});
});
</script>

Yes it is possible to add multi line html and php to a variable. You can add multiple entries in options as given below
while($row = $query->fetch_assoc()){
/* here . operator is used to append
to the existing value of $chooseroom */
$chooseroom .= '<option value="'.$row['occupatio_id'].'">'.$row['occpation_name'].'</option>';
}
Print this variable where it is required as
<?php echo $chooseroom; ?>

You can't do what you're attempting in the way you're attempting it; what you're trying to do is run PHP code inside a HEREDOC block.
However, you can put the PHP code, and create your set of options, before that block and just interpolate it where required (you don't even need to assign the HEREDOC block to a variable, you can use echo it out):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<?php
//Include database configuration file
include('dbConfig.php');
//Get all occupation data
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
// Create an HTML options string
$htmlOptions = "";
if($rowCount > 0) {
while($row = $query->fetch_assoc()){
$htmlOptions .= '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
} else {
$htmlOptions .= '<option value="">occupation not available</option>';
}
// Output
echo <<<HERE
<div class="select-boxes">
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
$htmlOptions
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
HERE;
?>
</body>
</html>
Though, to be honest, the whole HEREDOC thing is slightly superfluous here as you can just break out of the PHP and echo out your options where you need them - makes for slightly better separation between the PHP and HTML code as well:
<?php
//Include database configuration file
include('dbConfig.php');
//Get all occupation data
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
// Create an HTML options string
$htmlOptions = "";
if($rowCount > 0) {
while($row = $query->fetch_assoc()){
$htmlOptions .= '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
} else {
$htmlOptions .= '<option value="">occupation not available</option>';
}
// OUTPUT
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<div class="select-boxes">
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
<?= $htmlOptions; ?>
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
</body>
</html>

I've always liked this solution myself:
<?php
include('dbConfig.php');
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
$rowCount = $query->num_rows;
ob_start();
if ( $rowCount > 0 ) {
while( $row = $query -> fetch_assoc() ){
echo '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
} else {
echo '<option value="">occupation not available</option>';
}
$values = ob_get_clean();
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<div class="select-boxes">
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
<?php echo $values; ?>
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
</body>
</html>

Related

Cant seem to get the first dependency to run on AJAX call

I am having significant issues trying to get the AJAX to fire on this PHP code.
I can get the first field populated without issue, however the AJAX call does not seem to populate the first dependency (and therefore the second). I am an AJAX newbie (and have googled extensively) but cannot seem to crack this one.
Note that the ladb.php file runs fine.
<?php
// Include the database config file
include_once 'ladb.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body style="background: #D5DDE0">
<div class="container">
<form action="" method="post">
<div class="form-group col-md-6">
<!-- Country dropdown -->
<label for="country">Country</label>
<select class="form-control" id="country">
<option value="">Select Country</option>
<?php
$query = "SELECT * FROM City_Index GROUP BY country ORDER BY country ASC";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<option value='{$row["countryid"]}'>{$row['country']}</option>";
}
}else{
echo "<option value=''>Country not available</option>";
}
?>
</select><br>
<!-- State dropdown -->
<label for="admin">Administrative Area</label>
<select class="form-control" id="admin">
<option value="">Select Administrative Area</option>
</select><br>
<!-- City dropdown -->
<label for="city">city_ascii</label>
<select class="form-control" id="city">
<option value="">Select City</option>
</select>
</div>
</form>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
// Country dependent ajax
$("#country").on("change",function(){
var country = $(this).val();
if (countryid) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{countryid:countryid},
success:function(data){
$("#admin").html(data);
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
}else{
$('#admin').html('<option value="">Select Country</option>');
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
// state dependent ajax
$("#admin").on("change", function(){
var admin = $(this).val();
if (admin) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{admin:admin},
success:function(data){
$("#city").html(data);
}
});
}else{
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
});
</script>
The action.php file below
<?php
// Include the database config file
include_once 'ladb.php';
// Get country id through state name
$country = $_POST['country'];
if (!empty($country)) {
// Fetch state name base on country id
$query = "SELECT * FROM CityList WHERE country = {$country} GROUP BY admin_name_ascii";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['admin_id'].'">'.$row['admin_name_ascii'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}elseif (!empty($_POST['admin'])) {
$admin = $_POST['admin'];
// Fetch city name base on state id
$query = "SELECT * FROM CityList WHERE admin_id = {$admin}";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['cityid'].'">'.$row['city_ascii'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
Any help greatly appreciated!
Thanks to #zergski I note that one of references were defined (countryid in Line 53). DevTools is my new best friend.

how to avoid repetition of values in dropdown list while updating in php

I want to update "profile of a user" in php. There is a repetition of one value for two times in dropdown list. for example i take language value='Punjabi' from database but there is also a value placed in dropdown with name of 'Punjabi'.
The issue is simply that there is a repetition of value which i don't want.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?> '> <?php echo $queryArray["language"]; ?></option>
//for example, the value from database is "Punjabi"
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
</select>
<?php } ?>
when a value='Punjabi' from database is selected in dropdown list, the dropdown should not show the value='Punjabi' that is already placed in dropdown.
Remember: i have more than 1000 values in my dropdown(html) list.
screenshot
Instead of creating a new option according to the user data, Check if existing options are equal to user data:
<select name="language" id="language" >
<option value="Punjabi" <?php if ($queryArray["language"]=="Punjabi"){echo 'selected="selected"'} ?>>Punjabi</option>
<option value="Hindi" <?php if ($queryArray["language"]=="Hindi"){echo 'selected="selected"'} ?>>Hindi</option>
<option value="Urdu" <?php if ($queryArray["language"]=="Urdu"){echo 'selected="selected"'} ?>>Urdu</option>
</select>
If there are large number of options and you don't want to hard code these conditions, you can remove the second option using javascript on DOM ready:
$(document).ready(function(){
$('option[value="<?php echo $queryArray["language"] ?>"]').eq(1).remove();
})
skip the loop when value is equal to Punjabi, Urdu and Hindi.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<?php if($queryArray["language"]!="Punjabi" && $queryArray["language"]!="Urdu" &&
$queryArray["language"]!="Hindi") { ?>
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } ?>
I think you are doing it wrong way the correct way would be having a table which stored all the languages along with values
using selected attribute to achieve your objective
<?php
$result=mysqli_query($conn, "select * from profile where id=$firstPerson");
$queryArray1=mysqli_fetch_array($result);
$langOfUser=$queryArray1["language"];
?>
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from langtab");
while($queryArray=mysqli_fetch_array($result)){ ?>
<option value='<?php echo $queryArray["languageValue"];?> ' <?php if($langOfUser== $queryArray["languageValue"]){ echo 'selected';}?>> <?php echo $queryArray["languageName"]; ?></option>
<?php } ?>
</select>
You have to use if condition to display values in select option.
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){
if($queryArray["language"]!="Punjabi") {
$opval = "<option value=" . $queryArray["language"] . ">". $queryArray["language"]. " </option> "
echo $opval;
}
?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<option value="Urdu">Urdu</option>
</select>
So your problem is that you have html hardcoded options and database options. You need to merge them into one on that website.
So you can use some javascript
elements = [1, 2, 9, 15].join(',')
$.post('post.php', {elements: elements})
But you can fill your elements like this is you don´t want to write it by hand
$("#id select").each(function()
{
allOptionsInSelect.push($(this).val());
});
Than on php side you can do
$elements = $_POST['elements'];
$elements = explode(',', $elements);
And now you have html hardcoded select on server side. Now you need to check if it doesn´t already exist when you are printing from database
You can do that like this
if(in_array(value_from_database, $elements) {
// It is so skip
} else {
// It is not, so print it
}
You can use if elseif this way.
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?>'><?php echo $queryArray["language"]; ?></option>
<?php if ($queryArray["language"] == "Hindi") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } elseif ($queryArray["language"] == "Urdu") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<?php } elseif ($queryArray["language"] == "Punjabi") { ?>
<option value="Urdu">Urdu</option>
<option value="Hindi">Hindi</option>
<?php } ?>

Changing the select value in php

I’m making an interface with 2 select lists that are interconnected with each other, so what I want is:
If the user selects an option in the category dropbox the second select list will show all the options in that category.
<hmtl>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option>
<?php }
?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="txtsection" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) {?>
<option value="<?php echo $rows['Gradelvl_ID'];?>"><?php echo
$rows['Section_Name'];?></option> <?php }
?>
</select>
</hmtl>
I took some to write some code according to your problem. While writing this, I assumed that you have a relationship between the two tables where you have stored the categories and the options. I assumed that the relationship is using "Gradelvl_ID". I also assume that you have some knowledge in JavaScript, jQuery, and AJAX.
Based on that, I created the code below.
This would be your selection area.
<hmtl>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="cat" >
<?php
while ($rows = mysqli_fetch_array($queryResultsec)) { ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php } ?>
</select>
<label>Section</label>
<select class="form-control selcls" name="txtsection" id="options" ></select>
</body>
</html>
This script is using jQuery, so you need to link the jQuery library to you above page. Also you can have this script inside the first page using <script></script> tags or attached as a .js file separately.
$(document).ready(function(){
$(document).on('change', '#cat', function(){
$.ajax({
url: 'getOptions.php',
type: 'get',
data: {
catId: $(this).prop('id')
}
}).then(function (response) {
$('#options').html(response);
});
});
})
The code above will send the selected ID to the getOptions.php which will contain the PHPto select all the options according to the sent ID number from you options table. Then, if the selection is successful, it will send the data back which will be captured by the AJAX code above and draw the options inside the second drop down.
<?php
include_once('dbconnect.php');
//I'm not a big mysqli user
if(!empty($_GET["id"])){
$results = $conn -> prepare("SELECT * FROM <your table name> WHERE id = ?");
$results -> bind_param('i', $_GET["id"]);
$results -> execute();
$rowNum = $results -> num_rows;
if ($rowNum > 0){
while($optRows = $results -> fetch_assoc()){ ?>
<option id="<?php echo $rows['Gradelvl_ID'];?>"><?php echo $rows['Section_Name'];?></option>
<?php
}
}
}?>
Also, pay attention to the code above. I'm using prepared statements, which is a very good habit to get into. Look it up here.
As I said, I was assuming some part of the code and used the information given by you, and I hope you do some more research and make the code above work for you.
Try This Code:
$("#select1").change(function() {
if ($(this).data('options') === undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
Do one thing
1-Keep your second dropdown empty.
2-Call jquery ajax to get the first dropdown value on change
create a new page where only db connection is defied after that process the sql with respect to the first dropdown selected value
3-get the response to ajax method and get the output

How to change a second select list based on the first select list option when values are dynamic?

I have php page for vehicle search filter which have 2 types of vehicle that is RV's and campervans and also have two selects
<div class="fields">
<p>Vehicle Type</p>
<select class="car" name="car_type" id="car_type">
<option value="0">Select Vehicle</option>
<?php if(count($vehicleType) > 0 ){
foreach($vehicleType as $vt){ ?>
<option value="<?php echo $vt ?>" <?=isset($_GET['car_type'])&&$_GET['car_type']==$vt?'selected':'';?> ><?php echo $vt ?></option>
<?php }
} ?>
</select>
</div>
<div class="fields">
<p>Total No. of Passengers*</p>
<select class="half" name="passengers" id="passengers">
<option>No. of Passengers</option>
<option <?php if(#$_REQUEST['passengers'] == 1){?>selected<?php }?>>1</option>
<option <?php if(#$_REQUEST['passengers'] == 2){?>selected<?php }?>>2</option>
<option <?php if(#$_REQUEST['passengers'] == 3){?>selected<?php } ?>>3</option>
<option <?php if(#$_REQUEST['passengers'] == 4){?>selected<?php }?>>4</option>
<option <?php if(#$_REQUEST['passengers'] == 5){?>selected<?php }?>>5</option>
<option <?php if(#$_REQUEST['passengers'] == 6){?>selected<?php }?>>6</option>
<option <?php if(#$_REQUEST['passengers'] == 7){?>selected<?php }?>>7</option>
<option <?php if(#$_REQUEST['passengers'] == 8){?>selected<?php }?>>8</option>
</select>
</div>
How do I do that with jQuery or php if I choose "Rv" in the first select? The second select would show me 8 passengers . If I choose Campervan in the first select, the second select would show me 5 passengers..
I would probably do something along these lines:
<?php
$number_of_passengers = 8;
if(!empty($_REQUEST['car_type'])) {
$number_of_passengers = $_REQUEST['car_type'] == 'Campervans' ? 5 : 8;
}
$passengers = 0;
if(!empty($_REQUEST['passengers'])){
$passengers = (int) $_REQUEST['passengers'];
}
?>
<select class="car" name="car_type" id="car_type">
<option value="0">Select Vehicle</option>
<option value="RV/Motorhome">RV/Motorhome</option>
<option value="Campervans">Campervans</option>
</select>
<select class="half" name="passengers" id="passengers">
<option>No. of Passengers</option>
<?php
for($i = 1; $i <= $number_of_passengers; $i++) {
?>
<option
<?php
if($i == $passengers) {
echo ' selected ';
}
?>
>
<?php echo $i ?>
</option>
<?php
}
?>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$('#car_type').change(function() {
$("#passengers").children().removeAttr("selected");
if ($(this).val() === 'Campervans') {
$('#passengers option:nth-child(n+7)').hide();
} else {
$('#passengers option').show();
}
});
</script>
There are cleaner ways of doing this but this should serve to get the point across.
Few things to note about the PHP:
See how I check if the $_REQUEST key is available using empty - this avoids having to use # which is generally not a good idea.
I am using a loop to echo the options in the passenger select to avoid code repetition because typing that out 8 times is boring ;-)
Hope this helps!
yes you need to add javascript code for that.
insert below code in your page and check if this is what you want?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$('.car').on('change', function(){
if($(this).val() === 'RV/Motorhome'){
$('.half').find('option').show()
}else if($(this).val() === 'Campervans'){
$('.half').find('option').slice(6).hide();
}
})
</script>

Values not inserting into database table

I am trying to insert the values from drop-down and text box throug web page.
first there will be one drop down box that has numbers from 1 to 25..
when i select the number from the dropdown, the corresponding textboxes and dropdown boxes are created.
But when i enter the data and click the submit button,the values are not going to database, instead only the last row values are inserting into database.
for example:
say i have selected 4 from number dropdown, now 4 rows with textbox and dropdown box appears.
when i enter the data in the textbox and select value from dropdown and click submit. the last row values are getting inserted 4 times.
i want it to insert the values correctly...How can i solve this.?
here is the code i am using..
code:
<html>
<head>
<link rel="stylesheet" href="css/common.css" type="text/css">
<link rel="stylesheet" type="text/css" href="css/page.css">
<link rel="stylesheet" type="text/css" href="css/button.css">
<link href="css/loginmodule.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/jquery.js"></script>
<script type='text/javascript' src='js/jquery.autocomplete.js'></script>
<link rel="stylesheet" type="text/css" href="css/jquery.autocomplete.css" />
<script type="text/javascript">
$().ready(function() {
$("#Fname").autocomplete("get_course_list.php", {
width: 260,
matchContains: true,
//mustMatch: true,
//minChars: 0,
//multiple: true,
//highlight: false,
//multipleSeparator: ",",
selectFirst: false
});
});
</script>
<script>
function showUser(str) {
if(str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gettheater.php?q="+str,true);
xmlhttp.send();
}
</script>
<script type="text/javascript">
function create(param) {
'use strict';
var i, target = document.getElementById('screens');
target.innerHTML = '';
target.innerHTML = '<input name="RowCount" value="' + param + '" hidden />';
for(i = 0; i < param; i += 1) {
target.innerHTML +='</br>';
target.innerHTML +='New Movie '+i+' ';
target.innerHTML += '<input type="text" name="Fname">';
target.innerHTML +=' '+'Language '+' ';
target.innerHTML += "<?php
try {
$dbh = new PDO('mysql:dbname=theaterdb;host=localhost','tiger','tiger');
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$sql = 'SELECT language FROM languages;';
$sth = $dbh->prepare($sql);
$sth->execute();
echo "<select name='language' id='course'>";
echo "<option>----Select Language----</option>";
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['language'] ."'>" . $row['language']. " </option>";
}
echo "</select>";
?>";
target.innerHTML +='</br>';
target.innerHTML +='</br>';
}
}
</script>
<style>
#screens{
color:black;
}
</style>
</head>
<body>
<h1>Welcome <?php echo $_SESSION['SESS_FIRST_NAME'];?></h1>
My Profile | Logout
<p>This is a password protected area only accessible to Admins. </p>
<center>
<div class="pan"><br><br>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" autocomplete="off">
<div class="head">Update Theater Information</div>
<table>
<tr>
<td><label for="screens">New Movies Released</label></td>
<td>
<select id="select" onchange='javascript:create(this.value);' name="range">
<option>--Select Number Of New Movies Released--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
<option value="15">15</option>
<option value="16">16</option>
<option value="17">17</option>
<option value="18">18</option>
<option value="19">19</option>
<option value="20">20</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<div id="screens">
</div>
</td>
<td></td>
</tr>
<tr>
<td></td>
<td><input type="submit" class="button" name='submit' value="Submit" /></td>
</tr>
</table>
</form><br><br>
</div>
<?php
mysql_connect("localhost", "tiger", "tiger") or die(mysql_error());
mysql_select_db("theaterdb") or die(mysql_error());
for ($i=0; $i < $_POST["range"] ; $i++)
{
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
}
?>
</center>
</body>
</html>
You should change you name to array like
target.innerHTML += '<input type="text" name="Fname[]">';
And also in insert query should be
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('".$_POST['Fname'][$i]."','".$_POST['language']."') ") or die(mysql_error());
1.Use mysqli_* function instead of mysql_* function...
2. What is error showing up.
If you have insertion query on same page then try it:.....
<?php
if(isset($_POST['submit'])
{
mysql_connect("localhost", "tiger", "tiger") or die(mysql_error());
mysql_select_db("theaterdb") or die(mysql_error());
for ($i=0; $i < $_POST["range"] ; $i++)
{
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
}
}
?>
It will triger your query when submit button will hit.... may this help
Use this
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('".$_POST['Fname']."','".$_POST['language']."') ") or die(mysql_error());
instead of
$query = mysql_query("INSERT INTO movie (movie_name,language) VALUES('$_POST[Fname]','$_POST[language]') ") or die(mysql_error());
You must keep php code outside of quote and Concate them
2.If The index of $_POST Array is string then it must be with quote. (e.x: $_POST[language] it must be $_POST['language']
Thank god....I resolved My issue.....i used the same logic that was applied to first text box...
and now the dropdown values are also getting inserted....
i added array to language[]
echo "<select name='language[]' id='course'>";
and added the $i in loop
.$_POST['language'][$i]
Thanks all for helping me.....
HaPpY CoDiNg....
I don't want to be an ass, but I would suggest cleaning things up and seperating the JavaScript, jQuery and PHP even loose JavaScript AJAX and use jQuery AJAX. It's no surprise code like this is giving you bugs.

Categories

Resources