Limiting column for fetched data in php - php

I am trying to put extracted mysql data into a table using php. The issue is that I am able to put the fetched data into either all rows or all columns. What I would like to do is put the fetched data into a column format and as soon as 4 columns are used, the next data should start on the next row and so on.
Currently I am using the logic below, however I am getting everything in a column.
The goal is to limit the data to a page size so the data can be printed.
<div>
$result = mysql_query("SELECT * FROM master_data");
echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
while($row = mysql_fetch_array($result))
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?></div>

If I understand your problem correctly you will want to do something like:
Keep a counter to see which number record you're looking at ($i)
$i = 0; // Your counter
while($row = mysql_fetch_array($result))
{
// ...
On every 4th iteration of the loop output something like </tr><tr>.
if ($i % 4 == 0 && $i > 0) // Will return true if `$i` is a multiple of 4 and greater than 0
{
echo "</tr><tr>"; // Output your HTML to start a new row
}
One final note: As others will be pointing out. You should avoid using the MySQL extension. You should use MySQLi or PDO instead.

<div>
$result = mysql_query("SELECT * FROM master_data");
echo "<table border='1'>
<tr>
<th>Accounts</th>
</tr>";
echo "<tr>";
$i = 1;
while($row = mysql_fetch_array($result))
{
if($i == 4)
{
echo "<td>";
echo "First Name:" . $row['First_Name'] . "</br>";
echo "Middle Name:" . $row['Middle_Name'] . "</br>";
echo "Last Name:" . $row['Last_Name'] . "</br>";
echo "</td>";
$i=0;
}
$i++;
}
echo "</tr>";
echo "</table>";
mysql_close($con);
?>
</div>

Related

select table from PHP MyAdmin using PHP file

Good day,
I am trying to select a table from MySQL and generaly I use this code:
$sql="CALL selectCreatedTableByName('".$tableNameIn."')";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table id='restable'>";
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['nameE'] . "</td>";
echo "<td>" . $row['nameN'] . "</td>";
echo "</tr>";
}
echo "</table>";
}
$conn->close();
but now, when I don't know the names of the table's columns, how can I select this table?
Thank you so much.
You are not selecting the table, you are selecting from the table. (at least I'm guessing that is the case since we don't know what your procedure actually does).
The PHP array returned uses the attribute names from the resultset as keys hence....
while($row = $result->fetch_assoc()) {
echo "<tr>\n";
foreach($row as $name=>$value) {
echo "<td>$value</td>\n";
}
echo "</tr>\n";
}
If you want a header row, then use a state variable to flag the first row.
$fetched=0;
while($row = $result->fetch_assoc()) {
if (!fetched) {
echo "<tr>\n";
foreach($row as $name=>$value) {
echo "<th>$name</th>\n";
}
echo "</tr>\n";
}
$fetched++;
echo "<tr>\n";
foreach($row as $name=>$value) {
echo "<td>$value</td>\n";
}
echo "</tr>\n";
}

Find % according to values in one column (Need to add iteration loop) in php

I want to update 3rd column according to values based in 2nd column. Right to now I could print % value only for 1st team correctly. Other teams have wrong values.
Any help please.
echo "<table border="."1"."align="."right".">
<tr>
<th align="."center".">ID</th>
<th>Internal Team Names</th>
<th width="."10px"." >Passed % for aw34_0530_tc1015</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['TeamInternalNames'] . "</td>";
$TotalTestsForTeam = mysqli_query($conn ,"SELECT * from aw34_0530_tc1015 where Application="."'".$application_l."'"); //rows for ace application
$TotalTestsForTeamCount = $TotalTestsForTeam->num_rows; //rows for ace application
$PassedTestsForTeam_query= "SELECT * from aw34_0530_tc1015 where Result='passed' AND Application='".$row['TeamInternalNames']."'"; //ace passed count
$passed = mysqli_query($conn ,$PassedTestsForTeam_query);
$TotalPaassedTestsForTeam = $passed->num_rows; //rows for ace application
//echo "Count of passed ace in aw34_0530_tc1015 = TotalPaassedTestsForTeam Results "; //rows for ace application
$passed_percentForTEam = ($TotalPaassedTestsForTeam/$TotalTestsForTeamCount)*100 | 0;
echo "<td>" . $passed_percentForTEam . "</td>";
// if ($row['Result'] == "passed") {
// echo "<td style="."background-color:#33FF38".">P</td>";
// } else {
// echo "<td style="."background-color:#FF334C".">F</td>";
// }
echo "</tr>";
}
echo "</table>";

How to display dates in two html tables side by side according to month?

I am trying to display status of employee for each date in a month in the given application.
i have divided data in two tables.
Now, if you can see , My tables are displaying dates correctly.
But i want to start new table for each month. i.e. whenever 1st date of new month begins, i want to start the procedure of rendering dates for the month again.
So i will be able to distinguish them by their months.
I hope i have explained the problem correctly.
Please provide guidance on this .
Thanks in advance.
My code for the given problem :
<?php
$name=$_SESSION['sess_username'];
$dateofattendance=$_SESSION['sess_date'];
$time="00-00-00";
$status="absent";
$counter=0;
$conn = new mysqli('localhost', '', '', 'test');
$sql="SELECT dateofattendance,timeofattendance, status,timeofdeparture FROM attendance Where emp='$name' ORDER BY dateofattendance ASC ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table class='main'><tbody><tr><td >";
// create the opening table
echo "<div align='left'><table class='sep1'style='float:left;'; border='black' cellpadding='5' ><thead> <tr><th> Date </th><th>IN</th><th>OUT</th><th>Status</th></tr></thead>tbody>";
while($row = $result->fetch_assoc())
{
// create the row
echo "<tr><td>" . $row["dateofattendance"]. "</td><td>" . $row["timeofattendance"]. "</td><td>" . $row["timeofdeparture"]. "</td>";
if($row["status"]=='present')
{
echo "<td ><span class='label label-success'>". $row["status"]."</span></td>";
}
else
{
echo "<td><span class='label label-danger'>". $row["status"]."</span></td>";
}"
</tr>";
$counter++;
// when the counter is 15, close this table and open another
if($counter == 15)
{
echo "</td><td>"; // move to the next cell in our wrap table
echo "</tbody></table></div> ";
echo "<table class='sep2'style='float:left;'border='black'cellpadding='5'><thead> <tr><th> Date </th><th>IN</th><th>OUT</th><th>Status</th></tr></thead><tbody>";
}
}
// close the last table
echo "</tbody></table>";
// close our wrapper table
echo "</td></tr></tbody></table>";
}
$conn->close();
?>
Instead of having a counter and creating a new table when it hits 15, you want to have a variable that stores the month number of the last row rendered, and check if the month number of the next row to be rendered matches. If it doesn't match, generate a new table.
The following code is produces the results you want. I've tested it with a database table with identical structure (table named "test_employees").
Note, the code outputs valid HTML and I re-formatted the echo statements and added newline chars to make the both the PHP and HTML source code more readable.
This code could be cleaned up considerably, so it's by no means good production code, but again, it demonstrates the logic you are after.
One item to note, the code only works within a given year. Additional code would be required if you wanted to display tables across multiple years.
If this helps you, please mark my answer.
I can also spend more time to refactor this code if you want. Let me know and I'll reply faster the next time.
<!DOCTYPE html>
<html>
<head>
<title>table test</title>
</head>
<body>
<?php
$name=$_SESSION['sess_username'];
$dateofattendance=$_SESSION['sess_date'];
$time="00-00-00";
$status="absent";
$counter=0;
$conn = new mysqli('localhost', '', '', 'test_employees');
$sql="SELECT dateofattendance,timeofattendance, status,timeofdeparture FROM attendance Where emp='$name' ORDER BY dateofattendance ASC ";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
echo "<table border='1'>";
echo "<thead>";
echo "<tr>";
echo "<th>Date</th>";
echo "<th>IN</th>";
echo "<th>OUT</th>";
echo "<th>Status</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
$first_iteration = 1;
$row = $result->fetch_array(MYSQLI_ASSOC);
$last_month_num = split('-', $row["dateofattendance"])[1];
while($row = $result->fetch_assoc())
{
$current_month_num = split('-', $row["dateofattendance"])[1];
if ($first_iteration == 1) { // do nothing the first time around
$first_iteration = 0;
}
else if ($current_month_num == $last_month_num) { // only close row in current table
echo "</tr>";
}
else { // close table and start new table
echo "</tr>";
echo "</table>";
echo "<table border='1'>";
echo "<thead>";
echo "<tr>";
echo "<th>Date</th>";
echo "<th>IN</th>";
echo "<th>OUT</th>";
echo "<th>Status</th>";
echo "</tr>";
echo "</thead>";
echo "<tbody>";
}
echo "<tr>" . "\n";
echo "<td>" . "\n" . $row["name"] . $row["dateofattendance"] . "\n" . "</td>" . "\n";
echo "<td>" . "\n" . $row["timeofattendance"] . "\n" . "</td>" . "\n";
echo "<td>" . "\n" . $row["timeofdeparture"] . "\n" . "</td>" . "\n";
if($row["status"]=='present')
{
echo "<td><span class='label label-success'>". $row["status"]."</span></td>";
}
else
{
echo "<td><span class='label label-danger'>". $row["status"]."</span></td>";
}
$counter++;
$last_month_num = split('-', $row["dateofattendance"])[1];
}
echo "</tr>";
echo "</table>";
}
$conn->close();
?>
</body>
</html>

Retrieve data from sql database and display in tables - Display certain data according to checkboxes checked

I have created an sql database(with phpmyadmin) filled with measurements from which I want to call data between two dates( the user selects the DATE by entering in the HTML forms the "FROM" and "TO" date) and display them in a table.
Additionally I have put, under my html forms, some checkboxes and by checking them you can restrict the amount of data displayed.
Each checkbox represent a column of my database; so along with the date and hour column, anything that is checked is displayed(if none is checked then everything is displayed).
So far I managed to write a php script that connects to the database, display everything when none of my checkboxes is checked and also managed to put in order one of my checkboxes.
Problem: The data that I call for are been displayed twice.
Question: I want to have four checkboxes.
Do I need to write an sql query for every possible combination or there is an easier way?
<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_Database_Test = "localhost";
$database_Database_Test = "database_test";
$table_name = "solar_irradiance";
$username_Database_Test = "root";
$password_Database_Test = "";
$Database_Test = mysql_pconnect($hostname_Database_Test, $username_Database_Test, $password_Database_Test) or trigger_error(mysql_error(),E_USER_ERROR);
//HTML forms -> variables
$fromdate = $_POST['fyear'];
$todate = $_POST['toyear'];
//DNI CHECKBOX + ALL
$dna="SELECT DATE, Local_Time_Decimal, DNI FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$tmp ="SELECT * FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$entry=$_POST['dni'];
if (empty($entry))
{
$result = mysql_query($tmp);
echo
"<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>
<th>Solar_time_decimal</th>
<th>GHI</th>
<th>DiffuseHI</th>
<th>zenith_angle</th>
<th>DNI</th>
";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal'] . "</td>";
echo "<td>" . $row['Solar_Time_Decimal'] . "</td>";
echo "<td>" . $row['GHI'] . "</td>";
echo "<td>" . $row['DiffuseHI'] . "</td>";
echo "<td>" . $row['Zenith_Angle'] . "</td>";
echo "<td>" . $row['DNI'] . "</td>";
echo "</tr>";
}
echo '</table>';}
else
{
$result= mysql_query($dna);
echo
"<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>
<th>DNI</th>
";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal']."</td>";
echo "<td>" . $row['DNI'] . "</td>";
echo "</tr>";
}
echo '</table>';
}
if($result){
echo "Successful";
}
else{
echo "Enter correct dates";
}
?>
<?php
mysql_close();
?>
Try to create your checkbox like below:
Solar_Time_Decimal<checkbox name='columns[]' value='1'>
GHI<checkbox name='columns[]' value='2'>
DiffuseHI<checkbox name='columns[]' value='3'>
Zenith_Angle<checkbox name='columns[]' value='4'>
DNI<checkbox name='columns[]' value='5'>
And try to hange your PHP code to this:
<?php
//HTML forms -> variables
$fromdate = isset($_POST['fyear']) ? $_POST['fyear'] : data("d/m/Y");
$todate = isset($_POST['toyear']) ? $_POST['toyear'] : data("d/m/Y");
$all = false;
$column_names = array('1' => 'Solar_Time_Decimal', '2'=>'GHI', '3'=>'DiffuseHI', '4'=>'Zenith_Angle','5'=>'DNI');
$column_entries = isset($_POST['columns']) ? $_POST['columns'] : array();
$sql_columns = array();
foreach($column_entries as $i) {
if(array_key_exists($i, $column_names)) {
$sql_columns[] = $column_names[$i];
}
}
if (empty($sql_columns)) {
$all = true;
$sql_columns[] = "*";
} else {
$sql_columns[] = "DATE,Local_Time_Decimal";
}
//DNI CHECKBOX + ALL
$tmp ="SELECT ".implode(",", $sql_columns)." FROM $database_Database_Test.$table_name where DATE>=\"$fromdate\" AND DATE<=\"$todate\"";
$result = mysql_query($tmp);
echo "<table border='1' style='width:300px'>
<tr>
<th>DATE</th>
<th>Local_Time_Decimal</th>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries)))
echo "<th>$v</th>";
}
echo "</tr>";
while( $row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td>" . $row['DATE'] . "</td>";
echo "<td>" . $row['Local_Time_Decimal'] . "</td>";
foreach($column_names as $k => $v) {
if($all || (is_array($column_entries) && in_array($k, $column_entries))) {
echo "<th>".$row[$v]."</th>";
}
}
echo "</tr>";
}
echo '</table>';
if($result){
echo "Successful";
}
else{
echo "Enter correct dates";
}
?>
<?php
mysql_close();?>
This solution consider your particular table columns but if your wish a generic solution you can try to use this SQL too:
$sql_names = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '$database_Database_Test' AND TABLE_NAME = '$table_name'";
and use the result to construct the $column_names array.
Solution for your problem : Change the mysql_fetch_assoc with mysql_fetch_array
If you have the same problem try to print your result with print_r
Answer : Use the bit datatype in mysql for store and read your checkboxes.
When you're receiving thr value from the database then you can use
in the parameter checked you can use the php code as exist :
$value = ...get the value from db ( 1 or 0 )
echo '<input type="checkbox" name="thename" value="thevalue" '.($value==1?'checked=checked'.'').'/>';

Element ID changing with each MYSQL Database insert

Ok so I have a script that pulls information from a database and puts it into a table. (the full script is at the bottom of this question)
Each TR is echoed with a standard ID: echo "<tr class='task' id='task1'>"; the only problem with this is each new tr or each row that is pulled from the database gets assigned the same ID task1 This is not good coding technique as well as not working with my javascript for changing the tables class name's based on the information from the database.
So my question is, is there a way to sort of "auto generate" the id name for each tr of the table? I would like to see task1, task2, task3 and so on.
Full code starts here
<?php
$con=mysqli_connect("");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM affiliate_tasks WHERE username = '$_SESSION[username]'";
if( isset($_POST['sort-selection']) && $_POST['sort-selection'] != 'all' )
{
$query .= " AND status = '". $_POST['sort-selection']."';" ;
}
$result = mysqli_query($con, $query);
echo "<table class='table table-message'>
<tr class='heading'>
<td class='cell-title'>Tasks</td>
<td class='cell-status hidden-phone hidden-tablet'>Status</td>
<td class='cell-time align-right'>Due Date</td>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr class='task' id='task1'>";
echo "<td class='cell-ttle'>" . $row['task_name'] . "</td>";
echo "<td class='cell-status hidden-phone hidden-tablet'>" . $row['status'] . "</td>";
echo "<td class='cell-time align=right'>" . $row['due_date'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
If your table row has an unique id column, that will be the best fit here. You can use:
echo "<tr class='task' id='task-" . $row['id'] . "'>";
If not, and you just want a sequential number, you just use a variable like this:
$i = 0;
while($row = mysqli_fetch_array($result)) {
echo "<tr class='task' id='task-" . ++$i . "'>";
// Rest of your lines ...
}

Categories