New lines HTML if value changed in MySql Output via PHP - 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.

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 ) { … }

Dictionary to table in PHP and HTML and sort number

I have a "dictionary" that I got from my MySQL table ( string from MySQL) :
$MyInitialData={"Siberian husky dog": 0.763, "gnawing mammal": 0.736, "azure color": 0.976, "lapin rabbit": 0.715, "rabbit": 0.726, "animal": 0.932, "mammal": 0.736, "domestic animal": 0.849, "malamute dog": 0.53, "dog": 0.848}
I would like to display it this way in my HTML page using PHP code:
the difficulties are the transformation from "dictionary" to a table and sorting the data in order from the highest value to the lowest.
EDIT: as requested below, here is how I get the data from My DB:
<?=$dbContent = str_ireplace($keyword,'<b>'.$keyword.'</b>',$search_data['meta_description']); ?></p>
I do not have hands on the MySQL table. I receive it and have to sort it myself.
And yes, I also asking how to display it on HTML using a recursive formula/code ( going thru the table )
I want to avoid this style:
<table>
<tr>
<th>My Data :</th>
<th>My Values</th>
</tr>
<tr>
<td>azure color</td>
<td>0.976</td>
</tr>
<tr>
<td>animal</td>
<td>0.932</td>
</tr>
etc...
</table>
And do something with iterations based on the size of my dictionary.
What is more, I do not know the exact number of row each table may would be

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>

Getting table elements in same row with jquery

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());
?>

Ajax - PHP auto refresh looped data without relooping everything

From the looped data I'd like to auto refresh only the data retrieved from the database, and not the whole layout. Currently I re-loop the complete layout but that seems somewhat clumsy (this table is a simplified example). Some direction or advice is appreciated!
<?
//.. rawdata.php ..//
while($row = mysql_fetch_array($result)) {
//building table by looping
?>
<tr>
<td><? echo $row['uniqueid']; ?></td>
<td><? echo $row['firstname']; ?></td>
<td><? echo $row['surname']; ?></td>
</tr>
<?
}
?>
<!-- index.php -->
<script type="text/javascript">
var auto_refresh = setInterval(function() {
$('#loadRawData').load('rawdata.php');
}, 5000);
</script>
<!--...-->
<div id="loadRawData"></div>
If you only update or add records, you could add a “version” column to your table. Each time you update a row, or insert a new row, you increment the version and add it to the row.
You transmit the version to the client (it's a MAX on the version column). When the client does its “refresh” request, it sends you the version it had last downloaded, and you simply send the rows that verify a condition such as WHERE version > clientVersion.
It will be trickier if rows may be deleted, because in that case you will need to keep track of deleted rows in the table, in order to forward the “delete” operations to the clients. But you can manage them with the same “version” mechanism.

Categories