I have a database table called 'Modules' and I am trying to select all of the rows from that table and display them in a table. Each row has a column called MOrder which ranges from 1 - how ever many modules are available.
Here is my code:
$sql_query = "SELECT * FROM Modules WHERE CourseID = ". $CourseID ." ORDER BY MOrder ASC";
$result = mysqli_query($dbconfig, $sql_query);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
echo '<div class="row">';
echo '<div class="col-md-12">';
echo '<table class="table">';
if($count > 0) {
$_SESSION['countMOrder'] = $count;
echo '<tr>';
echo '<th>Module Title</th> ';
echo '<th></th>';
echo '</tr>';
while ($row = mysqli_fetch_array($result)) {
echo '<tr>';
echo '<td>'. $row['Title'] .'</td> ';
echo '<td>Take Module</td>';
echo '</tr>';
}
}
echo '</table>';
echo '</div>';
echo '</div>';
?>
However, for whatever reason the statement is missing out the module with MOrder 1 and always starting with 2?
Why is this?
You are calling $row = mysqli_fetch_array($result, MYSQLI_ASSOC); in the third line of your pasted code, which is pulling the first array from the results.
This is then being overwritten in your while loop:
while ($row = mysqli_fetch_array($result)) { // <-- overwritten here with item 2
//...
}
Because in the 3rd line of your code you call
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
once, and then in the loop you start calling the
$row = mysqli_fetch_array($result)
again, thus overwriting the $row variable with the 2nd row. Get rid of the 1st $row = mysqli_fetch_array($result) line.
Try this code.
$sql_query = "SELECT * FROM Modules WHERE CourseID = ". $CourseID ." ORDER BY MOrder ASC";
$result = mysqli_query($dbconfig, $sql_query);
$count = mysqli_num_rows($result);
echo '<div class="row">';
echo '<div class="col-md-12">';
echo '<table class="table">';
if($count > 0) {
$_SESSION['countMOrder'] = $count;
echo '<tr>';
echo '<th>Module Title</th> ';
echo '<th></th>';
echo '</tr>';
while ($row = mysqli_fetch_array($result)) { //for every fetch we'll get one row.
echo '<tr>';
echo '<td>'. $row['Title'] .'</td> ';
echo '<td>Take Module</td>';
echo '</tr>';
}
}
echo '</table>';
echo '</div>';
echo '</div>';
At the beginning, you fetch the first row.
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
In while loop, fetch function returns second row.
Related
I would to like to create a dynamic table that the rows and columns of the table depends on the data in mysql data. Please see below my codes.
<?php
require "connect/db.php";
$query = mysqli_query($mysqli, "SELECT COUNT(level) level, shelf_no, bin_id FROM location_bin WHERE rack_id =1 GROUP BY shelf_no");
while($res=mysqli_fetch_array($query)){
$col = $res['level']; //col
$row = $res['shelf_no']; //rows
echo "<table border='1'>";
$i = 0;
while ($i < $col){
if ($i==$col){
echo "<tr>";
}
echo "<td>".$res['bin_id']."</td>";
$i++;
}
echo "</tr>";
echo "</table>";
}
?>
What I want is to display A-1-01 up to A-1-06 in the first row then A-2-01 to A-2-03 on the second row. Note that the data is dynamic.
Can you try this code . It works. change db.php path as your system path.
require "db.php";
$query = mysqli_query($conn, 'SELECT level, shelf_no, bin_id FROM location_bin ORDER BY shelf_no asc, level asc ');
echo "<table border='1'>";
echo "<tr>";
$i=0;
while($res = mysqli_fetch_assoc($query)) {
$row=$res['shelf_no'];
if ($i < $row){
$i=$row;
echo "</tr><tr>";
}
echo "<td>".$res['bin_id']."</td>";
}
echo "</table>";
?>
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>
Here's the code:
<?php
if(isset($_POST['results']) && $_POST['results'] != -1) {
$db = new PDO('mysql:host=localhost;dbname=;charset=utf8', '', '');
echo "<table border='1'>
<tr>
<th>Courses</th>
</tr>";
$stmt = $db->prepare("SELECT title FROM course WHERE `subject_id`=?");
$stmt->execute(array($_POST['results']));
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr>";
echo "<td>", $row['title'], "</td>";
echo "</tr>";
}
} else {
echo "No results found";
} echo "</table>";
}
?>
This is just returning one result into the table, when there are more results to show.
Where am I going wrong?
remove the if, because it's change the pointer of array(fetch)
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { // get the first record, remove this if
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {// get the second record and reset $row
you can change to:
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
$total_rows = $stmt->rowCount();
if($total_rows > 0){
foreach($row as $item){
echo '<td>'. $item['title'] .'</td>';
}
}else{
echo 'no results';
}
Hi I'm attempting to display data retrieved from a mysql table horizontally in an html table using php. The code below works well except for the fact that it leaves out the first record (starts at the second record) in my database. I'm sure it has something to do with the counter but I can't seem to figure out how to get it to stop doing this. If anyone can point out my error I'd really appreciate it!
$items = 5;
$query = "SELECT * FROM members ";
$result = mysql_query($query)
or die(mysql_error());
$row = mysql_fetch_array($result);
if (mysql_num_rows($result) > 0) {
echo '<table border="1">';
$i = 0;
while($row = mysql_fetch_array($result)){
$first_name = $row['first_name'];
if ($i==0) {
echo "<tr>\n";
}
echo "\t<td align=\center\">$first_name</td>\n";
$i++;
if ($i == $items) {
echo "</tr>\n";
$i = 0;
}
}//end while loop
if ($i > 0) {
for (;$i < $items; $i++) {
echo "<td> </td>\n";
}
echo '</tr>';
}//end ($i>0) if
echo '</table>';
}else {
echo 'no records found';
}
try and remove the 1st
$row = mysql_fetch_array($result);
you are calling it twice, that's why it skips 1 row in your while loop
try this simpler.
$items = 5;
$query = "SELECT * FROM members ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
echo '<table border="1">';
while($row = mysql_fetch_array($result)){
$first_name = $row['first_name'];
echo "<tr>";
for ($i=0 ; $i <= $items ;$i++) {
echo "<td align='center'>".$first_name."</td>";
}
}//end while loop
echo "</tr>";
echo '</table>';
}else{ echo 'no records found'; }
I have run into this issue before. Try the do while loop instead. Example
do {
// code
} while($row = mysql_fetch_array($result)); //end while loop
$row = mysql_fetch_array($result);
1) remove this line of code from ur scripts
2) only use while loop code instead.
My code below displays 10 entries, but it displays it in 10 rows and 1 column. I would like for it to display 10 entries, but in 2 columns and 5 rows. Can anyone help? Thanks in advance.
< ?php
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error());
mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10")
or die(mysql_error());
echo '<table>';
echo '<tr>';
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No')
{
continue;
}
else{
echo '<td>';
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
echo '<tr>';
}
}
echo '</table>'
?>
<?php
mysql_connect($dbhost, $dbuser, $dbpass) or die(mysql_error()); mysql_select_db($dbname) or die(mysql_error());
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10") or die(mysql_error());
$i = 1; //The following logic only works if $i starts at '1'.
$numofcols = 2; //Represents the number of columns you want in the table.
echo '<table>'; //Open table.
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No'){
continue;
}
else{
//If it's the beginning of a row...
if( $i % $numofcols == 1 ){
echo '<tr>'; //Open row
}
//Table Cell.
echo '<td>'; //Open Cell
echo 'ID Number: '.$row['id'];
echo '<br/> <img src="'.$row['Pic'].'"> <br/>';
echo '</td>'; //Close Cell
//If we have already placed enough cells, close this row.
if( $i % $numofcols == 0) {
echo '</tr>'; //Close Row.
}
//Now that we've made a table-cell, lets increment our counter.
$i = $i + 1;
}
}
//So we make sure to close our rows if there are any orphaned cells
if( ($i % $numofcols) > 0){
echo '</tr>';
}
echo '</table>' //Close Table
?>
Please note that the mod logic will only work if the starting value of $i is '1'.
This code will create a table with 2 columns.
Not tested, but basically you can call $row = mysql_fetch_array() in the loop as well to grab another row.
while($row = mysql_fetch_array( $result ))
{
echo "<tr>";
echo "<td>";
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
echo "</td>";
$row = mysql_fetch_array( $result );
if($row)
{
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
}
else
{
// Empty cell
echo "<td> </td>";
}
echo "</tr>";
}
Use modulo for echo "< tr>"
$result = mysql_query("SELECT * FROM Members LIMIT 0, 10")
or die(mysql_error());
$i = 0;
echo '<table>';
echo '<tr>';
while($row = mysql_fetch_array( $result )) {
if ($row['Approved']=='No')
{
continue;
}
else{
echo '<td>';
echo "ID Number: ".$row['id'];
echo "<br/>";
echo '<img src="'.$row['Pic'].'">';
echo "<br/>";
echo '<hr>';
if ($i % 5)
echo '</tr>';
$i++;
}
echo '</table>'