How to display database value into specific index of html table? - php

I need help for display selecting data value from database into a specific position in a html table.
I have made the code for displaying it but it will display the data in index 0 on the html table.
Anyone know how to make the data will displaying at index 1 on the html table?
I've try to change the index but it failed to displaying it.
Here my code:
$(document).ready(function(){
$.ajax({
type: "Post",
url: "../php/bkk/bkk_isel.php",
success: function(data){
var list = JSON.parse(data);
for(var i = 0; i < list.length; i++){
$('#mat').val((list[i]['material']));
$('#lok').val((list[i]['lokasi']));
$('#kpl').val((list[i]['kapal']));
$('#po_numb').val((list[i]['po']));
var tr = "<tr>";
tr += "<td>"+list[i]['tanggal']+"</td>";
tr += "<td>"+list[i]['no_pol']+"</td>";
tr += "<td>"+list[i]['netto']+"</td>";
tr += "</tr>";
$("#table_s tbody").append(tr);
}
return false;
}
});
});
This is the {data} that i use. i use php function for the data
<?php
$con=mysqli_connect("localhost","root","","silo");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
// Data for Titik1
$query = mysqli_query($con,"SELECT * FROM temp2");
$rows = array();
while($tmp= mysqli_fetch_array($query)) {
$rows[] = $tmp;
}
echo json_encode($rows);
mysqli_close($con);
?>

can you please more explain what shape you mold with html Table. basically table row always append with general indexing. if you need a black row before your data row so kindly append a blank row in your html table.

If you want the index number of the row to show on the html table, then you need to add a new column before all other columns. This new column will show the serial number of the row. For example before this line:
tr += "<td>"+list[i]["tanggal"]+"</td>";
Add this line:
tr += "<td>"+ (i+1) +"</td>";

Related

How to click all database buttons generated through php script using a singe button?

The problem i've run into is that i have multiple buttons generated through php from data mysql data base and i do not want to manually click them all(it can go over 150). How do i make a button in HTML or PHP to click them all? or How to select the ID of each button (not manually) to include it in the General button?
I have tried onclick="document.getElementByID('').click()" atribute on the button that i want to click them all but with no succes
This is the code that i have and the issue:
<?php
// server info
$server = 'localhost';
$user = 'root';
$pass = '';
$db = 'testcases';
// connect to the database
$mysqli = new mysqli($server, $user, $pass, $db);
//fetching data
// get the records from the database
if ($result = $mysqli->query("SELECT * FROM test1 ORDER BY id"))
{
// display records if there are records to display
if ($result->num_rows > 0)
{
echo "<table style=\"position:absolute; left:10px; top:80px;\" border ='1px'>";
while ($row = $result->fetch_object())
{
echo "<tbody>";
echo "<tr>";
echo "<td><textarea id=\"row->date\">". $row->date ." </textarea></td>";
echo "<td><textarea id=\"row->testcase\">". $row->testcase ."</textarea></td>";
echo "<td><textarea id=\"row->percentage\">". $row->percentage ." </textarea></td>";
echo "<td><a href='temp.php?id=" . $row->id . "'><button type=\"button\" class=\"btn\" name=\"id\" id=\"$row->id\" >COPY To Temp</button></a></td>";
echo "</tr>";
echo "</tbody>";
}
echo "</table>";
}
}
// close database connection
$mysqli->close();
?>
<button type="button" style="width:200px" class="pure-button fuller-button1 blue" onclick="document.getElementByClassName('btn').click();">Copy All</button>
The expected result would be to have a table with multiple rows and button generated through php and another button to click them all, but i got stuck at the part where i need to click all the buttons.
I don't know what you really wanna do, but first of all it's a really strange thing to put a button into a link: if you want a like you can add a span child styled like a button and if you really want a button just listen to click events on it.
Another thing would be that you could use form + checkboxes so that your button can make a single action by submitting form (and this single action/HTTP query will be exploded in N actions (loop) server-side)
If you really would like to do this like you do, using ID property is not wrong but it doesn't help readability nor CSS selection, I would use data-* attributes.
So, now you want a simple answer ;)
var elements = document.getElementsByClassName("btn");
for (var i=0; i<elements.length; i++) {
elements[i].click(); // or anything you want
}
If you wanna get id properties you can do:
var elements = document.getElementsByClassName("btn");
var ids = [];
for (var i=0; i<elements.length; i++) {
ids.push(elements[i].id);
}
If you plan to use jQuery:
var ids = [];
$(".btn").each(function() {
var $button = $(this);
ids.push($button.attr("id"));
});
try this:
<button type="button" onclick="copyBtn()">Copy</button>
and using jQuery
function copyBtn(){
var id = $(this).attr("id");
console.log(id);
//do some stuff
}

populate HTML table with JQuery AJAX using JSON formatted data

I am new here and newbie learner. I've checked some similar questions like this but could not get them to work.
What I am trying to achieve is, querying my database, retrieve list of accounts, then jquery function sends a query to ajaxtest2.php file for each of the account to retrieve account information and shows it in a html table.
Main problem is, table is populating with information of the last account in the database instead of all accounts.
I am getting this output at the moment:
`3459 1459 3459 1459`
Your help will be much appreciated.
Thank yoU :)
include_once('database.php');
$sql1 = "select * from account ";
$result1 = mysql_query($sql1);
while ($arr1 = mysql_fetch_array($result1)) {
$var = $arr1["account_no"];
?>
<script type="text/javascript">
$(document).ready(function() {
$(window).load(function() {
var numValue = <?php echo $var; ?>;
$.getJSON("ajaxtest2.php", {number: numValue}, function(data){
var trHTML = '';
$.each(data, function () {
trHTML += '<td>' + data.bal + '</td><td>' + data.eq + '</td>';
});
$('#location').append(trHTML);
});
}); `
});
</script>
<table id="location" border='1'>
</table>
<?php
}
The below is the response from ajaxtest2.php
echo json_encode(array("bal" => "$balance", "eq" => "$equity"));
?>
Make sure that you have table rows when you generate the cells.
trHTML += '<tr><td>' + data.bal + '</td><td>' + data.eq + '</td></tr>';
Else your cells will always append to the right of the previous cell without changing rows
Also, the your code could all be done using PHP only (no js)
Here's how:
<?php
include_once('database.php');
$sql1 = "select * from account ";
$result1 = mysql_query($sql1);
?>
<table id="location" border='1'>
<?php
while ($arr1 = mysql_fetch_array($result1)) {
$var = $arr1["account_no"];
//your ajaxtest2.php functionnalities go here
//let's say $accBalance and $accEquity contain the information you wanted about that specific row
echo '<tr><td>'.$accBalance.'</td><td>'.$accEquity.'</td></tr>';
}
?>
</table>
And there you have your populated table using database values without using JS.
Hoped it helped!

Get value from dropdown list to use in MySQL query

So I'm having this issue with geting a value from a dropdown list in HTML into a variable so that I can do the mysql query. This will be a little tricky to explain but I will do my best. (Do not be shy in correcting my english or my expressions so that the question becomes more concrete and easy to understand).
So I have this dropdown list that gets his values from a mysql query.
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
This "connects" with this query:
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'");
$result4 = mysql_query($sql4, $link);
This query will populate the dropdown list with values. What I'm seeking to do is to populate another dropdown list. For examples I select a list of countrys, and when I select on country it should appear all it's citys in the other dropdown list.
I have been searching guys. Belive me I have.
P.s: Please do not get mad if I change the question a couple of times when I see that you guys show me a way to explain it better. Sorry if my english isn't perfect. Thank you guys for the help.
You can do it with ajax and jquery. I try to write little example
<!-- index.php -->
<select name="desig_act" id="desig_act">
<?php while ($row2 = mysql_fetch_assoc($result4)): ?>
<option value="<?=$row2['new_name_freg']?>">
<?=$row2["new_name_freg"]?>
</option>
<?php endwhile; ?>
</select>
<!-- select tag for countries -->
<select name="country" id="country"></select>
write a little script to return countries as json
<?php //ajax-countries.php
$link = mysql_connect(); // connect as usual
$query = ("SELECT * FROM countries");
$result = mysql_query($query, $link);
$json = array();
while ($row = mysql_fetch_assoc($result)) $json[] = $row;
echo json_encode($json);
?>
Then you can have some sort of script like:
// script.js
$("#desig_act").change(function(){
$.getJSON( "ajax-countries.php", function( data ) {
$.each( data, function(key, val) {
$("#desig_act").append("<option val='" + key + "'>" + val + "</option>");
});
});
I hope it can be useful
1: Create a PHP script to return the data
Essentially just generate the value based off the $_GET input.
2: Create a json request in jquery
Calls the PHP file which will return the data and you will use that data to add more values to the select.
<?php
//Step 1 - The posted ajax data that will return our json request.
if(isset($_GET['fetchrow'])) //Is our ajax request called on page load? If yes, go to this code block
{
//Other stuff like DB connection
$pesq = mysql_escape_string($_GET['fetchrow']); //Put our variable as the variable sent through ajax
$sql4 = ("SELECT DISTINCT new_name_freg FROM freguesias WHERE codg_cc = '$pesq'"); //Run our query
$result4 = mysql_query($sql4, $link); //Please change from mysql_* to mysqli
$data = array(); //The array in which the data is in
while($row = mysql_fetch_assoc($result4)) //Look through all rows
{
array_push($data, $row); //Put the data into the array
}
echo json_encode($data); //Send all the data to our ajax request in json format.
die; //Don't show any more of the page if ajax request.
}
?>
<html>
<head>
<script type='application/javascript' src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js'></script> <!--Include jquery -->
<script>
//Step #2:
//The jquery script calls ajax request on change of the first select
$( "#desig_act" ).change(function() {
$.getJSON('thisfilename.php', {fetchrow:$("#desig_act").val()}, function(data){ //Get the json data from the script above
var html = '';
var len = data.length;
for (var i = 0; i< len; i++) { //Loop through all results
html += '<option value="' + data[i].new_name_freg + '">' + data[i].new_name_freg + '</option>'; // Add data to string for each row
}
$('#otherselect').html(html); //Add data to the select.
});
});
</script>
</head>
<body>
<!-- Your html code -->
<td>Designação atual :</td> <td><select name="desig_act" id="desig_act">
<?php
while ($row2 = mysql_fetch_assoc($result4)) {
echo "<option size=30 value=".$row2['new_name_freg'].">".$row2["new_name_freg"]."</option>";
}
?>
</select>
</td>
<!-- The new select -->
<select name='otherselect' id='otherselect'>
</select>
<!-- Rest of html code -->
</body>
</html>

Unable to catch data

I am passing data using J-Query and AJAX to res.php page:-
attempt.php (my main page from where the res.php is called)
$.ajax(
{
url: "res.php",
type: "POST",
data: data,
success: function (data)
{
var build_id='build_';
build_id += i;
alert(build_id);
$('#npc').append(data);
$('#build_id').attr('disabled','true');
var total = $("#build_id");
alert(total);
}
});
In the res.php page I am using the passed data to generate the query and retrieve data from the database and calculated the total value and display the total in a text box.
res.php
$i = mysql_real_escape_string($_POST['i']);
$query = "select * from ";
$query = $query . $building;
$query = $query . " where lvl=" . $level;
$query = $query . ";";
$result = mysql_query($query) or die('Error in Child Table!');
echo $i;
while( $data = mysql_fetch_assoc($result))
{
$total_res = $data['lumber'] + $data['clay'] + $data['iron'] + $data['crop'];
echo '<tr><td>'. $building. '</td><td>'. $level. '</td><td><input type="text" style="width:70px" id="build_' . $i . '" value="' . $total_res . '"></td></tr>';
}
I am using id="build_' . $i . '" to auto increment the id of the text box. Till here everything goes fine.
Back to the attampt.php page,
when I try to access the data from the text box i am unable to access it.
The code that I'm using to access the data is:-
var build_id='build_';
build_id += i;
$('#build_id').attr('disabled','true');
var total = $("#build_id");
alert(total);
the alert function at the end of the code gives the following output:-
[object Object]
I am trying to append a list of text boxes with some values to a table and then calculate the sum of all the values in the text boxes.
Please help.
$('#build_id') should be $('#'+build_id) and to calculate the total of all the values, you should put var total=0; outside your callback function, and the function should contain
total += $('#'+build_id).val();
Another problem is that each row of the table has the same id="build_$i", but IDs have to be unique.
And do you really intend to display $i at the beginning of the table, without it being in a table row?

How to get the row id of html table

Assume I have some data from the database and store in a array, which like this:
$testArray = array(
array('0', 'name1', 'status1'),
array('1', 'name2', 'status2')
);
and I can print the content of the array as a html table, like this way:
Id name status
0 name1 status1
1 name2 status2
I want to use a 'status' dropdown list at the end of each row to change the status of each entry, and update into the database table. My questions are:
How do I get the row id of each row(the 'Id' column) when I select a option of the drodown list?
How to pass these info to the backend inorder to update the database table? I guess it should use some javascript. And below is the code:
<?php
$testArray = array(
array('0', 'name1', 'status1'),
array('1', 'name2', 'status2')
);
?>
<html>
<head>
</head>
<body>
<table>
<tr>
<td>Id</td>
<td>name</td>
<td>status</td>
</tr>
<?php
for ($i = 0; $i < count($testArray); $i++){
echo '<tr>';
for ($j = 0; $j < count($testArray[$i]); $j++){
echo '<td>';
echo $testArray[$i][$j];
echo '</td>';
}
echo '<td>';
echo '<select>';
echo "'<option value='0'>status1</option>";
echo "'<option value='1'>status2</option>";
echo '</select>';
echo '</td>';
echo '</tr>';
}
?>
</table>
</body>
</html>
Thanks for help!
You Could:
Give each of your select's an id that correspond to the row of data.
On change(jQuery), Get the value of the select, and use the jquery ajax call to send the rowID, and the 'StatusValue' to the handling page.
Show an status message on return of data.
http://api.jquery.com/jQuery.ajax/
--Building the Select
<?php
for ($i = 0; $i < count($testArray); $i++){
echo '<tr>';
for ($j = 0; $j < count($testArray[$i]); $j++){
echo '<td>';
echo $testArray[$i][$j];
echo '</td>';
}
echo '<td>';
**echo '<select id="' + $testArray[$i][0] + '">';**
echo "'<option value='0'>status1</option>";
echo "'<option value='1'>status2</option>";
echo '</select>';
echo '</td>';
echo '</tr>';
}
?>
--The jQuery (you will need the jquery file, download from jquery.com)
$(document).ready(function(){
$('select').change(function () {
var rowIdVal = $(this).attr('id'); // the id of the select (your rowID)
var statusVal = $(this).val(); // the value of the select
// post id to the server using ajax (you can use jQuery ajax request)
////I would check if the values are valid and not null...
$.ajax({
type: "POST",
url: "YOURHANDLERFILE.php",
data: {status: statusVal, rowId: rowIdVal},
success: function(d){
//show a status message
}
});
});
});
You can:
Store your row id in the hidden field in the first column and the get using jQuery
Store as id attribute and then using jQuery get the value
(I think the best one) store the id in id attribute in the your select control and then get value on selected index change using jQuery
in html you will have:
<select id="1">
in javascript:
$('select').change(function () {
var id = $(this).attr('id');
// post id to the server using ajax (you can use jQuery ajax request)
});
I would do something like
$('#yourTableId').find('select').change(function() { //bind a change event to the selects
$(this).closest('tr') //this way you get the tr element of the row you changed the select value
.find('td:first') //or .find('td').first(). This will give you the td element for the Id column
.val(); //The actual value of the td Id element
});

Categories