I've checked around google and in here and I am unable to find an answer specific to what I'm wanting to do.
Basically, I am trying to make a table with the database like this:
[0001][0002]
[0003][0004]
However, for some reason I am unable to do that.
This is what I've got down, and it's not even functioning. I would like to note that I am pretty new to php, although that may be obvious.
<table>
<?php
...
$x = 0;
while($info = mysql_fetch_array( $data ))
{
while($info['id'] <= 4)
{
if($x ==0){ // [I feel like the error is in here.]
Print "<tr>";
$x++;
}elseif($x == 2){
Print "</tr>";
}else(){
$x++;
}
Print '<td><img src="' .$info['img'] . '" width="210" height="157">';
Print "".$info['name'] . "</td>";
}
}
?>
</table>
Without the counter, the table is more of a single-column table going down.
You've got a few issues:
Syntax errors in your print lines, your concatenation (.) areas have inconsistencies with the type of quotes you're using to get back into the string e.g. ' or "
Identifying which column and where the break point is isn't really there
Try something like this (assume your database results are fine):
<table>
<?php
// ...
$i = 1;
$columns = 2;
while($info = mysql_fetch_array( $data )) {
if($i == 1) {
echo '<tr>';
}
echo '<td><img src="'.$info['img']. '" width="210" height="157">' . $info['name'] . '</td>';
if($i == $columns) {
echo '</tr>';
$i = 1;
} else {
$i++;
}
}
?>
</table>
Related
Wanted to get 2 values id and name but im confuse how get it, i wanted to show the id in the link. heres the sample code.
echo "<table width=\"100%\" border=\"1\" cellpadding=\"5\" cellspacing=\"2\" bordercolor=\"#FFFFFF\">";
$count = 1;
$id=$_GET['id'];
$col1 = $col2 = array();
$rowcount = round(mysqli_num_rows($nquery) / 2);
while($crow = mysqli_fetch_assoc($nquery)) {
if($count > $rowcount) $col2[] = $crow['title'];
else $col1[] = $crow['title'];
$count++;
}
$counter = 0; // Arrays start with 0
foreach($col1 as $crow) { // $col1 will always be >= $col2
$row2 = (isset($col2[$counter])) ? $col2[$counter] : "";
echo "<tr><td><a href='index.php?page=".$id."'>" . $crow . "</td><td>" . $row2 . "</td></tr>";
$counter++;
}
echo "</table>";
?>`
id wont show up on the link. Hope someone can help. Thanks
You're trying to get $id values from the query string (that's what the $_GET superglobal is) and not from the database.
If both elements (ID and name) are coming from the same database query, you may try something like this:
$crow = mysqli_fetch_assoc($nquery);
foreach ($crow as $row)
{
echo $row['id'].' is the ID and '.$row['title'].' is the title';
}
if you remain within the foreach loop, you can use $row['id'] and $row['title'] to build the table element and link you're trying to obtain.
I have been trying to return a list of results from MySQL using PHP.
The basic query is simple and the output is multiple columns. I want to add a number so the array looks like this:
Club 1
Club 2
I have tried the below but it keeps breaking the script:
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
for($i=1; $i++){
$club = $row['club_name'];
echo '<p>' . $i . $club . '</p>';
}
}
}
I have then tried placing the for statement outside the while and inside it, changed it to foreach and used the format ($i=1; $i<100; $i++){} and it still doesn't work.
Sorry if this is an obvious one I've tried numerous different ways and it just isn't working for me.
Try creating a counter variable ($i) and incrementing it on every iteration of the while loop ($i++), like this:
if (mysqli_num_rows($result) > 0) {
$i = 1;
while($row = mysqli_fetch_assoc($result)) {
$club = $row['club_name'];
echo '<p>' . $i . $club . '</p>';
$i++;
}
}
Then, to change the format to match 1. Club Name, change
echo '<p>' . $i . $club . '</p>';
to
echo "<p>$i. $club</p>";
But, I'd personally recommend to use an <ol> instead and skip setting the counter altogether like this:
if (mysqli_num_rows($result) > 0) {
echo "<ol>";
while($row = mysqli_fetch_assoc($result)) {
$club = $row['club_name'];
echo "<li>$club</li>";
}
echo "</ol>";
}
I am working on a project to pull data from a sql database via PHP and create an HTML table from it. It is part of a form I am creating and the table will be a listing of what I am selling, costs, weights, etc. Anyway, I need to do this with PHP. So far I have the following in this section of my code to make this table:
<?php
$db=mysqli_connect(null,null,null,'weblab')
or die("Can't connect to DB: " .
mysqli_connect_error());
$query="SELECT fruit_item_no, fruit_name, fruit_price, fruit_weight FROM fruit_$
$result=mysqli_query($db, $query);
if (!$result) {
print "Error - The query could not be executed!" .
mysqli_error();
}
print "<table class = 'main'><caption> <h2> Fruit Purchasing Form </h2> </c$
print "<tr align = 'center'>";
$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);
$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
}
else {
print "There were no such rows in the table <br />";
}
print "</table>";
?>
The problem I am running into is when I attempt the view the entire page in Chrome, all I see is:
I think the error is somewhere around this section of code:
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
If anyone can give me a little direction on what I might be missing, I would greatly appreciate it. I have been researching a while now and no clear fix has come up that i can see.
UPDATE:
Thought it would be best to just update my post instead of new question or comment somewhere. Thanks to all your suggestions I was able to correct my code to properly display my table and worked out all validation errors. I apologize for the code reading nightmare... I am still fairly new at this and I need to work more at it.
I did run into one issue I still cannot resolve though. I am trying to add an input box on the end of each row in the table I created. Problem is no matter what I try the boxes stay in a line above the table (pretty much at the top of the browser screen.
I placed this line in the sql query block to try to get the input box:
echo ("<input name='item[]' type='text' .=''/>");
and I also tried:
echo ("<input type='text' name ='item'/>");
Both did the same thing in giving me the line of boxes along the top. Any direction you could provide in getting these to be at the end of each row? I do not need it to put data back in the database or add to a table there. I just am trying to get input fields that will allow input that will submit with my form.
You can simplify the code by running and while loop on the result and iterating through the rows. And then using foreach loops since each row is an array of key value pairs. On the first iteration you could print the header.
$num_rows=mysqli_num_rows($result);
if ($num_rows > 0) {
$i = 0;
// loop through each row in the result
while ($row=mysqli_fetch_assoc($result)) {
// if first then print the header
if ($i == 0) {
print "<tr>";
foreach ($row as $field => $value) {
print "<th class='a'>".$field."</th>";
}
print "</tr>";
}
// print the row
print "<tr>";
foreach ($row as $value) {
print "<td class='b'>".$value."</td>";
}
print "</tr>";
$i++;
}
}
else {
print "<tr></td>There were no such rows in the table</td></tr>";
}
As suggested in the comments it would be a good idea to separate your view from your code.
In your second for loop, you have this:
for($index=0; $index<$num_fields; $row_num++)
Well, the value of $index will remain 0 throughput your execution. Try changing it to
for($index=0; $index<$num_fields; $index++)
{
$row_num++;
//rest of code
}
Hope it helps.
This is unnecessarily complicated:
$row=mysqli_fetch_assoc($result);
$num_fields=mysqli_num_fields($result);
$keys=array_keys($row);
for ($index = 0; $index < $num_fields; $index++)
print "<th class='a'>" . $keys[$index] . "</th>";
print "</tr>";
for ($row_num = 0; $row_num < $num_rows; $row_num++) {
print "<tr>";
$values = array_values($row);
for ($index = 0; $index < $num_fields; $row_num++) {
$value=htmlspecialchars($values[$index]);
print "<td class = 'b'>" . $value . "</td>";
}
print "</tr>";
$row=mysqli_fetch_assoc($result);
}
Something like this would be easier to read and should solve your problem, which was caused by incrementing the wrong index on one of the for loops:
$headers = false;
while($row=mysqli_fetch_assoc($result)) {
if (!$headers) {
echo "<thead><tr>";
foreach($row as $k=>$v) {
echo "<th>$k</th>";
}
echo "</tr></thead>";
$headers = true;
}
echo "<tr>";
foreach ($row as $k=>$v) {
$v=htmlspecialchars($v);
print "<td class='b'>$v</td>";
}
echo "</tr>";
}
But I would strongly recommend a) using a database abstraction layer like PDO, and b) separating your logic from your presentation. Debugging problems with HTML is made 100 times harder when it's jumbled all together with your PHP like this.
Hey guys I'm back and I feel like I'm making a really stupid error in my code but I can't seem to find it. What I am trying to do is split data retrieved from a mysql table into two columns inside an html table. So far I got it working...sort of. The problem I am having is the data keeps replicating to both rows in the table versus being an individual entry in each cell. I have used googled and searched these forms and can't seem to see where I am making the error. Below is the code
// Build the table
echo '
<table>
<tr>
';
// Build the headers
for ($x = '1'; $x <= '2'; $x++)
echo '
<td>Truck</td>
<td>Home Base</td>
<td>Client</td>
<td>Job Details</td>
<td>Crew</td>
';
// Close off headers
echo '</tr>';
// Fetch the table contents if the rigs are active
while($row = mysqli_fetch_array($truck_full_query)) {
for ($y = '1'; $y <= '1'; $y++):
echo '<tr>';
for ($z = '1'; $z <= '2'; $z++):
echo '<td>' . $row['model'] . ' #' . $row['position'] . '<br>' . $row['unit_number'] . '</td>';
echo '<td>' . $row['dispatch_location'] . '</td>';
// Get client information
echo '<td> </td>';
// Get Job Details
echo '<td> </td>';
// Get Crew
echo '<td> </td>';
endfor;
echo '</tr>';
endfor;
}
// Close table
echo '</table>';
// Build the table
echo '<table><tr>';
// Build the headers
echo '<td>Truck</td><td>Home Base</td><td>Client</td><td>Job Details</td><td>Crew</td>';
echo '<td>Truck</td><td>Home Base</td><td>Client</td><td>Job Details</td><td>Crew</td>';
echo '</tr>';
$data = mysqli_fetch_all($truck_full_query);
$i = 0;
$t = sizeof($data);
for (; $i < $t; $i += 2) {
echo '<tr>';
$left_row = $data[$i];
echo '<td>' . $left_row['model'] .'</td><td>...</td><td>...</td><td>...</td><td>...</td>';
$right_row = $data[$i + 1];
echo '<td>' . $right_row['model'] .'</td><td>...</td><td>...</td><td>...</td><td>...</td>';
echo '</tr>';
}
echo '</table>
And don't forget to check if the last $right_row exists.
I'm trying to display all the information in a msSQL table in an HTML table and have up with something that is not so great.
<table border="1">
<?
echo "<tr>";
for ($i = 0; $i < mssql_num_fields($result); ++$i){
echo "<th>" .$column_names[$i] . "</th>";
}
echo "</tr>";
$num_rows = mssql_num_rows($result);
for ($i = 0; $i < $num_rows; ++$i){
echo "<tr>";
foreach ($column_names as $key => $val){
$result_row = mssql_query("SELECT * FROM username WHERE id = '$i'");
$row = mssql_fetch_assoc($result_row);
echo "<td>";
echo $row[$val];
echo "</td>";
}
echo "</td>";
}
?>
</table>
This works. The first part prints out the column names successfully, but as for the rest:
1) I think it is sort of cumbersome to make a query for every time through the loop
2) it doesn't really work because the ids of the rows go much higher than the number of rows in the table, as some ids aren't used.
It seems like I should be able just make one query and pull everything from the database at one go, then build my HTML table from that, but I can't figure out how to access it row by row where I could go $row[next row][shifted value from $column_names. How can improve this query?
function table_cell($item, $header=false) {
if (!$item) return '';
$elemname = ($header) ? 'th' : 'td';
$escitem = htmlspecialchars($item, ENT_NOQUOTES, 'UTF-8');
return "<{$elemname}>{$escitem}</{$elemname}>";
}
function table_header_cell($item) {
return table_cell($item, true);
}
function table_row($items, $header=false) {
$func = ($header) ? 'table_header_cell' : 'table_cell';
return "<tr>\n\t".implode("\n\t", array_map($func, $items))."\n</tr>\n";
}
function echo_result_as_table($result) {
if ($result && $row = mssql_fetch_assoc($result)) {
$columnnames = array_keys($row);
echo "<table>\n", table_row($columnnames, true), "\n";
do {
echo table_row($row), "\n";
} while ($row = mssql_fetch_assoc($result));
echo "</table>\n";
}
}
$result = mssql_query("SELECT * FROM username");
echo_result_as_table($result);
if ($result) mssql_free_result($result);
If you have an array of associative arrays instead of a raw mssql result handle, you can use a function like this to produce a table string:
function array_to_table($arrayofassoc) {
if (!$arrayofassoc) return '';
$tablestr = '<table>';
$tablestr .= table_row(array_keys($arrayofassoc[0]), true);
$tablestr .= implode('', array_map('table_row', $arrayofassoc));
$tablestr .= '</table>';
return $tablestr;
}
try this:
while($row = mysql_fetch_results($result)){
echo '<td>'.$row['column_name'].'</td>';
}
with 'column_name' being the name of the column in mysql.
but some will say..."wait, but PDO"