Getting table elements in same row with jquery - php

I am really confused about how I can do this. I need to get the value of two <td> when one is selected. For example, below let's say I select the td with id=monthly of $550 dollars. I need to get the age and excess that corresponds with that price. I hope this makes sense. SO in the example of selecting $550 I need jQuery to get the values age(18-24) and excess($1000). I then will take these two values and insert into mysql as noted below. Is there anyway I can do this with either jQuery or PHP? I am open to ideas.
<table>
<tr>
<td width="67"></td>
<td width="102" id="excess">$1000</td>
<td width="102" id="excess">$2000</td>
</tr>
<tr>
<td width="67" id="age">18-24</td>
<td width="102" id="monthly">$550</td>
<td width="102" id="monthly">$650</td>
</tr>
<tr>
<td width="67" id="age">25-29</td>
<td width="102" id="monthly">$750</td>
<td width="102" id="monthly">$850</td>
</tr>
</table>
MYSQL(using the example above):
$query = mysql_query("UPDATE table SET Monthly = '$550' WHERE Age = '18-24' AND Excess = '$1000'")or die(mysql_error());

Your HTML is invalid. You cannot have more than one element with the same id, id values (as the name suggests) must be unique. If you're trying to classify elements, use a class. The rest of this answer assumes those id values have been changed to class names.
If I understand you, you want to handle clicks on cells with the monthly class and get the text of the first cell in the row along with the first cell in the column. This is easily done with jQuery (live example | source):
$("td.monthly").click(function() {
var $this = $(this),
firstCellInRow = $this.closest('tr').find('td').first(),
firstCellInColumn = $this.closest('table').find('tr').first().find('td').eq($this.index());
console.log("First cell in row: " + firstCellInRow.text());
console.log("First cell in column: " + firstCellInColumn.text());
});
We find the first cell in the row by finding the row via closest, then finding its first cell via find and first.
We find the first cell in the column by finding the table via closest, then getting the first row via find and first, then getting the index of the clicked cell and finding the cell in the first row with the same index via eq.

$('.monthly').bind('click', function()
{
lstrMonth = $(this).html();
lstrAge = $(this).parent().find('td:first').html();
lnIndex = $(this).parent().index($(this));
lstrExcess = $(this).parent('table').find('tr:first td:nth-child('+ (lnIndex + 1) +')');
// do ajax call to a php script which execute the query
$.post('ajax/update.php',
{
age: lstrAge,
excess: lstrExcess,
month: lstrMonth
},
function(data) // success
{
// do whatever you want
});
});
I think this will work, the PHP will simplified look like:
<?php
$query = mysql_query("UPDATE table SET Monthly = '".$_POST['month']."' WHERE Age = '".$_POST['age']."' AND Excess = '".$_POST['excess']."'")or die(mysql_error());
?>

Related

Getting id from a textarea in a while loop in PHP for updating in mysql

I have a table where is one week displayed (each row is one day).
I get the rows from a while loop from my database. The rows are displayed in bootstrap accordions.
There is a textarea in every accordion row where the user can input (update) some text.
I want to update this text into my database. It should update the text depending on the day id.
<form method="POST" action="">
<table class="table table-hover" style="border-collapse:collapse;">
<thead>
<tr>
<th>Weekday</th>
<th>Date</th>
</tr>
</thead>
<tbody>
<?php
// Select Statement (for shortening not included into this Stack question)//
while($row = $statement->fetch()) {
$thedate = $row['Date'];
$weekday=strftime("%A", strtotime($thedate));
$date=date('d-m-Y', strtotime($thedate));
echo "<tr data-toggle='collapse' data-target=#".$row['Date']." class='clickable collapse-row collapsed'>";
echo "<td >".$weekday."</td>";
echo "<td>".$date."</td>";
echo" <td style='color:black; font-size:20px;'><i class='fas fa-angle-down'></i></td>";
echo "</tr>";
echo "<tr><div class='accordian-body collapse' id=".$row['Date'].">
<td colspan='1' class='hiddenRow'><textarea name=".$row['id']." rows='5' cols='80'>".$row['Text']." </textarea></td>
//the $row['id'] should give every textarea a unique dayid from my database
echo"</td>
</div></tr>";
}
if(ISSET($_POST['id'])){
$debug=$_POST['id'];
}
var_dump($debug); // var_dump for debugging. See text below
?>
</tbody>
</table>
<button type="submit" name="Speichern" class="btn btn-lg btn-primary btn-block">Speichern</button>
</form>
Before writing the Sql Update Statement I wanted to debug to find possible bugs.
If i debug this with var_dump I get the error message "Undefined variable $debug" and I dont know why. The variable shouldnt be empty because in the textareas is always text.
Im new to PHP and coding at all so probably Im making a dump mistake.
EDIT: If I put the var_dump inside the if condition i get nothing as return.
I tried it also with the var_dump in the if block but then i get nothing as return.
That’s because you do not have any form field that is actually named id. You put name=".$row['id']." on your textarea, and that is likely a numeric value. And you probably don’t know which one that will be, on the receiving end.
Plus, since you are creating multiple such fields in a loop, PHP will overwrite all values for this parameter with the last one. You need to use a naming scheme that includes square brackets to avoid that, something like name="foo[]" - then $_POST['foo'] will become an array that you can loop over.
And since you will still need your record ID to associate with the data, you can put that into the brackets, name="foo[123]" – then this 123 will become the key of that array element, for this specific textarea.
If you loop over that using the extended foreach syntax, then you have easy access to the ID, and the value entered by the user:
foreach( $_POST['foo'] as $id => $value ) { … }

New lines HTML if value changed in MySql Output via PHP

This is the HTML/PHP , I am using to display some data.
<body>
<section>
<h1>Facebook Search</h1>
<!-- TABLE CONSTRUCTION-->
<table>
<tr>
<th>Comment</th>
<th>Comment Made By</th>
<th>Commentor's Profile Link</th>
<th>Comment ID</th>
<th>Post ID</th>
</tr>
<!-- PHP CODE TO FETCH DATA FROM ROWS-->
<?php // LOOP TILL END OF DATA
while($rows=$result->fetch_assoc())
{
?>
<tr>
<!--FETCHING DATA FROM EACH
ROW OF EVERY COLUMN-->
<td><?php echo $rows['comtext'];?></td>
<td><?php echo $rows['comby'];?></td>
<td><?php echo $rows['compro'];?></td>
<td><?php echo $rows['commentid'];?></td>
<td><?php echo $rows['postid'];?></td>
</tr>
<?php
}
?>
</table>
</section>
</body>
</html>
and I am getting the data like this from the db.
$sql = "SELECT comments.*, posts.postid FROM comments JOIN posts USING(postid)";
$result = $mysqli->query($sql);
$mysqli->close();
This outputs a single table with all the data. My question is , is there a way to break the single table into tables when the value of postid changes? It goes like..is 1 for x number of rows, then 2 for x number of rows and so on. I wanted to have a little break between those tables.
is there a way to break the single table into tables when the value of postid changes
You should stop using "SELECT *", it's inefficient and makes code difficult to maintain. While we're talking about style here, you swap back and forth between PHP and inline HTML which also impacts the readability of your code.
As to your question...
You need to ensure that the output of your query is sorted by postid - or you're going to get a lot of tables.
Use a state variable to track the postid from the previous iteration of the loop.
$prev=0;
while($rows=$result->fetch_assoc()) {
if ($rows['postid']!=$prev) {
close_table();
open_table();
$prev=$rows['postid'];
}
output_row($rows);
}
close_table();
The problem with this is that each iteration of the expects that you've already written <table> to the output stream - including the first iteration. You could do this before the loop - but you'll end up with an empty table at the top of the page. You could add another state variable to track whether you have opened a table tag yet. Personally, I'd go with making inferences from the value of the existing state variable:
$prev=0;
while($rows=$result->fetch_assoc()) {
if ($rows['postid']!=$prev) {
$prev || close_table();
open_table();
$prev=$rows['postid'];
}
output_row($rows);
}
close_table();
(the || is a quick way of writing if (not(condition)) do something() )
Note that unless you fix the size of the columns, then each table will be independently sized to fit the data that resides within it.

Multi Dimensional Array Challenge

I have been reading endless posts today on php arrays, and multidimensional arrays ... I'm a tad confused :)
I have a mySql table that has rows that consist of the following columns:
name, email, choice1, choice2, choice3, choice4, choice5, choice6, choice7, choice8, choice9, choice10
I'm populating an array as follows:
while($row = mysql_fetch_assoc($result)){
$allResults[$index] = $row;
$index++;
}
I know I can access the data by $allResults[0][name]; that all is fine.
However here is what I'm trying to do.
One of the rows will include a piece of data: IPO3_1 (it would be in one of the choice columns)
I need to cycle through all of the rows in the array, find this data and then pull out the name column. Here is very rough code of my ultimate goal (although incomplete as I cannot get my head around this)
<TR>
<?php
if (in_array("IPO3_1", $allResults[0])||in_array("IPO3_1", $allResults[1])) {
?>
<TD WIDTH="30" ALIGN="CENTER"><input type="checkbox" name="sp1" value="IPO3_1" DISABLED></TD>
<?php
} else {
?>
<TD WIDTH="30" ALIGN="CENTER"><input type="checkbox" name="sp1" value="IPO3_1" ></TD>
<?php
}
?>
<TD WIDTH="210" ALIGN="LEFT"> IPO3 - 1st</TD>
<TD WIDTH="40" ALIGN="CENTER">$120</TD>
<TD WIDTH="270" ALIGN="CENTER"><?php echo $allResults[0][name]; ?></TD>
</TR>
Basically when I find the value "IPO3_1" in any row, I need to disable a checkbox , and also add the name into the table
There could be as many as 34 rows in my mySql table maximum. THere are 34 values similiar to "IPO3_1" but are all unique text strings.
Any thoughts to get me pointed in the right direction ?
I've written as undestood the task. But I'm not shure in my undestanding :)
// $row will be false if string will be not found anywhere
// else it will be index of row, in wwhich first occurence found
$row = false;
foreach($allResults as $key=>$value) {
// remove non-'choice' fields
unset($value['name']);
unset($value['email']);
// Lookup the string in other field
if(in_array('IPO3_1', $value, true))
// if found break the loop
{ $row = $key; break; }
}

Get the row number onclick using Ajax

I have wore below code and its working.But I want row number when a ROW clicked(Hope Ajax is okay) and pass it to a php code in same page. I tried javascript it worked,bt not in the way I want. If its in Ajax its better. Any HELP would b gratefull :)
if(isset($_POST['search'])){
$search=mysqli_query($con,"SELECT * FROM bus_fares WHERE route_no='$_POST[route_no]'");
$num_rows = mysqli_num_rows($search);
$search1=mysqli_query($con,"SELECT fare FROM fare limit $num_rows ");
$x = 0;
echo" <table id='my_table'><tr><th>Fare Stage</th>
<th>Location</th>
<th>Fare</th>
</tr>";
while($row=mysqli_fetch_assoc($search) and $row1=mysqli_fetch_assoc($search1)){
echo"<tr>";
echo"<td>".$x."</td>";
echo"<td>".$row['location']."</td>";
echo"<td>".$row1['fare']."</td>";
echo"</tr>";
$x++;
}
echo"</table>";
}
What you really want is to not only store the visual data in your table but also some sort of meta data. There are several ways to achieve this.
Method #1: (ab)use the id or class attributes:
The resulting HTML would look like this:
<!-- example with the id-attribute: -->
<tr id="mysql_row_1"> ... </tr>
<tr id="mysql_row_2"> ... </tr>
<!-- example with the class-attribute: -->
<tr class="mysql_row_1"> ... </tr>
<tr class="mysql_row_2"> ... </tr>
This would both generate valid HTML but you would abuse attribute-tags for a purpose they're not implemented for, what is generally regarded as bad. Imagine if you had to store more than just one value. You could assign multiple classes, but you'd get stuck with the id-tag then. Therefore: don't do this!
You'd have to change your code like this to achieve this solution:
(I assume you want the value of $x as the rownumber.)
while ($row=mysqli_fetch_assoc($search) and $row1=mysqli_fetch_assoc($search1)) {
echo '<tr class="mysql_row_'.$x.'" onclick="getRowNumber()">';
echo "<td>".$x."</td>";
echo "<td>".$row['location']."</td>";
echo "<td>".$row1['fare']."</td>";
echo "</tr>";
$x++;
}
The javascript part:
function getRowNumber() {
var rowNumber = this.className.replace("mysql_row_",""); // fetches the classname and removes the extra-strings
alert(rowNumber); // alerts "1", "2", ...
}
Method #2: Use the data-* attributes:
This solution is valid for HTML5. Please add additional information regarding compatibility if you have some.
Your HTML Code will look like this:
<tr data-mysql_row_number="1" onclick="getRowNumber()"> .... </tr>
<tr data-mysql_row_number="2" onclick="getRowNumber()"> .... </tr>
And the modified javascript:
function getRowNumber() {
alert(this.getAttribute("data-mysql_row_number")); // alerts "1", "2", ...
}
This also generates perfectly valid HTML(5) code and lets you store infinite endless amounts of information since you can specify as many data-* attributes as you want to.
Method #3: use invisible <input> fields:
The resulting HTML code:
<tr onclick="getRowNumber()">
<td>
Normal content of this field
<input type="hidden" name="mysql_row_number" value="1"/>
</td>
</tr>
And the JS code to fetch the values:
function getRowNumber() {
var rowNumber = this.getElementsByName('mysql_row_number')[0].value;
alert(rowNumber); // alerts "1", "2", ...
}
This as well produces valid HTML but is semantically not really correct in my opinion, since the data inside the <input> fields is some kind of loose and not directly connected to the row. Plus you can make multiple <input> fields with the same name.
I would suggest method #2 ( data-* ), as this is the most flexible solution and uses an attribute that has been designed to store meta-data.
Method #1 would work the most reliable across all (older) browsers since all of them support acces to the id or class attribute via JS, as long as you keep the id tag unique.
Method #3 will also be quite reliable with older browsers.
Instead of echo"<tr>"; do :
echo "<tr id='row_".$row['id']."'>";
then when a tr is clicked, just retrieve $(this)[0].id like that with jQuery inside a script tag (be sure jQuery is included, it's a powerful JS library, google it for additional informations) :
<script>
$("#my_table").on("click", "tr", function(){
alert($(this)[0].id.replace("row_", ""));
});
</script>

Dynamic texbox modification with ajax/php/javascript

I have two tables. company_details and company_specials. Each company_details can have multiple specials. I display the company details at http://eurothermwindows.com/ed/admin.php
The first row and fourth row that has the 0 in the active column is from company_details and the rows below are from company_specials.
Currently the code allows for dynamic modification of the company_details rows as denoted by the compid in that table. However i would like to have the rows below it to be dynamically modified as well but it's using the same compid and i'm not sure how to separate them in the code.
Code below is the code being generated for the company_specials. I need a way to uniquely identify each row and be able to modify it.
http://pastebin.com/RAe9iwAP
Could somebody provide some guidance please? I'm thinking that i would probably need to uniquely identify each of the specials within the company_specials or set some sort of pointers?
Q.I need a way to uniquely identify each row
A. you already are doing so;
<tr id="<?php echo $compid; ?>"
Q. and be able to modify it.
A. add a input button before the end of each row, that onclick="edit(<?php echo $compid; ?>)" and launches the editing cycle based on the $compid for that row.
Then using Javascript you can extract the contents of all the <td></td> within the row by the $compid in the tr like this;
var originalString = "<tr>" + document.getElementById(compid).innerHTML + "</tr>";
var targetArray = [];
$(originalString) /*.find("tr")*/ .each(function(index, tr) {
targetArray = $("td", tr).map(function(index, td) {return $(td).text();});
});
all of the <td> contents will be in targetArray variable accessible to be put into a form for editing like so;
document.getElementById("forminputid").value = targetArray[1];

Categories