php - how to exclude a line of code in a loop - php

I have a code in HTML in a table. And I want the loop to just ignore them
<?php
$sel_admin = "query ";
$rs_admin = mysql_query($sel_admin);
while($row = mysql_fetch_array($rs_admin))
{
echo "<th>". $row['a']. "</th>";
</thead> // This two line of code
<tbody> // is the one I want to exclude in the while loop
$sel_admin2 = "query2 ";
$rs_admin2 = mysql_query($sel_admin2);
while($row2 = mysql_fetch_array($rs_admin2))
{
echo" <tr class='gradeX'> ";
echo "<td>" . $row2['sched3_time']. "</td>";
echo"</tr>";
}
}
?>
Is this even possible?

You need to end your first loop, spit out the html and then start the loop again, havent tested but i think the below should now work.
<?php
$sel_admin = "query ";
$rs_admin = mysql_query($sel_admin);
while ($row = mysql_fetch_array($rs_admin)) {
echo "<th>" . $row['a'] . "</th>";
}
?>
</thead>
<tbody>
<?php
$sel_admin2 = "query2 ";
$rs_admin2 = mysql_query($sel_admin2);
while ($row2 = mysql_fetch_array($rs_admin2)) {
echo " <tr class='gradeX'> ";
echo "<td>" . $row2['sched3_time'] . "</td>";
echo "</tr>";
}
?>

I'm guessing you want those lines printed once, not to be outside the loop, per se. You could use a variable to track it:
$linesNeeded = true;
while (...) {
...
if ($linesNeeded) {
echo $line1;
echo $line2;
$linesNeeded = false;
}
...
}

Please use mysqli instead of mysql. Take a look: MySQL vs MySQLi when using PHP
+
Your problem's answer too.
<?php
$sel_admin = "query ";
$rs_admin = mysqli_query($connection,$sel_admin);
while($row = mysqli_fetch_array($rs_admin))
{
echo "<th>". $row['a']. "</th>";
?>
</thead>
<tbody>
<?php
$sel_admin2 = "query2 ";
$rs_admin2 = mysqli_query($connection, $sel_admin2);
while($row2 = mysqli_fetch_array($rs_admin2))
{
echo" <tr class='gradeX'> ";
echo "<td>" . $row2['sched3_time']. "</td>";
echo"</tr>";
}
}
?>

This is honestly just a guess but based on the code you provided you actually need to add more code after remove the code you do not want:
<?php
$sel_admin = "query ";
$rs_admin = mysql_query($sel_admin);
while($row = mysql_fetch_array($rs_admin))
{
echo "<tr><th>". $row['a']. "</th></tr>"; // Notice the <tr></tr>
$sel_admin2 = "query2 ";
$rs_admin2 = mysql_query($sel_admin2);
while($row2 = mysql_fetch_array($rs_admin2))
{
echo" <tr class='gradeX'> ";
echo "<td>" . $row2['sched3_time']. "</td>";
echo"</tr>";
}
}
?>

Related

how to output mysql table data into an html table without knowing what $row is like phpmyadmin

Ok so I'm trying to make a localhost site that has the same base functions as Phpmyadmin, and everything is working other than displaying a table's data.
here's an example of what I'm trying to accomplish:
though I'm not sure how to accomplish this. Here is some code to show you what I have now
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$columquery = "SHOW COLUMNS FROM " . $table;
$columresult = mysql_query($columquery);
while ($row3 = mysql_fetch_array($columresult)) {
echo "<th>" . $row3['Field'] . "</th>";
}
?>
<?php
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_array($result2)) {
foreach($row2 as $var) {
echo "<tr><td>" . $var . "</td></tr>";
}
}
?>
</table>
</div>
Yes yes, I know it's horrible.
The other answers use the mysqli API while you're using the older, no longer supported mysql API. I really recommend upgrading to either mysqli or PDO, but if you want to stay with mysql you can use the following solution:
<div class="content">
<?php $query2 = "SELECT * FROM " . $table; ?>
<div class="query-class">
<?php echo $query2; ?>
</div>
<h1>
Tables In <?php echo $db; ?>
</h1>
<table>
<?php
$shouldOutputHeaders = true;
$result2 = mysql_query($query2);
while ($row2 = mysql_fetch_assoc($result2)) {
if ($shouldOutputHeaders) {
echo "<tr>";
foreach (array_keys($row2) as $header) {
echo "<th>" . $header . "</th>";
}
echo "</tr>";
$shouldOutputHeaders = false;
}
echo "<tr>";
foreach ($row2 as $var) {
echo "<td>" . $var . "</td>";
}
echo "</tr>";
}
?>
</table>
</div>
If i understood you well, You need mysqli_fetch_row.
$q= "SELECT * FROM table";
$result = $mysqli->query($q)
while ($row = $result->fetch_row()) {
print ("$row[0], $row[1]);
}
I think you are looking for something very ugly like the following. I found it in the garbage. I am not responsable for any use of it:
<?php
$db=Db::getConnection(); // singleton
$this->var['result']=$db->query($_POST['query']);
if (isset($this->var['result'])) {
echo '<table cellpadding="5" cellspacing="2" border="1"><tbody>';
$titles=array_keys(#$this->var['result'][0]);
echo '<tr>';
foreach($titles as $title)
echo '<th>'.$title.'</th>';
echo '</tr>';
foreach($this->var['result'] as $row) {
echo '<tr>';
foreach($row as $cell) {
echo '<td>'.$cell.'</td>';
}
echo '</tr>';
}
echo '</tbody></table>';
}
?>
Db is an standard singleton that contains a mysqli private object.
query() contains something like
$sql = $this->mysqli->query($query);
$this->lastInsertId = $this->mysqli->insert_id;
$errno = $this->mysqli->connect_errno;
if ($errno === 0) {
if ($this->mysqli->field_count > 0) {
while ($row = $sql->fetch_assoc()) $response[] = $row;
return $response;
}else{
return true;
}
}
to create the "array of arrays" response. Suitable for the output you are looking for.
I've added some escaping and only queried the database when needed:
// Print table tags
echo "<table>";
// Print out records
$q = mysql_query("SELECT * FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print out columns
$columns = array_keys($res[0]);
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$columns).'</th></tr>';
// Print out table data
echo'<tr><td>'.implode('</td><td>', array_map('htmlspecialchars',$res).'</td></tr>';
} else {
// IFF there is no data, print out columns
$q = mysql_query("SHOW COLUMNS FROM {$table};");
if($res = $result->fetch_all(MYSQLI_ASSOC)){
// Print columns
echo'<tr><th>'.implode('</th><th>', array_map('htmlspecialchars',$res).'</th></tr>';
}
}
echo '</table>';
Hope this helps,

creating table rowspan php

i need help with my code..how do i have output like in the image below where it will automatically insert rowspan ..my current code
$result = $cmsDB->query("SELECT * FROM ".$cmsDB->prefix("departments")."");
echo "<br /><br /><table class='table table-bordered table-striped'>
<tr>
<th>Bil</th>
<th>Department</th>
<th>Staff</th>
</tr>";
$count =1 ;
while($row = $cmsDB->fetchArray($result))
{
$deptid=$row['deptid'];
$deptname=$row['deptname'];
echo "<tr><td>".$count++."</td><td>".$deptname."</td><td>";
global $cmsDB;
$result2 = $cmsDB->query("SELECT * FROM ".$cmsDB->prefix("staff")." WHERE deptid=$deptid");
while($row = $cmsDB->fetchArray($result2))
{
$name=$row['name'];
echo "".$name." <br />";
}
}
echo "</td></tr></table>";
current output and desired results
Please Note: By design performing two queries for this just a bad idea. Still going with that. All you need to do is to perform the second query ahead of creating the block. Record the counts of the result Data and use that as rowSpan. Quite Simple.
global $myDB;
$result2 = $myDB->query("SELECT * FROM ".$myDB->prefix("staff")." WHERE deptid=$deptid");
$rowSpan=$result2-num_rows;
echo "<tr>"
echo "<td rowspan=" . $rowSpan . ">" . $count++ . "</td>";
echo "<td rowspan=" . $rowSpan . ">".$deptname."</td>";
The second while loop must output
<td>$name</td></tr>
The important thing is to close the table row inside the while loop also start a new table row in case you are printing a second name for the same dept.
$result = $cmsDB->query("SELECT * FROM ".$cmsDB->prefix("departments")."");
echo "<br /><br /><table class='table table-bordered table-striped'>
<tr>
<th>Bil</th>
<th>Department</th>
<th>Staff</th>
</tr>";
$count =1 ;
while($row = $cmsDB->fetchArray($result))
{
$deptid=$row['deptid'];
$deptname=$row['deptname'];
global $cmsDB;
$result2 = $cmsDB->query("SELECT * FROM ".$cmsDB->prefix("staff")." WHERE deptid=$deptid");
$num_rows = $cmsDB->getRowsNum($result2);
$rowSpan=$num_rows;
echo "<tr>";
echo "<td rowspan=" . $rowSpan . ">" . $count++ . "</td>";
echo "<td rowspan=" . $rowSpan . ">".$deptname."</td>";
while($row = $cmsDB->fetchArray($result2))
{
$name=$row['name'];
echo "<td>$name</td></tr>";
}
}
echo "</table>";
I used this logic and it worked perfectly. You can try this.
$result = get_pending_sales_order_details(ST_SALESORDER, $_POST['customer_id'],null);
$order_count=0;
$array_ord=array();
while ($myrow = mysql_fetch_array($result))
{
$result23 = get_pending_sales_order_details(ST_SALESORDER, $_POST['customer_id'],$myrow["order_no"]);
$row_span = mysql_num_rows($result23);
start_row();
if($currentorg != $myrow["order_no"])
{
label_cell($myrow["order_no"], "rowspan='".$row_span."' align=center");
}
label_cell($myrow["stk_code"], "align=center");
label_cell($myrow["description"], "align=left");
label_cell($myrow["pending_quantity"], "align=center");
end_row();
$currentorg = $myrow["order_no"];
}

Writing the attributes of a database in PHP

I am writing an application in which user can enter a database name and I should write all of its contents in table with using PHP.I can do it when I know the name of database with the following code.
$result = mysqli_query($con,"SELECT * FROM course");
echo "<table border='1'>
<tr>
<th>blablabla</th>
<th>blabla</th>
<th>blablabla</th>
<th>bla</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['blabla'] . "</td>";
echo "<td>" . $row['blablabla'] . "</td>";
echo "<td>" . $row['bla'] . "</td>";
echo "</tr>";
}
echo "</table>";
In this example I can show it since I know the name of table is course and it has 4 attributes.But I want to be able to show the result regardless of the name the user entered.So if user wants to view the contents of instructors there should be two columns instead of 4.How can I accomplish this.I get the table name with html.
Table:<input type="text" name="table">
Edit:Denis's answer and GrumpyCroutons' answer are both correct.You can also ask me if you didnt understand something in their solution.
Quickly wrote this up, commented it (This way you can easily learn what's going on, you see), and tested it for you.
<form method="GET">
<input type="text" name="table">
</form>
<?php
//can be done elsewhere, I used this for testing. vv
$config = array(
'SQL-Host' => '',
'SQL-User' => '',
'SQL-Pass' => '',
'SQL-Database' => ''
);
$con = mysqli_connect($config['SQL-Host'], $config['SQL-User'], $config['SQL-Pass'], $config['SQL-Database']) or die("Error " . mysqli_error($con));
//can be done elsewhere, I used this for testing. ^^
if(!isSet($_GET['table'])) { //check if table choser form was submitted.
//In my case, do nothing, but you could display a message saying something like no db chosen etc.
} else {
$table = mysqli_real_escape_string($con, $_GET['table']); //escape it because it's an input, helps prevent sqlinjection.
$sql = "SELECT * FROM " . $table; // SELECT * returns a list of ALL column data
$sql2 = "SHOW COLUMNS FROM " . $table; // SHOW COLUMNS FROM returns a list of columns
$result = mysqli_query($con, $sql);
$Headers = mysqli_query($con, $sql2);
//you could do more checks here to see if anything was returned, and display an error if not or whatever.
echo "<table border='1'>";
echo "<tr>"; //all in one row
$headersList = array(); //create an empty array
while($row = mysqli_fetch_array($Headers)) { //loop through table columns
echo "<td>" . $row['Field'] . "</td>"; // list columns in TD's or TH's.
array_push($headersList, $row['Field']); //Fill array with fields
} //$row = mysqli_fetch_array($Headers)
echo "</tr>";
$amt = count($headersList); // How many headers are there?
while($row = mysqli_fetch_array($result)) {
echo "<tr>"; //each row gets its own tr
for($x = 1; $x <= $amt; $x++) { //nested for loop, based on the $amt variable above, so you don't leave any columns out - should have been <= and not <, my bad
echo "<td>" . $row[$headersList[$x]] . "</td>"; //Fill td's or th's with column data
} //$x = 1; $x < $amt; $x++
echo "</tr>";
} //$row = mysqli_fetch_array($result)
echo "</table>";
}
?>
$tablename = $_POST['table'];
$result = mysqli_query($con,"SELECT * FROM $tablename");
$first = true;
while($row = mysqli_fetch_assoc($result))
{
if ($first)
{
$columns = array_keys($row);
echo "<table border='1'>
<tr>";
foreach ($columns as $c)
{
echo "<th>$c</th>";
}
echo "</tr>";
$first = false;
}
echo "<tr>";
foreach ($row as $v)
{
echo "<td>$v</td>";
}
echo "</tr>";
}
echo "</table>";
<?php
$table_name = do_not_inject($_REQUEST['table_name']);
$result = mysqli_query($con,'SELECT COLUMN_NAME FROM information_schema.COLUMNS WHERE TABLE_NAME='. $table_name);
?>
<table>
<?php
$columns = array();
while ($row = mysql_fetch_assoc($result)){
$columns[]=$row['COLUMN_NAME'];
?>
<tr><th><?php echo $row['COLUMN_NAME']; ?></th></tr>
<?php
}
$result = mysqli_query($con,'SELECT * FROM course'. $table_name);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>';
foreach ($columns as $column){
?>
<td><?php echo $row[$column]; ?></td>
<?php
}
echo '</tr>';
}
?>
</table>

how to view database data in vertical way

Here is my code to view data from db. some of the column must be get from other table so it will have different query. the problem is, why the second and third 'while loop' show the result in horizontal way and not vertical.
//FIRST WHILE
$result = $waran->getall();
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo " <td style='text-align:center'>".$bil."</td>";
if($_SESSION['mPosition'] == "FULL ACCESS"){
echo " <td><a href='javascript:showDialog(\"view_Waran\");showWaran(\"".$row['id']."\")' class='no_decoration'>".$row["name_position"]."</a></td>";
}else{
echo " <td>".$row['name_position']."</td>";
}
echo " <td style='text-align:center'>".$row['grade_position']."</td>";
echo " <td style='text-align:center'>".$row['code_skim']."</td>";
//SECOND WHILE
$resultWaranFix = $waran->getListWaranFix();
while ($rowWaranFix = mysql_fetch_array($resultWaranFix )) {
echo "<td>".$rowWaranFix ['total_waran_fix']."</td>";
}
//THIRD WHILE
$resultFullfilmentFix = $waran->countFullfilmentFix ();
while ($rowFullfilmentFix = mysql_fetch_array($resultFullfilmentFix )) {
echo "<td>".$rowFullfilmentFix ['fullfilment_fix']."</td>";
}
echo "</tr>";
$bil=$bil+1;
}
You could try something like this:
$result = $waran->getall();
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo " <td style='text-align:center'>".$bil."</td>";
if($_SESSION['mPosition'] == "FULL ACCESS"){
echo " <td><a href='javascript:showDialog(\"view_Waran\");showWaran(\"".$row['id']."\")' class='no_decoration'>".$row["name_position"]."</a></td>";
}else{
echo " <td>".$row['name_position']."</td>";
}
echo " <td style='text-align:center'>".$row['grade_position']."</td>";
echo " <td style='text-align:center'>".$row['code_skim']."</td>";
// You could end the row here for example.
echo "</tr><tr>";
// Instead of just adding cells you can put a table inside the cell and display all those items as rows in the sub table.
echo "<td><table>";
$resultWaranFix = $waran->getListWaranFix();
while ($rowWaranFix = mysql_fetch_array($resultWaranFix )) {
echo "<tr><td>".$rowWaranFix ['total_waran_fix']."</td></tr>";
}
echo "</table></td>";
echo "</tr><tr>";
// Same for this loop.
echo "<td><table>";
$resultFullfilmentFix = $waran->countFullfilmentFix ();
while ($rowFullfilmentFix = mysql_fetch_array($resultFullfilmentFix )) {
echo "<tr><td>".$rowFullfilmentFix ['fullfilment_fix']."</td></tr>";
}
echo "</table></td>";
echo "</tr>";
$bil=$bil+1;
}
I have changed it so the loops inside are displayed inside sub tables.

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'.'').'/>';

Categories