How can i display data from selected row in textarea - javascript

I'm trying to learn php with html and I decided to create a project.
Right now, I'm stuck at this point where I want to display data on a textarea.
I created a database named 'company' with the table 'login' and the columns 'id','password' and 'username'.
When I select an option in the select option menu, the data from the column 'id','password' and 'username' is displayed in a table. What I want to achieve is when I click on a row, that the data from the column "problem" is displayed on the textarea which describes the situation with explanation.
I don't know how to write this but the syntax should be something like: Select 'problem' from login WHERE id='selected row id' I created on my php a select case witch works fine. The only problem that I have is I don't know how to select the id when I click on a specific row to display the data on the textarea.
Here's my code so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Formulaire</title>
<link rel="stylesheet" type="text/css" href="formulaire.css"/>
<!--<script type="text/javascript" src="select1.js"></script>-->
<!--<script src="http://code.jquery.com/jquery-latest.js"></script>-->
<style>
table tr:not(:first-child){
cursor: pointer;transition: all .25s ease-in-out;
}
table tr:not(:first-child):hover{background-color: #ddd;}
</style>
</head>
<body>
<div id="form">
<form action="#" method="post">
<label>Veuillez choisir une option :</label>
<select id="choix" name="choixtest">
<option value="tous">tous</option>
<option value="id">id</option>
<option value="username">username</option>
<option value="password">password</option>
</select>
<input type="submit" name="submit" value="Get Selected Values" />
<table id="table">
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "company");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM login";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>id</th>";
echo "<th>username</th>";
echo "<th>password</th>";
echo "</tr>";
if(isset($_POST['submit'])){
$selected_val = $_POST['choixtest']; // Storing Selected Value In Variable
while($row = mysqli_fetch_array($result)){
switch($_POST['choixtest']){
case 'tous':
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "</tr>";
break;
case 'id':
echo "<tr>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'username':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "<td>" . "</td>";
echo "</tr>";
break;
case 'password':
echo "<tr>";
echo "<td>" . "</td>";
echo "<td>" . "</td>";
echo "<td>" . $row[$selected_val] . "</td>";
echo "</tr>";
break;
default:
// Something went wrong or form has been tampered.
}
}
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
</table>
<textarea id="erreur" rows="20" cols="100"></textarea>
</form>
</div>
</body>
</html>

For a table with <table id="myTable">to get the first column value into a textbox which is defined as
<input type="text" placeholder="Customer Name" id="cus_name">
You can add the following js code.
<script>
var table = document.getElementById('myTable');
for(var i = 1; i < table.rows.length; i++)
{
table.rows[i].onclick = function()
{
document.getElementById("cus_name").value = this.cells[0].innerHTML;
};
}
</script>
Here the cus_name is the id of the text field while in the this.cells[0], the value 0 represents the first column. You can change it accordingly and also can add more columns with the code document.getElementById("cus_name").value = this.cells[0].innerHTML; by only changing the cell value and the textbox id.

Every row in your html table must correspond to an id in the login table.
you have to place somewhere in the row the id corresponding to that row. You can achieve this in many ways.
one way to do it is using a data-something attribute to put the id, for instance
<tr data-id="<?php echo $current_row['id']; ?>">
<td>column1</td>
<td>column2</td>
<td>etcetera</td>
</tr>
Once you have the data-id atttribute set you can access it via Javascript everytime a user clicks on the row. For this you need to capture the click event on the row. I'll show you an example using jQuery:
$('.myTable tr').click(function(){
let id = $('this').data('id');
console.log('id of selected row: ' + id);
});
Now the 'id' variable contains the id of the row the user selected (check console output to make sure the id is the one you expect). The next step would be to use that id to make a request to the server, via Ajax or via regular http request. If this works successfully i suggest you to research, or make another post to find out how to reload the page with the content with the data you want. Since the more specific a question is the higher is the chance that it will be answered

Related

Calling PHP via a HTML anchor on the same page

I am currently reading through a piece of code provided by my faculty and I am having troubles understanding how it works.
Specifically how the anchor is linked to the php without method="post" or method="get".
Kindly appreciate if anyone could explain or link me to relevant materials to do further readings. Much thanks.
if (!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
if (isset($_GET['buy'])) {
$_SESSION['cart'][] = $_GET['buy'];
header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
exit();
}
for ($i=0; $i<count($items); $i++){
echo "<tr>";
echo "<td>" .$items[$i]. "</td>";
echo "<td>$" .number_format($prices[$i], 2). "</td>";
echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
echo "</tr>";
}
Cart for bought items indexes is created in session if it's not there yet.
if (!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
When link with buy query parameter is opened, buy value is added to session cart. After that page is redirected to location without buy parameter.
if (isset($_GET['buy'])) {
$_SESSION['cart'][] = $_GET['buy'];
header('location: ' . $_SERVER['PHP_SELF']. '?' . SID);
exit();
}
List of items to buy is printed on page (i quess code in question is not full).
for ($i=0; $i<count($items); $i++){
echo "<tr>";
echo "<td>" .$items[$i]. "</td>";
echo "<td>$" .number_format($prices[$i], 2). "</td>";
echo "<td><a href='" .$_SERVER['PHP_SELF']. '?buy=' .$i. "'>Buy</a></td>";
echo "</tr>";
}
Links open pages with GET method.
Link query parameters can be accessed by special $_GET variable

Passing Parameters To PHP Table Hyperlink

I want the second and third columns of my php table to be a hyperlink to a different page for each row. I need to pass 3 parameters to the hyperlink
1) The value from the first column - empID listed in the table below
2) The value from $weekStart - selected from a input type="date" at top of page
3) The value from $weekEnd - selected from a input type="date" at top of page
I am trying this syntax, but it is not passing in the parameters and I am getting a page not found error. How should this syntax be altered so that it passes all 3 params and navigates to the appropriate page?
Week Start:<input type="date" name="weekStart">
Week End:<input type="date" name="weekEnd">
<input type="submit" name="submit" value="View Employee Data">
<?php
if (isset($_POST['submit']))
{
$weekStart = $_POST['weekStart'];
$weekEnd = $_POST['weekEnd'];
//Generate Table Here
}
?>
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td>'.$Row['DailySales'].''" . $res->DailySales . "</td>";
print "<td>'.$Row['SalesForWeek'].''" . $res->SalesForWeek . "</td>";
print "</tr>";
}
You didn't append the string well. Please try the below code
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td><a href='DailySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$Row['EmpID']."'>".$Row['DailySales']."</a>" . $res->DailySales . "</td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$Row['EmpID']."'>".$Row['SalesForWeek']."</a>" . $res->SalesForWeek . "</td>";
print "</tr>";
}
If it still shows not found page, then please check the file names.
Update: I hope you need to replace some variables in your loop as updated in the below code
foreach ($tsql as $res)
{
print "<tr>";
print "<td>" . $res->EmpID . "</td>";
print "<td><a href='DailySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$res->EmpID."'>".$res->DailySales."</a></td>";
print "<td><a href='WeeklySales.php?param1=".$weekStart."&param2=".$weekEnd."&param3=".$res->EmpID."'>".$res->SalesForWeek."</a></td>";
print "</tr>";
}
Completely untested and I'm not 100% sure what the data in those links were supposed to be doing, but I think this should give you a solid starting point and you can tweak the HTML generation to get what you want.
I wouldn't bother trying to do it in PHP at all, pass the entire data set to JS and do it there.
Week Start:<input type="date" name="weekStart" id="weekStart">
Week End:<input type="date" name="weekEnd" id="weekEnd">
<input type="submit" name="submit" value="View Employee Data">
<?php
if (isset($_POST['submit']))
{
$weekStart = $_POST['weekStart'];
$weekEnd = $_POST['weekEnd'];
//Generate Table Here
}
// Create a JSON version of your data to pass to the script
$data = json_encode( $tsql );
?>
<!-- Create an empty table for your data-->
<table id="employee-table"></table>
<script>
$("#submitForm").on("click", function(e) {
// Stop the form from reloading the page
e.preventDefault();
// Set up your variables, you'll need to add ID's to the form inputs
var employees = <?php echo $data; ?>;
// See the employees data in your inspector console
console.log(employees);
var weekStart = $("#weekStart").val();
var weekEnd = $("#weekEnd").val();
// Generate the HTML for all the employees
var html = "";
for( var1=0; i<employees.length; i++ ) {
html += "<tr>";
html += "<td>" . employees[i].EmpID . "</td>";
html += "<td>" + employees[i].DailySales + "</td>";
html += "<td><a href='WeeklySales.php?param1='" + weekStart + "'&param2='" + weekEnd + "'&param3='" + employees[i].id +"'>" + employees[i].SalesForWeek + "</a></td>";
html += "</tr>";
}
// Insert the HTML that you generated into the table.
$("#employee-table").html(html);
});
</script>

PHP and HTML table search using javascript

I want to create a search box, that only displays matched entries as search phrases are typed; the same in function as described here:
How to perform a real time search and filter on a HTML table
The difference is, the table I have is created from a PHP loop - and SQL data. But, I am unsure how to adopt the code to work for me.
Personally, I think it could be related to the "// printing table rows" section.
Here is the code:
var $search_rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$search_rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
<html>
<script src="./jquery-1.6.4.js"></script>
<script src="./sorttable.js"></script>
<script src="./searchbox.js"></script>
<link rel="stylesheet" href="styles.css">
<head>
<title>Tau Empire Cadre Census</title>
</head>
<body>
<?php
//// //// //// ////
// DATABASE
//// //// //// ////
//database credentials
$db_host="localhost";
$db_user="tau";
$db_pwd="kuhohNg3";
$db="tau_census";
$db_table="cadres";
//make the connection
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($db))
die("Can't select database");
// sending query
$result = mysql_query("SELECT * FROM {$db_table}");
if (!$result) {
die("Query to show fields from table failed");
}
//assign a variable the number of returned table fields
$fields_num = mysql_num_fields($result);
//// //// //// ////
// HEADING
//// //// //// ////
echo "<h1>Tau Empire Cadre Census</h1>";
// Search box
echo '<input type="text" id="search" placeholder="Type to search">';
//// //// //// ////
// TABLE
//// //// //// ////
//create the table, and use the JS sortable script
echo '<table id="table" class="sortable"><tr>';
// printing table headers
echo "<td class=headings>Designation</td>";
echo "<td class=headings>Location</td>";
echo "<td class=headings>Founding</td>";
echo "<td class=headings>Commanding Officer</td>";
echo "<td class=headings>Current Status</td>";
echo "<td class=headings>Current Location</td>";
echo "<td class=headings>Mission</td>";
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// For each field print the content
for($i=1; $i<$fields_num; $i++) {
echo "<td>" . $row[$i] . "</td>";
}
echo "</tr>";
}
echo "</table>";
mysql_free_result($result);
?>
</body>
</html>
Running this does not throw up any errors, but nor does it work either. This requires brains greater than mine to work out, please.
I have this working now, thanks for all the assistance. It was a possible combination of the following:
i) Having the following script lines inserted correctly:
<script src="./jquery.min.js"></script>
<script src="./jquery-1.6.4.js"></script>
ii) Wrapping the external JS in $(function(){...});
iii) Incorrectly constructing my table rows and data fields.
Since you think the problem lies in the "printing table rows" section, I will point out that indeed you have formatting issues in that section, fix them like this and it might solve some of the problems:
// printing table rows
while($row = mysql_fetch_row($result))
{
echo "<tr>";
// For each field print the content
for($i=1; $i<$fields_num; $i++) {
echo "<td>" . $row[$i] . "</td>";
}
echo "</tr>";
}

Hide table row that contains specified string

$row['attended'] can be either 'YES' or 'NO' (strings). I want to hide every row that has 'Attended' as 'NO'. So in pseudo code:
if (<tr> contains 'NO') {
hide that row (<-That's the tricky part to me)
}
My code is on the server side, but I'd be happy to echo out some JavaScript if that's what's necessary.
<?php
include 'connect2.php';
date_default_timezone_set('Europe/Lisbon');
$today = date('Y-m-d');
$sql="Select * FROM detentions WHERE date = '$today'";
$result = mysqli_query($con,$sql);
echo "<center><table style='width:400px; border:3px solid #444'>
<tr>
<th style='background-color:#444'>First</th>
<th style='background-color:#444'>Last</th>
<th style='background-color:#444'>Attended</th>
<th style='background-color:#444'></th>
</tr>";
while($row=mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td><center>" . $row['attended'] . "</center></td>";
echo "<td><button type = 'button' class='unattended button-error pure-button button-xsmall' style='float:right; margin-left:0.2cm' name='" . $row['lname'] . "' id='" . $row['fname'] . "'><b>Unattended</b></button> <button type = 'button' class='editDet2 button-success pure-button button-xsmall' style='float:right' id=" . $row['det_id'] . "><b>Attended</b></button></td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
Another option is to skip the record with $row['attended']="No" in your while statement... An "if ($result.attended=='yes') {add ...} stamement" will do... Though the more efficient and elegant way would be to add a clause on the query statement like:
Select * FROM detentions WHERE date = '$today' and attended='yes'"
As suggested on the previous answer...
replace your select statement
$sql="Select * FROM detentions WHERE date = '$today' AND attended = 'YES' OR attended = ''";
and remove your if condition.
You can add a WHERE clause unto your SELECT statement, which specifies that the Attended field should be equal to no. This would prevent the unwanted rows from being returned in the first place.
Change your SELECT statement to:
SELECT * FROM detentions WHERE date = '$today' AND attended='yes'

Dynamic way to get a list of ticked checkboxes on a php generated page

I've got a webpage that returns a dynamic number of rows from a mysql db, which is output to the webpage via table, of which the first column is a checkbox via the following code:
while($row = mysql_fetch_array($result))
{
$id = $row['circuit_id'];
echo "<tr>";
echo "<td align=\"center\"><input name=\"checkbox[]\" type=\"checkbox\" id=\"checkbox[]\" value=" . $row['circuit_id'] . "></td>";
if ($row['status_name'] == 'Disconnected') {
echo "<td><font color=\"red\">" . $row['status_name'] . "</font></td>";
} else {
echo "<td>" . $row['status_name'] . "</td>";
};
echo "<td>" . $row['circuit_name'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td>" . $row['circuit_appID'] . "</td>";
echo "<td><img src=\"images/icons/application_edit.png \"></td>";
echo "<td><img src=\"images/icons/note_add.png \"></td>";
echo "</tr>";
}
echo "</table>";
below this data presentation, I've added a few HTML buttons (one of which is shown below) that will allow the user to do 'mass' updates on the shown data, in this particular case to change the status from one state to another via the checkbox selection.
echo "<table align=\"center\">";
echo "<tr>";
echo "<td>Set status to Migrated for selected records</td><td><img src=\"images/icons/application_edit.png \"></td>";
echo "</tr>";
echo "</table>";
Is there a way to get the list of checkboxes that have been selected without changing everything to forms, and using a simple html based button to submit the request to the server?
I've been looking for an online solution for something like this via javascript but haven't managed to find anything that matches what I need.
Thanks
I've tried to piece together a few bits and pieces to get where I need to be, but am not making much progress at all, here's the current code:
var obj = {}
$('#click').on('click', function() {
$('input[type="checkbox"]').each(function() {
var name = $(this).attr('id');
obj[name] = $(this).is(':checked') ? 1 : 0;
});
$.each(obj, function(key, value) {
alert(key + ' : ' + value);
});
console.log(obj);
});​
how do I get the list of 'true' ie. ticked boxes into a string and update the button with a 'new' url?
Any help is appreciated...
jQuery has the option to select all checkboxes and submit them in the background via AJAX..
jQuery Selectors: http://api.jquery.com/category/selectors/
jQuery AJAX: http://api.jquery.com/jQuery.ajax/
Good luck and hope this helps you!

Categories

Resources