Populate text input field automatically based on dropdown selection mysqli - javascript

I've created a dropdown list that is populated by data from my mysql db and programmed using php. What I need to do is populate a text field based on the selection made in the dropdown. Unfortunately, my question differs from the others asked on this forum because most are simply typing all of their options into a html form. Mine are contained within a table and I do not want to save the content in the text field to my database...it will be used for user reference only.
I've read a plethora of forum posts on this site and numerous others and have tried using jquery, javascript, and ajax scripts, but for some reason the only thing I've been successful in getting to appear in the text field is the id of the corresponding item selected from the dropdown list. I think it is important to know that both fields come from the same table in the db, so I can't figure out why it is so difficult to automatically populate the field. I would like to use javascript because I want everything in this one file.
This is the code in the php form:
<?php
'<div id="trxdetailstable">';
echo '<table align="center" width="750px" cellspacing="0" border=".5px" ! important><tr>
<th>Movie Title</th><th>Category</th><th>Price</th></tr>';
echo '<td align="left" width="8%" height="25px">';
$ddlquery4 = "SELECT id, title, categoryname FROM dvd ORDER BY title ASC";
$ddlresult4 = mysqli_query($dbc, $ddlquery4) or die("Bad SQL: $ddlquery4");
echo '<select class="dropdown" name="dvdid" id="dvdid" size="1" onchange="updatecat()">';
while($ddlrow4=mysqli_fetch_array($ddlresult4, MYSQLI_ASSOC)){
$categoryname = $ddlrow4['categoryname'];
echo "<option data-categoryname='' value='".$ddlrow4['id']."'>" . $ddlrow4['title'] . "</option>";
} //End while statement
echo "</select>";
echo '</a></td>';
echo '<td align="left" width="10%">';
echo '<input required id="categoryname" name="categoryname" type="text" readonly="readonly">';
echo '</a></td>';
This is the code I currently have in the html head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
This is the code that is currently generating no results (text field is left blank after a dropdown item is selected):
$('#dvdid').change(function(e){
var optionChange = $('#dvdid option:selected').text();
$('#categoryname').val(optionChange);
});
</script>
And this is the code that actually gave me the primary key (id) for the item selected in the dropdown list (I want it to be the categoryname):
<script>
function updatecat(id){
if (id === "") {
$("input[name=categoryname]").val("");
} else {
$("input[name=categoryname]").val(id);
}
}
</script>
I have about 3 other scripts I've tried, but they all left the text (category) field blank.
Any advice would be appreciated. Please keep in mind all of my data is generated from a database not manually entered. Thanks.

You have repeated rows and do not use ID atrribute with them , you can use class like this :
$('select.dropdown').change(function(e){
var optionChange = $(this).find('option:selected').text();
$(this).closest("tr").find(".categoryname").val(optionChange);
});
and your php code should be something like this :
<?php
'<div id="trxdetailstable">';
echo '<table align="center" width="750px" cellspacing="0" border=".5px" ! important>
<tr>
<th>Movie Title</th>
<th>Category</th>
<th>Price</th>
</tr>';
echo '<tr>
<td align="left" width="8%" height="25px">';
$ddlquery4 = "SELECT id, title, categoryname FROM dvd ORDER BY title ASC";
$ddlresult4 = mysqli_query($dbc, $ddlquery4) or die("Bad SQL: $ddlquery4");
echo '<select class="dropdown" name="dvdid" id="dvdid" size="1" onchange="updatecat()">';
while($ddlrow4=mysqli_fetch_array($ddlresult4, MYSQLI_ASSOC)){
$categoryname = $ddlrow4['categoryname'];
echo "<option data-categoryname='' value='".$ddlrow4['id']."'>" . $ddlrow4['title'] . "</option>";
} //End while statement
echo "</select>";
echo '</a></td>';
echo '<td align="left" width="10%">';
echo '<input required class="categoryname" id="categoryname" name="categoryname" type="text" readonly="readonly">';
echo '</a></td></tr>';

For others using html/php and searching for a way to auto populate a text field based on the selection made in a dropdown fed from data held in their mysql db (and only use one file) here is what FINALLY worked for me:
In html head:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
In html/php portion:
echo '<td align="left" width="8%" height="25px">';
$ddlquery4 = "SELECT id, title, categoryname FROM dvd ORDER BY title ASC";
$ddlresult4 = mysqli_query($dbc, $ddlquery4) or die("Bad SQL: $ddlquery4");
echo '<select type="text" class="dropdown" name="dvdid" id="dvdid" size="1" onchange="updatecat()">';
while($ddlrow4=mysqli_fetch_array($ddlresult4, MYSQLI_ASSOC)){
echo "<option value='".$ddlrow4['id']."' data-categoryname='".$ddlrow4['categoryname']."'>" . $ddlrow4['title'] . "</option>";
} //End while statement
echo "</select>";
echo '</a></td>';
echo '<td align="left" width="10%">';
echo '<input type="text" id="categoryname" name="categoryname" readonly="readonly" value="">';
echo '</a></td>';
In HTML area at end of file:
<script>
$('#dvdid').change(function() {
selectedOption = $('option:selected', this);
$('input[name=categoryname]').val( selectedOption.data('categoryname') );
});
</script>
I sincerely hope this prevents someone else from having to go the days of trial and error and endless searching and reading that I went through.

Related

Post recordset to a table, then select one row and post to another page

I recently ran into a problem I wasn't quite sure how to solve. Sharing it here in case it helps someone else.
Use Case: User enters a string in a search box on a PHP page. On submit, the page queries the database and then posts results to a table on the same page. User then selects a single record with a radio button and needs to post only that record to a different PHP page. The second page does not have access to the database.
I took the actual page and created a sample page for clarity and testing, since the original had about 15 table columns.
<div class="container">
<div class="row" style="margin-top: 1rem;">
<div class="col-sm">
<form action="" method="post">
<table class="fit" id="entry">
<tr>
<td class="fit"><label for="start">Planet (try <strong>Caprica</strong> or <strong>Picon</strong>): </label></td>
</tr>
<tr>
<td class="fit"><input type="test" id="planet" name="planet" required autofocus /></td>
</tr>
</table>
<input class="btn btn-primary" type="submit" value="Get Characters" />
</form>
</div>
</div>
</div>
<div class="container" style="margin-top: 2rem;">
<div class="row">
<div class="col-sm">
<?php
require_once('./resources/pdo.php');
if ( isset($_POST['planet']) ) {
$planet = strtolower($_POST['planet']);
$pdo = new myPDO('phppostpost');
try {
$stmt = $pdo->prepare('CALL devCharacters(?)');
$stmt->bindParam(1, $planet, PDO::PARAM_STR);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
die("Error occurred: " . $e->getMessage());
}
?>
<div class="table-responsive">
<table class="table table-striped table-hover">
<thead class="thead-light">
<tr>
<th class="fit">Select</th>
<th class="fit" scope="col">Customer First</th>
<th class="fit" scope="col">Customer Last</th>
<th class="fit" scope="col">Planet</th>
</tr>
</thead>
<tbody>
<?php while ($r = $stmt->fetch()): ?>
<tr>
<?php echo "<td class='fit'><input type='radio' id='cust-" . $r['customer_id'] ."' name='cust-id' value='". $r['customer_id'] . "' </td>"; ?>
<?php echo "<td class='fit'>" . $r['first_name'] . "</td>"; ?>
<?php echo "<td class='fit'>" . $r['last_name'] . "</td>"; ?>
<?php echo "<td class='fit'>" . $r['origin_planet'] . "</td>"; ?>
</tr>
<?php endwhile; ?>
</tbody>
</table>
</div>
<input class="btn btn-primary" onclick="getSelectedRowData();" type="submit" value="Send" />
<?php } ?>
</div>
</div>
</div>
As a relatively new developer, I couldn't figure out how to (1) grab just the selected row and (2) post data on submit from just that row, rather than from the the original search form.
After much Googling, as well as a kick in the pants from a Stack Overflow user who reminded me I needed to actually research for more than 20 minutes (thank you!), I was able to solve it.
I'll post the answer below for anyone else who runs into a similar problem.
To solve this, I used JavaScript to grab the selected row. In order to efficiently grab the correct record, I updated each TD element to have a unique, dynamically-generated ID:
<?php echo "<td class='fit' id='fname-" . $r['customer_id'] ."'>" . $r['first_name'] . "</td>"; ?>
<?php echo "<td class='fit' id='lname-" . $r['customer_id'] ."'>" . $r['last_name'] . "</td>"; ?>
<?php echo "<td class='fit' id='planet-" . $r['customer_id'] ."'>" . $r['origin_planet'] . "</td>"; ?>
I also gave the table body an ID so I could grab it quickly without grabbing a parent, then children, etc.:
<tbody id="results-body">
Finally, here's the JavaScript.
function getSelectedRowData() {
const tableRowArray = Array.from([document.getElementById('results-body')][0].rows);
let custFirst;
let custLast;
let custPlanet;
tableRowArray.forEach((tableRow, i) => {
cellButton = tableRow.getElementsByTagName('input');
if (cellButton[0].checked == true ) {
const rowID = cellButton[0].id.split('-').pop();
custFirst = document.getElementById('fname-' + rowID).innerHTML;
custLast = document.getElementById('lname-' + rowID).innerHTML;
custPlanet = document.getElementById('planet-' + rowID).innerHTML;
}
});
/* Build a hidden form solution to prep for post.
Source: https://stackoverflow.com/questions/26133808/javascript-post-to-php-page */
let hiddenForm = document.createElement('form');
hiddenForm.setAttribute('method', 'post');
hiddenForm.setAttribute('action', 'newpage.php');
hiddenForm.setAttribute('target', 'view');
const fieldCustFirst = document.createElement('input');
const fieldCustLast = document.createElement('input');
const fieldCustPlanet = document.createElement('input');
fieldCustFirst.setAttribute('type', 'hidden');
fieldCustFirst.setAttribute('name', 'custFirst');
fieldCustFirst.setAttribute('value', custFirst);
fieldCustLast.setAttribute('type', 'hidden');
fieldCustLast.setAttribute('name', 'custLast');
fieldCustLast.setAttribute('value', custLast);
fieldCustPlanet.setAttribute('type', 'hidden');
fieldCustPlanet.setAttribute('name', 'custPlanet');
fieldCustPlanet.setAttribute('value', custPlanet);
hiddenForm.appendChild(fieldCustFirst);
hiddenForm.appendChild(fieldCustLast);
hiddenForm.appendChild(fieldCustPlanet);
document.body.appendChild(hiddenForm);
// Post
window.open('', 'view');
hiddenForm.submit();
}
This worked for me, but I'm sure there's a better way to do this. Hopefully this (1) helps someone else and (2) a better solution is posted!
Here's a working demo: https://postfrompost.paulmiller3000.com/
Full source here: https://github.com/paulmiller3000/post-selected-from-post

HTML Send selected option to PHP via Ajax on same page

What I want to acheive:
I have a HTML/PHP page where I display the home page of the website. I have a highscore section on this page. The data for the highscore page is retrived from a database. There is a Select box where you can choose how the highscores are sorted.
The highscore section on the page
I want to be able to select an option from the dropdown. When an option is selected, the way that the data is displayed changes dynamically, without the page refreshing.
Here is the code on the home.php page (Where the highscore section is)
<div class="third third-center">
<h2>Highscores</h2>
<div class="sortby">
<form id="" method="post" action="home.php">
<select id="selectForm" name="sort">
<option value="score ASC">Score Ascending</option>
<option value="score DESC">Score Descending</option>
<option value="userName ASC">Name Ascending</option>
<option value="userName DESC">Name Descending</option>
</select>
</form>
</div>
<div class="inner">
<table>
<tr>
<th style="font-size: 20px">Position</th>
<th style="font-size: 20px">Name</th>
<th style="font-size: 20px">Score</th>
</tr>
<?php
$i = 0;
$choice = "score ASC";
$search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));
while($row = mysqli_fetch_array($search)){
$i++;
echo "<tr>";
echo "<th>" . $i . "</th>";
echo "<th>" . $row['userName'] . "</th>";
echo "<th>" . $row['score'] . "</th>";
echo "</tr>";
}
?>
</table>
</div>
</div>
I am using the Mysqli_Query to get all the data from the database. I am passing in a variable in place of the ORDER BY so that I can change the way the data is retrieved.
I know I can use Ajax to get the data, but Im not sure how to do it, I have looked at many other questions posted on this forum.
Any help would be greatly appreciated!
Use JQuery AJAX something like so:
Make two pages one where you display data(index.php) and other from where you fetch data (process.php).
The content of index.php would be something like:
<div class="third third-center">
<h2>Highscores</h2>
<div class="sortby">
<form id="" method="post" action="home.php">
<select onChange="getData();" id="selectForm" name="sort">
<option value="score ASC">Score Ascending</option>
<option value="score DESC">Score Descending</option>
<option value="userName ASC">Name Ascending</option>
<option value="userName DESC">Name Descending</option>
</select>
</form>
</div>
<div class="inner">
<table>
<thead>
<th>
<th style="font-size: 20px">Position</th>
<th style="font-size: 20px">Name</th>
<th style="font-size: 20px">Score</th>
</th>
</thead>
<tbody id="data"></tbody>
</table>
</div>
</div>
The code of process.php should be something liek:
<?php
$i = 0;
if($_REQUEST['sortBy'] == "score ASC")
{
$choice = "score ASC";
}
else if ()//and so on
$search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice) or die(mysqli_error($connect));
while($row = mysqli_fetch_array($search)){
$i++;
echo "<tr>";
echo "<th>" . $i . "</th>";
echo "<th>" . $row['userName'] . "</th>";
echo "<th>" . $row['score'] . "</th>";
echo "</tr>";
}
?>
Your Javascript should be like:
function getData()
{
$.ajax({
url : 'process.php',
method : 'GET',
data:{ sortBy:$('#selectForm').val() }
success : function(response)
{
$('#data').html(response);
},
error : function(e)
{
alert('error');
}
});
}
you can make another page by the name of highscores.php and get all the code there.then make a call on page load to get the scores dynamically in this div.
$(document.ready(function(){
//on page load,for the first time.
$('#highscore').load('http://site_url/highscores.php');
//on selectbox change
$('#selectbox').change(function(){
$.post("highscores.php", {sort: val}, function(data){
//perform sorting and return the data div.
$('#highscore').html(data);
});
})
});
//// homepage section where the scores load,add a div by the id
<div id="highscore"></div>
//////// highscore page
<div class="third third-center">
<h2>Highscores</h2>
<div class="sortby">
<form id="" method="post" action="home.php">
<select id="selectForm" name="sort">
<option value="score ASC">Score Ascending</option>
<option value="score DESC">Score Descending</option>
<option value="userName ASC">Name Ascending</option>
<option value="userName DESC">Name Descending</option>
</select>
</form>
</div>
<div class="inner">
<table>
<tr>
<th style="font-size: 20px">Position</th>
<th style="font-size: 20px">Name</th>
<th style="font-size: 20px">Score</th>
</tr>
<?php
$i = 0;
$choice = "score ASC";
$search = mysqli_query($connect, "SELECT * FROM accounts ORDER BY ".$choice."") or die(mysqli_error($connect));
while($row = mysqli_fetch_array($search)){
$i++;
echo "<tr>";
echo "<th>" . $i . "</th>";
echo "<th>" . $row['userName'] . "</th>";
echo "<th>" . $row['score'] . "</th>";
echo "</tr>";
}
?>
</table>
</div>
</div>
There are couple of changes to be done by you, first you need to change the selection box code such that you need to write an on change function and read the value in the javascript and then execute your AJAX call. Second is after the ajax call get the response from the server you need to do a DOM manipulation and populate the value in your desired format.
For example
$(document).on("change", "#select_box_id", function(){
//your ajax call here based on the value
});
I don't know whether you use jquery, if not import the library in your file and use it, which will make your life simpler
Look at this for basic AJAX http://api.jquery.com/jquery.ajax/
If you don't wish to have "live" high-scores that are reloaded from the database every time someone changes the sorting, you might be better off loading the scores into a JavaScript object and then (re)arranging them with JavaScript.
For this you'd need to have a div-element into which you recreate the data (+table structure, if needed) with something like innerHTML after you have sorted the array as you wish with sort. You run this with onChange event in the dropdown list, for example.
If you have a div, for example:
<div id="targetdiv"></div>
So your PHP-generated array could look something like:
var scores = [
{
"name" : "Adam",
"score": "100"
},
{
"name" : "Bert",
"score": "150"
},
{
"name" : "Cecilia",
"score": "75"
} ];
And your sorting algorith could be something like:
scores.sort(function(a, b) {
return parseFloat(a.scores) - parseFloat(b.scores);
});
Then just save the result to a string variable in a for-loop or whatever you want and output it into that "targetdiv" div:
var intostring = "By SCORES!<br><br>"
for (var index = 0; index < scores.length; ++index) {
intostring += scores[index]["name"] + ": " + scores[index]["score"] + "<br>";
}
document.getElementById('targetdiv').innerHTML = intostring;
I made a JSFiddle example for you to better demonstrate the above code:
https://jsfiddle.net/docweird/oaqoysm6/
(Without the onChange and dropdown).

Post drop down value of selected checkboxes

I have an html table created dynmically in PHP.The table has checkbox,Name Price and quantity.The quantity is dropdown list.I want to know how to post all these values depending on selected checkbox.Here is small snipet.What I want is the user will select
checkbox and i want to post name,price and selected quantity to another page cart.php.
What i am having working right now is i am only able to post selected checkbox value by doing $_POST["checkboxes"].But i dont know to post value for those selected checkboxes.Please help..I am trying to learn PHP.
<form action="cart.php" name="myform" id="menuform" method="post" >
echo "<label>"."Appetizers"."</label>";
echo "<center>";
echo "<table class='appetizerstable'>";
echo "<thead>";
echo "<tr>";
echo "<th>";
echo "Select";
echo "</th>";
echo "<th>";
echo "Name";
echo "</th>";
echo "<th>";
echo "Price";
echo "</th>";
echo "<th>";
echo "quantity";
echo "</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
while($row = mysqli_fetch_array($appetizers)) {
echo "<tr>";
echo "<td>" ."<input type='checkbox' name ='checkboxes[]' value=".$row['id'].">".
"</td>";
echo "<td>" ."<label name='foodname[]'>". $row['name']."</label>" . "</td>";
echo "<td>" ."<label name='foodprice[]'>". $row['price']."</label>" . "</td>";
echo "<td>"."<select id='quantity[] name='quantity[]'>".
"<option value='1'>1</option>".
"<option value='1'>2</option>".
"</select>".
"</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
echo "<center>";
You won't need to send the name and price values as you can always retrieve those from the database by knowing the id of that item when sending the form data. So we will be focusing on just the quantities and the id of the items checked.
The main problem with what you are trying to do is that the quantity[] form data and the checkboxes[] form data wont have the same amount of items in the array when the form is sent....unless you check off every item. What happens is checkboxes only gets data sent when the box is checked while quantity[] gets data sent when a select option is selected and by default one is always selected. So basically every quantity select data will get sent whether its checked or not. So it will be hard to determine which quantity array items belong to the checkboxes array items. But there is a solution....a complicated one but still a solution with just php.
Here is the new HTML
I cleaned it up a bit for readability
<form action="cart.php" name="myform" id="menuform" method="post" >
<label>Appetizers</label>
<center>
<table class="appetizerstable">
<thead>
<tr>
<th>Select</th>
<th>Name</th>
<th>Price</th>
<th>quantity</th>
</tr>
</thead>
<tbody>
<?php while($row = mysqli_fetch_array($appetizers)) : ?>
<tr>
<td>
<input type="checkbox" name ="checkboxes[]" value="<?php echo $row['id'] ?>">
</td>
<td>
<label><?php echo $row['name']; ?></label>
</td>
<td>
<label><?php echo $row['price']; ?></label>
</td>
<td>
<select id="quantity[]" name="quantity[]">
<option value="<?php echo '1-' . $row['id']; ?>">1</option>
<option value="<?php echo '2-' . $row['id']; ?>">2</option>
</select>
</td>
</tr>
<?php endwhile; ?>
</tbody>
</table>
<center>
</form>
Ok so what changed...well take a look at the new quantity[] values. I have appended a dash followed by the row id. Now each value has a unique value and we have a way to associate the quantity value with the check box value. We will figure this out on the cart.php file next. Here is how to do that:
cart.php
<?php
if(isset($_POST['checkboxes']) && isset($_POST['quantity']) ) {
$checkboxes = $_POST['checkboxes'];
$quantities_unfiltered = $_POST['quantity'];
$quantities = array();
foreach($quantities_unfiltered as $unfiltered) {
$filtered = explode('-', $unfiltered);
// $filtered now equals a 2 item array
// $flitered[0] = the quantity value
// $filtered[1] = the id
// create an associative array for easy access to the quantity by using the id as the array key
$quantities[ $filtered[1] ] = $filtered[0];
}
// now we can figure out the quantity values for each checkbox checked
// test it out by echoing the values
foreach($checkboxes as $id) {
echo 'Item with id of ' . $id . ' was selected with a quantity of ' . $quantities[$id] . '<br>';
}
}
?>
Hope that helps you out a bit.
UPDATE
I added an if statement in the cart.php example and removed the foodprice[] and foodname[] from the name attributes as they don't send as POST data anyways as the html is not a form element. I got a little picky about that.
you can use the jquery to submit form when change on dropdown value
<select name="" id="" onchange="this.form.submit()">
..........
.........
</select>

Store updated forms as an array w/jQuery

I am currently building an internal tool for viewing and editing SQL-like tables via the web. I have some PHP and html written that generates these tables and jQuery written that does this, so far:
Delete Rows
Add New Rows
Output form value after entry
The ultimate goal, of course, is to generate a SQL statement using INSERT, UPDATE, DELETE, etc on the modified data. I have a grasp on how to concatenate the results into such a statement, but could use help targeting columns for it.
My main concern is modifying the form value output function so that I can store any updated entries in an array and output them as a CSV string. I've read about .each, .map, .push, and .serializeArray. I'm not sure exactly how to use/combine these methods to accomplish the desired result. Here are some code snippets:
The current jQuery:
$('#add_row').on('click', function(){
$('<tr><td id="data"><input class ="new_row"></td><td id="data"><input class ="new_row"></td><td id="data" style="text-align:center;"><input class ="new_row"></td><td id = "Delete_Button"><button class="rmv_row">-</button></td></tr>').appendTo('#SQLdata');
});
$("table").on('keyup', 'input', function(){
$('#output').text($(this).val());
});
$('table').on('click', '.rmv_row', function(){
$(this).closest('tr').remove();
});
});
and the PHP/HTML:
<table id="SQLdata">
<tr style="background-color: margin-left:#6b685c;">
<td style="background-color: margin-left:#6b685c; font-family:tahoma,arial,verdana,sans-serif"; colspan="3">
<form style="color:black;" method="post" action="WebEventsStructureColumnTool.php">
Select your table name:
<select method="post" name="table_name" id="picker">
<option>Removed For Security</option>
</select>
<input type="submit" value="Go" name="submit">
</form>
</td>
<td><button id="add_row">Add a Row</button></td>
</tr>
$tableName = $_POST['table_name'];
$statementObject = $pdo->prepare("SELECT a, b, c FROM tab WHERE _id =?");
$statementObject->bindParam(1, $tableName, PDO::PARAM_STR);
$statementObject->execute();
$statementObject->bindColumn('a', $Col1);
$statementObject->bindColumn('b', $Col2);
$statementObject->bindColumn('c', $Col3);
while ($statementObject->fetchAll(PDO::FETCH_BOUND)){
// Gets an array from the CSVs in the column :
$Column1 = explode(",", $Col1);
$Column2 = explode(",", $Col2);
$Column3 = explode(",", $Col3);
}
//Fetches the total number of values from each exploded array:
$Count1 = count($Column1);
$Count2 = count($Column2);
$Count3 = count($Column3);
//Establishes the total length/height of the table:
$largest = $Count1;
if ($Count2 > $largest){
$largest = $Count2;
}
if ($Count3 > $largest){
$largest = $Count3;
}
echo '
<tr>
<th>a</th>
<th>b</th>
<th style="text-align: center">c</th>
<th>delete row</th>
</tr>';
for($i = 0; $i < $largest; $i++){
$tableRows[] =
"<tr>
<td id='data'>
<input type='text' value='" . $Column1[$i] . "'>
</td>" .
"<td id='data'>
<input type='text' value='" . $Column2[$i] . "'>
</td>" .
"<td id = 'data' style='text-align:center;'>
<input type='text' value='". $Column3[$i]. "'>
</td>
<td id = 'Delete_Button'><button class='rmv_row'>-</button></td>";
}
foreach ($tableRows as $row){
echo $row;
}
echo '</table><div><table><tr id="output" colspan="4"></tr></table>'
If anyone also has advice/recommendations on existing code, feel free to criticize. I am a young developer just starting out and could use all the help I can get. Thanks!
I added this bit this morning and am now successfully getting CSVs:
var string = new Array()
function updateString(){$('#output').text(string);}
$('input').each(function(){
string.push($(this).val());
});
Working on creating three different arrays for each data manipulation option and limiting printing to conditionals.

Grab ALL values from a column pulled out of a DB comma seperated and put into a textfield

I have a table which contains the column fleet name, vehicle registration and some other info about each vehicle. 1 fleet can have many vehicles. The main aim of my application is to show vehicles within a fleet when a fleet is selected (from a dropdown), so filtering out and showing rows of the database (based on the column "fleet_name") so the results show only the cars in the selected fleet (this is already achieved, see code below). what i'm now trying to achieve is to grab, with a click of a button, ALL of the pulled out phone numbers of the vehicles within the selected fleet, comma seperated, so if the fleet had 3 vehicles, once you click the "grab numbers" button you would get 074123456789,07412347321,074292839201 in the textfield. if the 0 in the beggining could be changed to 44, that would be a huge bonus too! so i've got as far as being able to grab a row's phone number singular:
currently my code to show all the data:
<?php
$sql = "SELECT * FROM main_table";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= " WHERE fleet_name='$search_term'";
$sql .= " OR vehicle_registration_number='$search_term'";
}
$query = mysql_query($sql) or die(mysql_error());
?>
form which filters out the data:
<form name="search_form" method="POST" action="index2.php">
<?php $sql2 = "SELECT DISTINCT fleet_name FROM main_table";
$query2 = mysql_query($sql2);
echo "<p> Select Fleet Name: <select name='search_box'><option></option>";
while($row = mysql_fetch_assoc($query2)){ echo "<option>{$row['fleet_name']}</option>"; }
echo "</select></p>"; ?>
<input type="submit" name="search" value="Search the table...">
</form>
and my table code:
<table width="70%" cellpadding="5" cellspacing="5">
<tr>
<td><strong>Fleet Name</strong></td>
<td><strong>SIM Mobile Number</strong></td>
</tr>
<?php while ($row = mysql_fetch_array($query)) { ?>
<td><?php echo $row['fleet_name']; ?></td>
<td><?php echo $row['mobile_number']; ?><input type="button" value="select" onclick="clickMe('<?php echo $row['mobile_number']; ?>')" /></td>
<tr>
my button code atm:
function clickMe(number) {
$("#textfield").val(number);
}
and my textfield code:
<input type="text" name="to" id="textfield">
Thank you so much for taking time to read this and any help given.
Try to use the
GROUP_CONCAT(COLUMN_NAME)
this will give the comma separated value of your column values.
You can use PHP implode() function.

Categories