Display data fetched from remote PHP (mysql) in html table [closed] - javascript

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 11 years ago.
I have a PHP page displaying data from a mysql database, based on a dropdown list selection, also from a mysql database. This obviously makes use of a JavaScript.
The PHP and mysql integration is working perfectly however I need to change the way the data is displayed.
Currently the returned mysql data is displaying in one table cell, I want each returned mysql field to be displayed in its own table cell.
I have added a photo of the output, I want it to display in each table cell, not in one.
I have attached the code from both my PHP file and the PHP file querying the database.
Any assistance would be greatly appreciated!
index.php
<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getdata.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$con = mysql_connect('localhost', 'unilever_root', 'Unilever2011');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("unilever_unilever", $con);
$skusql="SELECT packcode from skudata";
$resultsku=mysql_query($skusql);
$optionssku="";
while ($row=mysql_fetch_array($resultsku))
{
$sku=$row["packcode"];
$optionssku.="<OPTION VALUE=\"$sku\">".$sku;
}
?>
<table border=1>
<tr>
<td>SKU</td>
<td>Description</td>
<td>SU</td>
<td>Points</td>
<td>Category</td>
<td>Grouping</td>
</tr>
<tr>
<td>
<select name="users" onchange="showUser(this.value)">
<OPTION VALUE=0>
<?=$optionssku?>
</SELECT>
</td>
<td>
<div id="txtHint"><b>SKU Details will be seen here</b></div>
</td>
</tr>
</table>
</body>
</html>
getdata page
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'dbuser', 'password');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("unilever_unilever", $con);
$sql="SELECT * FROM skudata WHERE packcode = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<td>" . $row['Description'] . "</td>";
echo "<td>" . $row['SellingUnits'] . "</td>";
echo "<td>" . $row['EOTTPoints'] . "</td>";
echo "<td>" . $row['Category'] . "</td>";
echo "<td>" . $row['Grouping'] . "</td>";
}
mysql_close($con);
?>

The problem here is that you've used two ideas that don't quite work together. This line: document.getElementById("txtHint").innerHTML=xmlhttp.responseText; is setting the content of the tag with id "txtHint" to what your php script returns. This means that when your php returns, for example:
<td>blah</td><td>blah</td><td>blah</td>
then your page ends up with:
<div id="txtHint">
<td>blah</td>
<td>blah</td>
<td>blah</td>
</div>
Do you see what's happening here? You aren't adding more cells to the existing row, you're creating another table within the cell you already have (and a bad one at that, with no <table> or <tr> tags...).
To get around this, change the element with id "txtHint" to the <tr> tag for the row you are editing, and update the php to return the first cell of that row as well, eg:
HTML:
<table border=1>
<tr>
<td>SKU</td>
<td>Description</td>
<td>SU</td>
<td>Points</td>
<td>Category</td>
<td>Grouping</td>
</tr>
<tr id="txtHint">
<td>
<select name="users" onchange="showUser(this.value)">
<OPTION VALUE=0>
<?=$optionssku?>
</SELECT>
</td>
<td colspan="5">SKU Details will be seen here</td>
</tr>
PHP:
while($row = mysql_fetch_array($result))
{
echo "<td><select name='users' onchange='showUser(this.value)'><OPTION VALUE=0>";
echo $optionssku; //Not sure where this variable comes from, so I'll leave getting it from wherever necessary to you
echo "</SELECT></td>";
echo "<td>" . $row['Description'] . "</td>";
echo "<td>" . $row['SellingUnits'] . "</td>";
echo "<td>" . $row['EOTTPoints'] . "</td>";
echo "<td>" . $row['Category'] . "</td>";
echo "<td>" . $row['Grouping'] . "</td>";
}
(code not tested, but it'll be something like this).
There are certainly other methods to get around this problem, almost certainly better ones, but this is the first idea that came to me.

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

Populate text input field automatically based on dropdown selection mysqli

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.

Hide Rows on Click Table

I'm trying to create a table that has individual lines with a summary of individual invoices(e.g. Invoice Date, Invoice Total,Status, etc).
I want to be able to click on the row and for it to expand down and show me the detailed information relating to that invoice, however I haven't been able to solve the issue that I need to isolate the row and then expand the new information underneath it?
Keeping in mind a < div > can't surround a < tr > element so I can't hide the < div > and < tbody > wants to encompass the whole table body not just a set of rows.
My PHP and HTML skills I are decent but my knowledge of javascript is not, so any assistance in getting this going is appreciated.
<table>
<tr><th colspan='6'><h2>Billing Details</h2></tr><tr><td>Invoice ID</td><td>Invoice Date</td><td>Due Date</td><td>Date Paid</td><td>Total</td><td>Status</td>
<?php
for ($counter = 0; $counter < $invoicesData['numreturned']; $counter++)
{
echo "<tr><td>WellConn - " . $invoicesData['invoices']['invoice'][$counter]['id'] . "</td>";
echo "<td>" . $invoicesData['invoices']['invoice'][$counter]['date'] . "</td>";
echo "<td>" . $invoicesData['invoices']['invoice'][$counter]['duedate'] . "</td>";
echo "<td>" . $invoicesData['invoices']['invoice'][$counter]['datepaid'] . "</td>";
echo "<td>$" . $invoicesData['invoices']['invoice'][$counter]['total'] . "</td>";
echo "<td>" . $invoicesData['invoices']['invoice'][$counter]['status'] . "</td></tr>";
}
?> </table>
Any help is greatly appreciated.
Try this pattern bro..
<tr onclick="myFunction()">
<td id="td1" hidden> <?php echo ?> </td>
</tr>
<script>
function myFunction(){
document.getElementById("td1").style.display = "table-row";
}
</script>
Automatically hide the td's.When you click the tr, the td's will show.Cheers bro.

I want to display 1 record instead of displaying the whole Database, PHP

dbconnect.php
<form method="post" action="a.php">
<select name="taskOption" id="cust-id" onchange="showUser(this.value)">
<?php
include 'orderSelect.php';
echo '<option>View Order</option>';
while($row = mysqli_fetch_array($result)):;?>
<option value='<?php echo $row[0]; ?>'><?php echo $row[1]; echo " ";
echo $row[2]; ?></option>
<?php endwhile; ?>
</select>
</form>
a.php
<?php
include 'connect.php';
$q = intval($_GET['q']);
$sql = "SELECT id, firstname, lastname,productOne, quantity, price
FROM orderlist";
$result = mysqli_query($conn, $sql);
echo "<table >
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
$tquan = $row['quantity'];
$tprice = $row['price'];
$total = $tquan * $tprice;
echo "<tr>";
echo "<td>" . $row['firstname'] . "</td>";
echo "<td>" . $row['lastname'] . "</td>";
echo "<td>" . $row['productOne'] . "</td>";
echo "<td>" . $row['quantity'] . "</td>";
echo "<td>" . $row['price'] . "</td>";
echo "<td>" . $total . "</td>";
echo "</tr>";
}
echo "</table>";
?>
I got it working. IT display the record/ users that I want to see when something is selected from the drop down list, but the problem is it's displaying the entire database data. I only want to get that specific that of the selected person. Any Ideas how to solve this problem? I would appreciate it.
Image Example
I only wanted the first row to be selected when I select from the dropdown list
Your SELECT is of the whole database you need to select something exact.
For example:
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
That is an example of using the WHERE clause.
In addition to what the above said.
You mentioned you only wanted 1 record.
Add " LIMIT 1" to the end of your query
OR
Change the 'while' command to an 'if' command and it will only run once.

Html Dropdown Menu Displays nothing

I'm trying to diplay my table when I click a value in Dropdown list. When I view page code source, the table values are there but it's not showing. I would like to query from mysql using the value from dropdown and populate the table with datas from mysql query.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript">
function jsFunction(value){
<?php
$con=mysqli_connect("localhost","root","","dengue");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mapping_details where case_type='value'";
echo '<div class="table-responsive ">
<table class="table table-condensed table-hover table-bordered">
<thead>
<tr>
<th>Barangay</th>
<th>Case Type</th>
<th>Total Dengue Cases</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['brgy'] . "</td>";
echo "<td>" . $row['case_type'] . "</td>";
echo "<td>" . $row['total_case_brgy'] . "</td>";
echo "</tr>";
}
echo '</tbody></table></div>';
mysqli_close($con);
?>
}
</script>
</head>
<body>
<select id ="ddl" name="ddl" onchange="jsFunction(this.value);">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
</body>
</html>
Originally, in my other webpages, the php code is inside the body. But this time, I can't make it work if I use dropdown menu so that's why I put it inside the function for me to be able to use onchange function. I've read some answers using AJAX or JSON but I'm not familiar with those so if possible I only want to use javascript as maybe it is the simplest way.
What you are trying to do here is run PHP code in the browser, which you cannot do. All the HTML, CSS, and JavaScript is sent down to the client ( your browser ) and then is rendered and initialized by the browser. When you are calling your onchange event to call the jsFunction() you are trying to execute PHP within that function but- you are on the client-side running in chrome or firefox or some browser and you cannot execute PHP there. PHP has to run on page load and then can change the html, css, or JavaScript before it is sent down to the client.
There are two ways of doing what you want to do. You can send an Ajax request ( call your server using javascript ) to get new data or you can submit a form that reloads the page and you can run PHP like you are comfortable with- modifying the html, css, and/or javascript before it is returned to the client (browser).
Here is the non-ajax way which just keeps reloading the page
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<?php
$value = isset( $_POST['ddl'] ) ? $_POST['dll'] : 1; // we are setting 1 as the default
$con=mysqli_connect("localhost","root","","dengue");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM mapping_details where case_type='{$value}'";
$html= '<div class="table-responsive ">
<table class="table table-condensed table-hover table-bordered">
<thead>
<tr>
<th>Barangay</th>
<th>Case Type</th>
<th>Total Dengue Cases</th>
</tr>
</thead>
<tbody>';
while($row = mysqli_fetch_array($result))
{
$html.= "<tr>";
$html.= "<td>" . $row['brgy'] . "</td>";
$html.= "<td>" . $row['case_type'] . "</td>";
$html.= "<td>" . $row['total_case_brgy'] . "</td>";
$html.= "</tr>";
}
$html.= '</tbody></table></div>';
mysqli_close($con);
?>
}
</script>
</head>
<body>
<form method="POST" action="">
<select id="ddl" name="ddl">
<option value='1'>One</option>
<option value='2'>Two</option>
<option value='3'>Three</option>
</select>
</form>
<script>
$("select#ddl").on("change",function(){
$('form').submit();
});
</script>
<?php echo $html; ?>
</body>
</html>

Categories