Genereting 'n' html inputs based on database variable - javascript

My intention is to create a form in HTML where the user could register some quality features of a product. The number of features to be registered varies according to the model, this info is registered on a table in SQL.
So far I manage to generate the inputs, but it is very fast, the user cannot fill all the inputs.
## query to get the product information from database ##
$query_list = "SELECT * FROM data_products";
$result_list = mysqli_query($conn, $query_list);
## get the number of rows
$query_data_rows = mysqli_query($conn, $query_list);
$data_rows = mysqli_fetch_array($query_data_rows);
?>
## here is the first form, where the user selects the product model,
## therefore it should query the number of raws (n) registered on the table
<div class="container">
<form action="" method="post" onsubmit="getdata()">
<select name="select1">
<option value=" "> </option>
<?php
while ($row = mysqli_fetch_array($result_list)) {
echo "<option value='" . $row['customer_Id'] . "'>" . $row['customer_Id'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="Go"/>
</form>
</div>
## here my intention is to return the (n) number of input fields
## it correctly displays the number of input fields, but it is very fast
## I am missing something here
<?php
if(isset($_POST['select1'])){ ?>
<form id="form" action="" method="post">
<input type="submit">
</form>
<?php
}
?>
## I am almost zero skilled on Javascript,
## but browsing on the world web wide and reading the documentation of the language
## I got the code below.
<script>
function getdata() {
var no = <?php echo $data_rows['number'] ;?>;
for(var i=0;i<no;i++) {
var textfield = document.createElement("input");
textfield.type = "text";
textfield.value = "";
textfield.name = i+1 + "a"
textfield.placeholder = i+1
document.getElementById('form').appendChild(textfield);
}
}
</script> ```

Here what actually happening is that when you are submitting the form getdata() function is called till the it get submitted, after submission is done the content called by function disappears, in order to avoid this use return false statement at the end of the function.
<div class="container">
<form action="" id="form_id" method="post" onsubmit="return getdata()">
<select name="select1">
<option value=" "> </option>
<?php
//accesing the database table
$query_list = "SELECT * FROM `data_products`";
$result = mysqli_query($conn, $query_list);
//to get rows
$data_rows = mysqli_num_rows($result);
echo $data_rows;
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['srno'] . "'>" . $row['srno'] . "</option>";
}
?>
</select>
<input type="submit" name="submit" value="go"/>
</form></div>
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST' ){
echo '<form id="form" action="" method="post">
<input type="submit">
</form>';
}
?>
<script>
function getdata() {
var no = <?php echo $data_rows;?>;
for(var i=0;i<no;i++) {
var btn = document.createElement("INPUT");
btn.type = "text";
btn.value = "";
btn.name = i+1 + "a"
btn.placeholder = i+1
document.getElementById('form').appendChild(btn);
}
return false;
}
</script>
This is working. Here I have made some changes in your code like replacing 'textfield' with 'btn', 'customerid' with 'srno' (for easy understanding) and avoid using php again and again.

Related

How to I save a list group in SQL database?

I have code in html that adds data in a list by selecting the data in the combo box and clicking on the add button. I am encountering an error "undefined index: subjectlist" when submitting the form. Appreciate your advise this? Thank you. I am still an newbie in web programming.
<h4>Subjects</h4>
<ul class="list-group list" id='subjectlist' name='subjectlist' >
</ul>
<div class="form-group">
<input class="submit" name="submit" type="submit" value="Save">
</div>
</form>
<button class="add_field_button" onclick="getsubject()">Add Subject</button>
<button class="add_field_button" onclick="removesubject()">Remove Subject</button>
<script>
function getsubject(){
var ul = document.getElementById("subjectlist");
var candidate = document.getElementById("st");
var SelectedValue = candidate.options[candidate.selectedIndex].text;
var li = document.createElement("li");
li.setAttribute('class',"list-group-item");
li.setAttribute('id',"subjectlistitem");
li.appendChild(document.createTextNode(SelectedValue));
ul.appendChild(li);
}
</script>
<?php
if(isset($_POST['submit'])){ // Fetching variables of the form which travels in URL
$sectioncode = $_POST['sc'];
$sectiongroup = $_POST['ccg'];
$selectedsubject = $_POST['st'];
$subjectlist = $_POST['subjectlist'];
$i = 0;
foreach ($subjectlist as $qst) {
$sql = "INSERT INTO sectionsubject(sectioncode, subjectcoden) VALUES ('" . $csectioncode . "',
'" . $subjectlist[$i] . "')";
if ($link->query($sql) === TRUE) {
echo "success";
} else {echo "error" . $link->error;}
$i++;}
}
?>
because $_POST,$_GET only deal with <input> tags and <ul>,<li> are not input methods.

Get data MySQL DB and display on in HTML

How would I code into my program using PHP/JavaScript and HTML/CSS to display data from a database I made in MySQL Monitor on the blue section below:
I made buttons that use PHP to go into the database and show the data on the HTML page:
HTML:
<form action="fullridez.php" method="post">
<h4 id="Filter">GPA</h4>
<input id="FilterBox" name="gpa" type="text"/>
<h4 id="Filter">Amount</h4>
<input id="FilterBox" name="amount" type="text"/>
<h4 id="Filter">School</h4>
<input id="FilterBox" name="school" type="text"/>
<input type="submit" id="FilterBox" name="myForm" onkeypress="checkEnter()" ><img src="search.png" width=15 height=15 /></button>
</form>
<script>
</script>
PHP:
<?php
if(isset($_POST['myForm'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarshiplist";
$conn = mysqli_connect($servername, $username, $password, $database);
$gpa = $_POST['gpa'];
$amount = $_POST['amount'];
$count = "SELECT * FROM scholarships";
$result = mysqli_query($conn, $count);
if ($result->num_rows > 0) {
$sql = "SELECT * FROM scholarships WHERE GPA <= " . $gpa . " AND Amount <= "
. $amount;
if ($result = mysqli_query($conn, $sql)) {
while ($row=mysqli_fetch_row($result)) {
for($i = 0; $i < count($row); $i++) {
echo $row[$i] . '<br>';
}
}
}
} else {
echo "0 results";
}
$conn->close();
}
SQL:
USE ScholarshipList;
CREATE TABLE Scholarships
(
id int unsigned NOT NULL auto_increment,
School varchar(500) NOT NULL,
GPA decimal(10,2) NOT NULL,
Amount decimal(10,2) NOT NULL,
PRIMARY KEY (id)
);
I am using XAMPP
When I click the button on the HTML file it bring me to the PHP page and all I see is the PHP code. I don't want it to go to the page but stay on the same page showing the data below the buttons.
This is what the page looks like so far
page
What am I doing wrong?
If your HTML form is contained within the 'fullridez.php' file and you are posting the form inputs to that same file, then you need to have some PHP where you'd like to output to be checking for results and then looping through those results while echoing them out:
<table>
<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td></tr>
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<tr><td>"
. $row['col_1'] . "</td><td>"
. $row['col_2'] . "</td><td>"
. $row['col_3'] . "</td></tr>";
}
?>
</table>
You can build a wireframe div table with for loop:
<?php
$num_rows = mysql_num_rows($result);
for ($i=0;$i<$num_rows;$i++) {
//loop through all rows of data
$row = mysql_fetch_assoc($result); // your data is now: $row['fieldName']
?>
<div>
GPA <input name="" value="<?php echo($row['gpa'])?>;" type="text">
AMOUNT <input name="" value="<?php echo($row['amount'])?>;" type="text">
SCHOOL <input name="" value="<?php echo($row['school'])?>;" type="text">
</div>
<?php
} //end of the loop
?>

PHP mysql - Display comma separated value from the database in tabular form

I am complete beginner
I want to display comma separated values from database in tabular form
From the below image link we can see how the data is getting added separated by commas:
I want to display in tabular form in html/php page just like below:
This is my html page below:-
<form action="insert.php" method="POST">
<div id="items">
<input type="text" placeholder="name" name="user_name[]" />
<input type="text" placeholder="email" name="user_email[]" />
</div>
<input type="button" value="add entry" id="add"/>
<input type="submit" value="submit"/>
Javascript file for adding additional input:-
$(document).ready(function(){
$("#add").click(function (e){
event.preventDefault()
$('#items').append('<div><input type="text" placeholder="Name" name="user_name[]" ><input type="text" placeholder="email" name="user_email[]">'
+'<input type="button" value="delete" id="delete"/></div>');
});
$('body').on('click','#delete',function(e){
$(this).parent('div').remove();
});
});
And below is the PHP code for inserting to database:-
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dynamic", $con);
$user_name = $_POST["user_name"];
$value = implode(',', $user_name);
$user_email = $_POST["user_email"];
$valueone = implode(',', $user_email);
$sql="INSERT INTO dynamicdata (user_name, user_email)
VALUES
('$value','$valueone')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Just fetch the data from the table and explode both username and useremail to make array and just loop it and diplay the values.
Below pasted code may help you.
<?php
$ArrUserName=explode($username,','); //exploding the coma separated username to make array of user names
$ArrUserEmail=explode($username,',');//exploding the coma separated user email to make array of user email
echo '<table><tr><td>Name</td><td>EMAIL</td></tr>';
for($i=0;$i<count($ArrUserName);$i++){
echo "<tr>";
echo"<td>".$ArrUserName[$i]."</td>"; //display user name
echo"<td>".$ArrUserEmail[$i]."</td>"; // diaplay user email
echo"</tr>";
}
?>
Please understand this nd try to implement in your code.
Ideally, you would want the username and email stored in a new row for each user. This would make it a lot simpler for yourself.
However, try something like:
<?php
$query = mysql_query('SELECT * FROM dynamicdata LIMIT 1', $con);
$results = mysql_fetch_assoc($query);
$usernames = explode(',', $results['user_name']);
$emails = explode(',', $results['user_email']);
//Now we should be able to loop over them.
for($row = 0; $row <= count($usernames); $row++) {
echo $usernames[$row] . ' : ' . $emails[$row];
}
I haven't had chance to test this, but hopefully it works.

PHP + MYSQL instant search with radio button filtering

I have with the help of this guide https://www.youtube.com/watch?v=_AqM9U3mi9A created a working search form that displays instant search results (without having to press submit button) with PHP and MYSQL.
Then I wanted to filter the search results depending on what radio button is pressed. Now I also got this to work (partly with the help of this guide https://www.youtube.com/watch?v=DVS4qoB98U8) but ONLY when pressing submit on my search form. It does not work with instant search results for some reason, and that is my problem.
index.php (form):
<form class="form-custom" role="search" action="index.php" method="POST">
<div class="form-group">
<label for="all" class="radio-btn">
<input id="all" class="radio-custom" type="radio" name="searchfilter" value="all" checked="checked"> ALL
</label>
<label for="sports" class="radio-btn">
<input id="sports" class="radio-custom" type="radio" name="searchfilter" value="sports"> SPORTS
</label>
<label for="e-sports" class="radio-btn">
<input id="e-sports" class="radio-custom" type="radio" name="searchfilter" value="e-sports"> E-SPORTS
</label>
<label for="show-business" class="radio-btn">
<input id="show-business" class="radio-custom" type="radio" name="searchfilter" value="show-business"> SHOW BUSINESS
</label>
</div>
<div class="form-group">
<input type="text" name="search" autocomplete="off" class="form-control form-control-custom" placeholder="Search..." onkeyup="searchq();">
<button type="submit" name="submit" value="" class="btn btn-default btn-form-custom">Submit</button>
</div>
</form>
<div class="test" id="output">
<!-- this is where instant search results are supposed to appear -->
</div>
index.php (jquery - requiered for instant search results to work):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php",{searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}
</script>
search.php (PHP code):
<?php
include_once("connect.php");
$output = '';
if (isset($_POST['searchVal']) && isset($_POST['searchfilter']) && trim($_POST['searchVal']) != '' && strlen('searchVal') > 3 ){
$searchq = $_POST['searchVal'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
if($_POST['searchfilter'] == "all") {
$sqlCommand = "(SELECT * FROM sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM e_sports WHERE Title LIKE '%$searchq%') UNION (SELECT * FROM show_business WHERE Title LIKE '%$searchq%')";
} else if($_POST['searchfilter'] == "sports") {
$sqlCommand = "SELECT * FROM sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "e-sports") {
$sqlCommand = "SELECT * FROM e_sports WHERE Title LIKE '%$searchq%'";
} else if($_POST['searchfilter'] == "show-business") {
$sqlCommand = "SELECT * FROM show_business WHERE Title LIKE '%$searchq%'";
}
$query = mysql_query($sqlCommand) or die(mysql_error());
$count = mysql_num_rows($query);
if($count == 0){
$output .= '<p class="p-nof">No results found</p>';
}else{
$output .= '<ul ="dropdown">';
$output .= '<p>Search results: '.$count.'</p>';
while($row = mysql_fetch_array($query)){
$title = $row['Title'];
$url = $row['url'];
$id = $row['id'];
$output .= '<a class="searchresult" href="'.$url.'"><li> '.$title.'</li></a>';
}
$output .= '</ul>';
}
}
echo($output);
?>
Thanks in advance for any help!
EDIT:
I changed the javascript to the following:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchfilterVal: searchFilter}, function(output){
$("#output").html(output);
});
}
</script>
With this change the instant search results are working like before but the radio button filtering is not working. It seems that it's only using the data from the first radio input and ignoring the rest. When I click the other radio buttons it continues to use the data from the one listed first in the form. It does not change as I click.
I still need help with this! Thanks in advance!
Adjust your JS to post the value of searchFilter
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
var searchFilter = $("input[name='searchfilter']").val();
$.post("search.php",{searchVal: searchTxt, searchFilter: searchfilter}, function(output){
$("#output").html(output);
});
}
</script>

Set input field value in Javascript value store in PHP variable

I'm creating a dynamic text field for the answer of a question, which the user selects from the answer field display. When the user enters the answer and submits the form, the php code stores the user's answer in php variable named $ans1. When the form reloads after submitting, the answer doesn't show. I want to show that answer in the field note that I'm creating dynamically. The code is given below:
<?php
$ques1Err = $ans1Err = '' ;//variable to display error like field required
$ques1 = $ans1 = '' ;// variable to store value what user enter or select
$qans1 = 0;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty($_POST['q1'])){
$ques1Err = 'Security Question Required' ;
}
else{
$ques1 = $_POST['q1'];
$qans1 = 1;
}
if(empty($_POST['ans1'])){
$ans1Err = 'Answer Required' ;
}
else{
$ans1 = check_input($_POST['ans1']);
if(!preg_match("/^[a-zA-Z ]*$/",$ans1)){
$ans1Err = "Only letters and white space allowed";
}
}
}
?>
<html>
<head>
<script>
// dynamically add input field for the user to enter the answer of question
function add_txt_field(){
var inpdiv = document.createElement("DIV");
inpdiv.setAttribute("class","input-txt");
var input = document.getElementById("ans1_txt-input");
input.appendChild(inpdiv);
var inp = document.createElement("INPUT");
inp.setAttribute("type","text");
inp.setAttribute("id","ans1");
inp.setAttribute("class","txt-box");
inp.setAttribute("name","ans1");
inp.setAttribute("value","");
inpdiv.appendChild(inp);
}
</script>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="post">
Security Question<select class="txt-box" onchange="add_txt_field()" id="q1" name="q1">
<option value="<?php echo $ques1 ?>"><?php echo $ques1 ?></option>
<option value="What was your childhood nickname?">What was your childhood nickname?</option>
<option value="What is your grandmother's first name?">What is your grandmother's first name?</option>
<option value="What school did you attend for sixth grade?">What school did you attend for sixth grade?</option>
</select><span class="error"> <?php echo $ques1Err;?></span></div>
<div id="ans1_txt-input"></div>
<?php
if($qans1 == 1){
echo '<script type="text/javascript"> add_txt_field() </script>';
***// here's the problem***
echo '<script> oFormObject.elements["ans1"].value = "$ans1" </script>' ;
}
?>
<button id="create" name="create" type="submit">Create</button>
</form>
</body
</html>
You have a problem in your javascript:
echo '<script> oFormObject.elements["ans1"].value = "$ans1" </script>' ;
Change it to this
echo '<script> document.getElementById("ans1").value = "'.$ans1.'"; </script>' ;
But you can also do something from php inside the form like:
<?php
if (isset($ans1)) {
echo '<input type="text" name="ans1" id="ans1" value="'.$ans1.'"/>';
}
?>
Instead of using javascript

Categories