Greetings,
I have data stored on mysql with delimiter "," in 1 table.
I have rows and column stored on database too.
Now i have to output the data using rows and column number stored on database to draw the table.
Rows and column number are user input, so it may varies.
Let say, there is number 3 on column and 3 on rows.
I need to do it like display like,
|___d1__|___d2__|___d3__|
|___d4__|___d5__|___d6__|
|___d7__|___d8__|___d9__|
Where d1-d9 would be the data stored on mysql database with delimiter "," in one table.
Thanks for helping me.
You can turn the comma separated values from your data column into an array using the explode() function:
<?php
$result = mysql_query('SELECT rows, columns, data from table_name where id=1');
$record = mysql_fetch_assoc($result);
$rows = $record['rows'];
$columns = $record['columns'];
$data = explode(',' , $record['data']);
if (sizeof($data) != $rows * $columns) die('invalid data');
?>
To display the table, you need two nested for-loops:
<table>
<?php for ($row = 0; $row < $rows; $row++) : ?>
<tr>
<?php for ($column = 0; $column < $columns; $column++) : ?>
<td>
<?php echo $data[$row * $columns + $column]; ?>
</td>
<?php endfor ?>
</tr>
<?php endfor ?>
</table>
This won't help you solve this very problem, but a word of good advice: never EVER write comma seperated values into a database field. You can't sensibly query information stored like this, and your application code will be cluttered with ugly conversions. Instead, use a seperate table with a reference to the main table and one row per value.
assuming that user set table size for 2 rows and 3 columns and makes some input fot 6 cells, data which will go to database will be
2,3,d1,d2,d3,d4,d5,d6
when you will fetch data from cell and make explode on fetched string you will get 1 dimension array with 8 elements
$r = $e[0] rows
$c = $e[1] cols
$e[2-7] data
wrtite openning < table > tag
two loops, one in another,
first one will generate code for start of row
wrtite openning < tr > tag
inside one will genereate code for row.
write opening < td > tag
write data $e[1 + position calulated from inside and outside loops]
write closing < td > tag
end of inside loop
wrtite closing < tr > tag
end of outside loop
wrtite closing < table > tag
It should give you the idea
Related
I have a HTML table where there are some columns. Each column is showing its own value. But in one cell of the table, I want to display an entire array of item-names separated by commas. I want the table cell to display like this:
User ID
Item Name
1
name1, name2, name3,....
$allitemnames holds the array values like name1, name2, name3 etc
This is my current code for fetching the array of items:
$itemnames="SELECT item_name FROM orderhistory WHERE uid='$userid' AND payment_mode = 'Cash'";
$itemnamescon=$con->query($itemnames);
$allitemnames=array();
while($x = mysqli_fetch_assoc($itemnamescon))
{
$allitemnames[]=array('item_name'=> $x['item_name']);
}
$itemsarrayresult = implode(", ", $allitemnames);
It's fetching the array properly because when I try to Echo out the $allitemnames outside the HTML table then it prints the whole array. But the main problem arises when i try to print it in a HTML table cell. I used the following code to print it:
echo"<tr style='color:white; background-color:#262626'>
<td><center>".$userid."</center></td>
<td><center>".$itemsarrayresult."</center></td>
</tr>";
This code does print multiple names in a single cell but the output is not at all what I want. It prints only "Array, Array, Array...."
Firstly it shows this warning message many times and it says-
Warning: Array to string conversion in C:\xampp\htdocs\Project\pendingpayments.php on line 62
and secondly the table looks like this:
User ID
Item Name
1
Array, Array, Array,....
I've had a look online but every forum I've come across has been people trying to loop through and print 1 value per td, not all values in one td
A couple of different approaches to this:
In php:
while($x = mysqli_fetch_assoc($itemnamescon))
{
$allitemnames[]=$x['item_name'];
}
$itemsarrayresult = implode(", ", $allitemnames);
In MySQL:
SELECT GROUP_CONCAT(item_name) FROM orderhistory WHERE uid='$userid' AND payment_mode = 'Cash'"
There is an multidimension array. You don't need her.
Do like this:
$allitemnames[] = $x['item_name'];
can you change your code as following and retry?
$itemsarrayresult = ''; //initialization
while($x = mysqli_fetch_assoc($itemnamescon))
{
$itemsarrayresult .= $x['item_name'].","; //concatenation
}
//now you need to display but variable will have an addirional ',' at the end so we will trim it using rtrim
echo '<tr style="color:white; background-color:#262626">
<td><center>'.$userid.'</center></td>
<td><center>'.rtrim($itemsarrayresult,',').'</center></td>
</tr>';
I am working on a PHP webapp. I have a table which contains a value for number of cells.
Lets say cells=4.
What I need to have happen, is PHP creates input fields for the number of cells.
For example:
Cell #1: (input field)
Cell #2: (input field)
Cell #3: (input field)
Cell #4: (input field)
The key thing is here, as the numbers of cells changes, so need for the code to allow for that.
I have googled my butt off, can't find anything on how to do this. I understand that I can create a loop to create the number of input boxes, but how do I create the text to the left of the input field together with the input boxes?
//create a regular query (this one is in PDO, but it is just an example. just use your own and put a count on the results
$query = "SELECT * FROM your_table WHERE equal = to_equal";
$query = $db->query($query);
$query ->execute();
$query_fetch= $query ->fetchAll(PDO::FETCH_ASSOC);
//count the amount of rows
$query_fetch_count= count($query_fetch);
//amount of rows is now 4 for example
create a for loop to create the input fields
for ($i = 0; $i < $query_fetch_count; $i++) {
echo "<input type='text'>"
}
EDIT
//something like this I believe. Putting the $i variable in the label and the input so it is equal to each other
//or use the $query_fetch if you want to use the data and not a number.
for ($i = 0; $i < $query_fetch_count; $i++) {
echo "<label for=".$i.">$i</label>;
echo "<input type='text' id='$i'>"
}
I have a page that's suppose to create a Div for every 9 entries in the database.
Every Div will consist of 3 ULs and every UL will consist of 3 LIs.
Something like this:
Demo
So, every LI is where each entry is displayed and every Div is essentially a unique page.
This is my code so far:
$sql = mysql_query("SELECT * FROM `reviews`") or die(mysql_error());
$e_count = mysql_num_rows($sql);
$r_pages = ceil($e_count / 9);
$x = 1;
$y = 1;
if($e_count > 9){ // if there are more than 9 entries in the database
for($x=1;$x<=$r_pages;$x++){ // creates a div for every 9 items in the database
echo '<div class="rp_pages" id="rp_page_'.$x.'">';
for($y=1;$y<=3;$y++){ // creates 3 ULS in each "page"
echo '<ul>';
// 3 lis should appear here
echo '</ul>';
}
echo '</div>';
}
}
The problem is, i don't want to use multiple queries with a LIMIT in them to select the respective entries.
Can this be done with just a single query?
I only see one query (the first select). After that, instead of using it to count the number of rows, parse each row and extract the review text, this way:
Let's imagine that the reviews table has a text column where the review text is saved. Having your code:
$sql = mysql_query("SELECT * FROM `reviews`") or die(mysql_error());
$e_count = mysql_num_rows($sql);
$r_pages = ceil($e_count / 9);
$x = 1;
$y = 1;
if($e_count > 9){ // if there are more than 9 entries in the database
for($x=1;$x<=$r_pages;$x++){ // creates a div for every 9 items in the database
echo '<div class="rp_pages" id="rp_page_'.$x.'">';
for($y=1;$y<=3;$y++){ // creates 3 ULS in each "page"
echo '<ul>';
// Here the code that extract the rows from the query.
for($z=1;$z<=3;$z++){
echo '<li>';
if($data = mysql_fetch_array($sql, MYSQL_ASSOC)) {
echo $data['text']; // Use some type of parser to show special characters like < or > as text, so you are safe from code injection.
}
echo '</li>';
}
echo '</ul>';
}
echo '</div>';
}
}
As you can see, it creates a new loop to create the 3 lis and in each li extracts the text selected in the query, then echoes it.
As http://php.net/manual/en/function.mysql-fetch-array.php says:
Returns an array that corresponds to the fetched row and moves the
internal data pointer ahead.
So the next time you fetch a row, it will be the next one.
PD: PHP's mysql is deprecated. Use mysqli instead. Is the same but with another library that is currently under developement, not like mysql.
I have a query like this:
$sql = "SELECT * FROM doctors WHERE city ='$city' LIMIT 10 ";
$result = $db->query($sql);
And I show the result like this :
while($row = $result->fetch_object()){
echo $row->city;
}
The Problem :
Mysql , will search through my database to find 10 rows which their city field is similar to $city.
so far it is OK;
But I want to know what is the exact row_number of the last result , which mysql selected and I echoed it ?
( I mean , consider with that query , Mysql selected 10 rows in my database
where row number are:
FIRST = 1
Second = 5
Third = 6
Forth = 7
Fifth = 40
Sixth = 41
Seventh = 42
Eitghth = 100
Ninth = 110
AND **last one = 111**
OK?
I want to know where is place of this "last one"????
)
MySQL databases do not have "row numbers". Rows in the database do not have an inherent order and thereby no "row number". If you select 10 rows from the database, then the last row's "number" is 10. If each row has a field with a primary id, then use that field as its "absolute row number".
You could let the loop run and track values. When the loop ends, you will have the last value. Like so:
while($row = $result->fetch_object()){
echo $row->city;
$last_city = $row->city;
}
/* use $last_city; */
To get the row number in the Original Table of the last resultant (here, tenth) row, you could save the data from the tenth row and then, do the following:
1. Read whole table
2. Loop through the records, checking them against the saved data
3. Break loop as soon as data found.
Like So:
while($row = $result->fetch_object()){
echo $row->city;
$last_row = $row;
}
Now, rerun the query without filters:
$sql = "SELECT * FROM doctors";
$result = $db->query($sql);
$rowNumber = 0;
while($row = $result->fetch_object()) {
if($row == $last_row) break;
$rowNumber++;
}
/* use $rowNumber */
Hope this helps.
What you can do is $last = $row->id; (or whatever field you want) inside your while loop - it will keep getting reassigned with the end result being that it contains the value of the last row.
You could do something like this:
$rowIndex = 0;
$rowCount = mysqli_num_rows($result);
You'd be starting a counter at zero and detecting the total number of records retrieved.
Then, as you step through the records, you could increment your counter.
while ( $row = $result->fetch_object() ) {
$rowIndex++;
[other code]
}
Inside the While Loop, you could check to see whether the rowIndex is equal to the rowCount, as in...
if ($rowIndex == $rowCount) {
[your code]
}
I know this is a year+ late, but I completely why Andy was asking his question. I frequently need to know this information. For instance, let's say you're using PHP to echo results in a nice HTML format. Obviously, you wouldn't need to know the record result index in the case of simply starting and ending a div, because you could start the div before the loop, and close it at the end. However, knowing where you are in the result set might affect some styling decisions (e.g., adding particular classes to the first and/or last rows).
I had one case in which I used a GROUP BY query and inserted each set of records into its own tabbed card. A user could click the tabs to display each set. I wanted to know when I was building the last tab, so that I could designate it as being selected (i.e., the one with the focus). The tab was already built by the time the loop ended, so I needed to know while inside of the loop (which was more efficient than using JavaScript to change the tab's properties after the fact).
Hi I need to build a table with two columns from a mySQL table.
Here is what i have now:
<table>
<?php
$sql = "SELECT field1, field2 FROM tblX"
$result = mysql_query($sql) or die("\nError Retrieving Records.");
while($row = mysql_fetch_array ($result, MYSQL_ASSOC)){?>
<tr>
<td>
<?=$row['field1']?> - <?=$row['field2']?>
</td>
</tr>
<?php }?>
</table>
This will create one column table like so:
1
2
3
4
5
I need the table to be in two columns like this:
1 4
2 5
3
Is this possible if it is how do I do that?
This should do what you want, if you insist on a table.
Get the mid point:
$mid = ceil(mysql_num_rows($result)/2);
Get an array:
while( $row = mysql_fetch_row($result) ) {
$list[] = $row; }
Output the rows:
for( $i = 0; $i < $mid; $i++ ) {
$itemOne = $list[$i];
$itemTwo = $list[$i + $mid];
// echo them in two tds.
}
I agree with marco, though. You could just as easily list items one to $mid in one div, then $mid to the end in another, and use CSS to float the divs side-by-side. Using tables for formatting purposes is evil.
read all values in a list, get the half value, write a loop that shows [i] and [i+halfvalue] together
Your question is unclear, but it sounds like you want to rearrange how the data is displayed and don't want the standard row-by-row output. You should probably do this manually if your order requires a method that cannot be looped through.
You should arrange the table BEFORE you output it, then once you've got everything all tidy, simply output the code.
Must it be in tables?
If you have in it a div and you have it set so that 3 items can contain in the height.
<div id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
#container { height: 300px; }
.item { height: 100px; }
You can use some css floating to solve that combined with some padding and margin.