Mysql to array not working - php

Hey Everyone i got a little problem! I know its something simple but for some reason i can not figure it out (arrays are kicking my butt!)
I want the results to display like the following...
title 1 | title 2 | title 3 | title 4 |
Title 5 | title 6 | title 7 | title 8 |
But for some reason when the code runs it shows as the following...
t | i |
It spells out the title 1 and not the whole word for each cell of the table.
What am i doing wrong?
$result = mysqli_query($con,"SELECT title FROM donuts");
$rows = 2;
$cols = ceil(count($result)/$rows);
$row = mysqli_fetch_array($result);
echo $result=$row['title'];
echo "<table border='1'>";
$i=0;
for($tr=1;$tr<=$rows;$tr++) {
echo "<tr>";
for($td=1;$td<=$cols;$td++) {
if (isset($result[$i])) {
echo "<td>".$result[$i]."</td>"; $i++;
}
}
echo "</tr>";
}
echo "</table>";
Note the table has no limit on how many columns there are just rows.
Link to working example http://lakeside.donavonscreativeinnovations.com/

You have to loop through the results. Something like this:
// $numrows = mysqli_num_rows($result); // Count rows if you want to know
while( $row = mysqli_fetch_array($result, MYSQLI_ASSOC) ) { // Loop through rows
echo "<tr>";
foreach($row as $key => $value) { // Loop through columns
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
At the moment you loop through each character of a column.

You might want to try it like this:
$result = mysqli_query($con, "SELECT title FROM donuts");
echo '<table>';
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
echo '<tr>';
foreach ($row as $cell)
{
echo '<td>' . $cell . '</td>';
}
echo '</tr>';
}
echo '</table>';

Here is your problem:
echo $result=$row['title'];
and then you loop through this with the code:
$i=0; for($tr=1;$tr<=$rows;$tr++)
{ echo "<tr>";
for($td=1;$td<=$cols;$td++)
{
if (isset($result[$i])) {
**echo "<td>".$result[$i]."</td>"; $i++;**
Thus you loop through a string outputting each character in that string.

Related

How to get the first column/td value of a foreach loop

I want to get the ID of a row which I want to use to generate the url.
I am generating the table rows using following code.
<?
$sql="SELECT pID,pName,pBudget,pRate FROM projects ORDER BY id";
$result=mysqli_query($con,$sql);
$projects = array();
while($row = mysqli_fetch_assoc($result))
{
$projects[] = $row;
}
foreach ($projects as $row)
{
echo "<tr>";
foreach ($row as $element)
{
echo "<td>".$element."</td>";
}
echo "<td class=\"actions\">
<a href=\"project.php?pID=$element[0]\">
Go to Project
</a>
</td>";
echo "</tr>";
}
?>
All work fine except the last <td> of the row. (not sure I am using the correct wording.)
Let's say my database table row is
pID | pName | pBudget | pRate
-----------------------------------------
12345 | Create Website | 250 | hourly
then I am getting the table rows like this in my page
<tr>
<td>12345</td>
<td>Create Website</td>
<td>250</td>
<td>hourly</td>
<td>Got to project</td>
</tr>
Why the last <td> does not have the pID value '12345' and why there is 'h' ?
I want the last <td> to be:
<td>Got to project</td>
Why the last does not have the pID value '12345' and why there is 'h'?
Because value of $element after foreach loop is over is hourly. First symbol of this string is h.
Correct version is:
echo ".....<a href=\"project.php?pID={$row['pID']}\">
as you use fetch_assoc function.
<?php
$sql="SELECT pID,pName,pBudget,pRate FROM projects ORDER BY id";
$result=mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['pName']."</td>";
echo "<td>".$row['pBudget']."</td>";
echo "<td>".$row['pRate']."</td>";
echo "<td class='actions'>
<a href='project.php?pID=$row['pID']'>
Go to Project
</a>
</td>";
echo "</tr>";
}
?>

Mysql rows to html table using for loop

I tried to print the Mysql fetched rows into html table using php. However, when using the following code, the first fetched row is repeatedly printing. It looks like the $row hold the first fetched value. I found a similar problem here. But I would like to know about working with the for loop. Thanks
for ($j=0;$j<=$len2;$j++)
{
$sql = "SELECT * FROM database_search WHERE gene_id LIKE'%$key%'";
$qry = $dbo->prepare($sql);
$qry->execute();
$row = $qry->fetch(PDO::FETCH_ASSOC);
$val = array_values($row);
echo "<tr>";
for ($k=0;$k<=4;$k++)
{
$x=$val[$k];
echo "<td style=font-size:7.9px>$x</td>";
}
echo "</tr>";
}
<table>
<?php
while($row = $qry->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
foreach($row as $cell){ echo '<td>'.$cell.'</td>'; }
echo '</tr>';
}
?>
</table>
After fetching the query as $row variable, you need to use the following code instead
foreach($row as $tr) {
echo "<tr>";
echo "<td style=font-size:7.9px>".$tr['col1']."</td>";
echo "<td style=font-size:7.9px>".$tr['col2']."</td>";
echo "</tr>";
}
This is possible that $row only have one record fetching from database and than your for ($k=0;$k<=4;$k++) loop print that only one record 5 time
because you are using print under this loop, this loop will run 5 time.
Try the following code.
foreach($row as $val) {
echo "<tr>";
echo "<td style=font-size:7.9px>".$val['column Name']."</td>";
echo "</tr>";
}

PHP Delete Button

I recently started learning PHP on my own and started to use MySQL and Apache as well. I made a basic table in MySQL, and using some PHP code, I displayed the table in a HTML table in a browser. Now I'd like to add a delete button beside each row, and when clicked, it would delete that row. I am very new to this, and I'm just practicing. Could anyone please help me? This is the code I have so far:
From: phpcode on Pastebin
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysql_connect('localhost', 'root', '');
mysql_select_db('testdb');
$result = mysql_query('select * from products');
$numrows = mysql_numrows($result);
//****************************************************************
print "<table border = 3 style = width:400px>";
for($i = 0; $i < $numrows; $i++)
{
$row = mysql_fetch_row($result);
print "<tr>";
foreach($row as $cell)
{
print "<td>";
print $cell;
print "</td>";
}
print "</tr>";
}
print "</table>";
mysql_close();
?>
I also have a delete.php page, but I really don't know where to start. I've looked for online tutorials, and many say different ways.
Just add another "" inside the loop with delete text and pass the id for that
for($i = 0; $i < $numrows; $i++)
{
$row = mysql_fetch_row($result);
print "<tr>";
foreach($row as $cell)
{
print "<td>";
print $cell;
print "</td>";
print "<td>";
print "DELETE";
print "</td>";
}
print "</tr>";
}
Let say your table like below;
$result = mysql_query('select * from products');
print "<table>";
while ($row = mysql_fetch_assoc($result)) {
print "<tr><td>" . $row["name"] . "</td><td>" . $row["surname"] . "</td><td>Delete</td></tr>";
}
print "</table>";
Here, while iterating your row, you need to put $row["id"] in delete link id.
And in your delete.php
$id = $_GET["id"];
// Delete sql here. Do not forget to validate id here.
header("Location: index.php"); // I assume, table page is this
In your table products you need a field with different value for each register, name it id or whatever you want.
If you have table but doesn't have that field, good option would be and auto_increment field.
Code for add an auto_increment field:
ALTER TABLE `products` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST;
Then id would be unique for each register and you don't need to worried about it because you don't need to insert it, it is generated automatically.
print "<table border = 3 style = width:400px>";
for($i = 0; $i < $numrows; $i++)
{
$row = mysql_fetch_row($result);
print "<tr>";
foreach($row as $cell)
{
print "<td>";
print $cell;
print "</td>";
}
print "<td><a href='delete.php?id=".$row["id"] ."' > delete </a> " ;
print "</tr>";
}
$row["id"] is the id of register you want to delete.
in delete.php
$id = $_GET["id"];
$delete = " DELETE from yourTable where id = ". $id ;
mysq_query ( $delete ) ;
PD: Use mysqli_

PHP: Creating big HTML-table efficiently

I'm making a HTML table based on certain information in my MySQL database. The tables I need from the database hold the data for rows (rowid, rowname), columns (columnid, columnname) and cell data. A table, that links IDs from rows and columns together (cellid, rowid, columnid, somedata).
The table looks something like this:
__________| column1 | column2 | column3 | ...
row1 | somedata | somedata | |
----------|----------|----------|----------|-----
row2 | somedata | | somedata |
----------|----------|----------|----------|-----
... | | | |
My approach was to use several nested foreach loops, something like this:
$rows = new Rows(); //These objects are containers for objects
$columns = new Columns(); //that hold some of the database data.
$alldata = new Alldata(); //MySQL queries within these objects are irrelevant, I think. They already get the relevant data
$count = count($alldata);
echo "<table>";
echo "<tr>";
echo "<td> </td>";
foreach ($columns->getColumns() as $column) {
echo "<td>".$column->getColumnname()."</td>";
}
echo "</tr>";
foreach ($rows->getRows() as $row) {
echo "<tr>";
echo "<td>".$row->getRowname()."</td>";
foreach ($columns->getColumns() as $column) {
$last = 1;
foreach ($alldata->getAlldata() as $data) {
if ($data->getCID() == $column->getID() & $data->getRID() == $row->getID()) { //If the column has data the related to the row
echo "<td>".$data->getSomedata()."</td>";
break;
}
if ($last == $count) { //if loop couldn't find any entries, it prints an empty cell
echo "<td> <td>";
}
$last++
}
}
echo "</tr>";
}
echo "</table>";
Bruteforcing, obviously this is not very efficient method when there are several hundred rows of data on any table in the database and I don't like this. Any ideas how to make this more efficient? Is there better way of creating a table like I need?
EDIT:
Pondering about this problem for a week has finally given me some answers. It was so simple!
I did a slight modification to my Column object class. Previously, my code went through all possible entries on celldata table in the database. Now Column object gets an array of celldata where columnid's match and I can do the comparison using only that data.
$rows = new Rows();
$columns = new Columns();
echo "<table>";
echo "<tr>";
echo "<td> </td>";
foreach ($columns->getColumns() as $column) {
echo "<td>".$column->getColumnname()."</td>";
}
echo "</tr>";
foreach ($rows->getRows() as $row) {
echo "<tr>";
echo "<td>".$row->getRowname()."</td>";
foreach ($columns->getColumns() as $column) {
$last = 1;
$count = count($column->getAlldata());
foreach ($column->getAlldata() as $data) {
if ($data->getCID() == $column->getID() & $data->getRID() == $row->getID()) {
echo "<td>".$data->getSomedata()."</td>";
break;
}
if ($last == $count) {
echo "<td> <td>";
}
$last++
}
}
echo "</tr>";
}
echo "</table>";
Much faster, although still bruteforcing but there's less amount of data to go through. Of course, now the problem is that Column objects may do quite a lot of MySQL queries, depending on how many Columns there are.
If you ensure that the data fetched from MySQL is correctly ordered in $alldata by joining the tables and specifying an ORDER BY clause in your query:
SELECT data.*
FROM data RIGHT JOIN rows USING (rowid) RIGHT JOIN columns USING (columnid)
ORDER BY rowname, columnname;
Then you only need to output each cell in order:
echo '<table>';
echo '<thead>'
echo '<tr>';
echo '<th> </th>';
foreach ($columns->getColumns() as $column) {
echo '<th scope="col">', htmlentities($column->getColumnname()), '</th>';
}
echo '</tr>';
echo '</thead>';
echo '<tbody>';
$data = $alldata->getAlldata();
foreach ($rows->getRows() as $row) {
echo '<tr>';
echo '<th scope="row">', htmlentities($row->getRowname()), '</th>';
foreach ($columns->getColumns() as $column) {
$d = each($data);
echo '<td>', ($d ? htmlentities($d[1]->getSomedata()) : ' '), '</td>';
}
echo '</tr>';
}
echo '</tbody>';
echo '</table>';
The best way to solve this would be to rewrite the query for $alldata so that it is in the order you want like eggyal suggested. If you can't do that for some reason, you could iterate through $alldata in the beginning and create a properly indexed array from it. Something like this:
$ordereddata = array();
foreach($alldata as $d) {
$ordereddata[$d->getCID()][$d->getRID()] = $d->getSomedata();
}
Now you can replace your foreach($alldata) loop with this:
if(isset($ordereddata[$column->getID()][$row->getID()])) {
echo "<td>{$ordereddata[$column->getID()][$row->getID()]}</td>";
} else {
echo "<td> </td>";
}

SQL Image Database assembling rows into HTML cells and rows

I have a database of images which I want to output as a gallery ...
I want to display each image in its own cell <td>image1</td> and limit the number of cells to 7 per row.
<tr>
<td>image1</td><td>image2</td><td>image3</td><td>image4</td><td>image5</td><td>image6</td><td>image7</td>
</tr>
Then a new row would be created and continue to output all the images.
<tr>
<td>image8</td>
and so on ..
I know how to do a query, but I am lost as to how to assemble the rows into the format I am looking for.
Can anyone please help me it would be greatly appreciated. Thanks.
First run your query, then get the mysql_fetch_assoc in a variable. Then echo your beginning tags for the table and tr. Then create a foreach loop of the query assoc, as another variable such as row, and echo $row['image'] in a td. This will add a new td with the image for every entry in the database. Then echo your closing tags for the tr and table.
$query = mysql_query("SELECT image FROM table_name");
$query_a = mysql_fetch_assoc($query);
echo "<table><tr>"
foreach ($query_a as $row)) {
echo "
<td>" . $row['image'] . "</td>
";
}
echo "</tr></table>";
Not tested, but try something like this
<table>
<?php
// make sure there is at least 1 row first
$cnt = 0;
$while($row = mysql_fetch_assoc($query))
{
if(++$cnt == 1) {
echo '<tr>';
} elseif($cnt % 7 == 0) {
echo '</tr><tr>';
}
// show images in <td>'s
echo "<td>" . $row['image']. "</td>";
}
echo '</tr>';
?>
</table>
Keep it simple:
Query the database to get the desired information, loop through the results, construct a new row come each new loop.
$sql = "Select * from table";
mysql_query($sql) or die(mysql_error());
if(mysql_num_rows !=0)
{
// Found at least one record, create table
echo "<table>";
echo "<tr>";
while($row = mysql_fetch_assoc($sql)
{
$cell_count = 0;
// Create a new row for each record found
echo "<td>" . $row['image_column']. "</td>";
$cell_count++;
if($cell_count == 7)
{
echo "</tr>";
echo "<tr>";
$cell_count = 0;
}
}
// Close the table
echo "</tr>";
echo "</table>";
}

Categories