I have two tables like this.
books
=====
b_id a_id book_name
1 1 ABC
2 1 DEF
3 2 GHI
authors
=======
a_id author_name
1 A1
2 A2
I need a table like this.
S.No BookName
-----------------
A1
==
1 ABC
2 DEF
A2
==
1 GHI
What i'm planning to do is
1. Do a while loop and get the author name first and print it
2. Use the author id inside the first loop and do another one iteration to get the list of book list for each author.
A sample code is like this:
<table cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>
<th>S.No</th>
<th>Book Name</th>
</tr>
</thead>
<?php
$mysql_query1 = "my sql query to get the author name list first";
$results = mysql_query ( $mysql_query1 ) or die ( mysql_error () );
while($row = mysql_fetch_array($results)){
?>
<tbody>
<tr>
<td style="background:none;"><u><?php echo $row['author_name']; ?></u></td>
</tr>
<?php
$result = mysql_query ( "mysql query to get the list of books for each author with a where condition like this where a_id=$row['a_id']" ) or die ( mysql_error () );
$book_count = mysql_num_rows($result);
while($row1 = mysql_fetch_array($result)){
?>
<tr>
<?php for($i=1;$i<=$book_count;$i++){ ?>
<td><?php echo $i; ?> </td>
<td><?php echo $row1['book_name']; ?> </td>
<?php } ?>
</tr>
<?php
}
?>
</tbody>
<?php } ?>
</table>
My friends insisted me that the above method is a old one, and there is something to do with just few line codes. Is it?
If yes, could someone redefine my code and give me.
Thanks,
Kimz
Сan this be so?
$mysql_query1 = "select * from authors"
$result = mysql_query ( "select * from books where a_id=".$row['a_id']) or die ( mysql_error () );
The PHP method would be something like:
//First let's get all the values we need and store them in array format
// so that we don't need to make expensive calls to the database
<?php
$result = mysql_query("SELECT author_name, book_name FROM books b, authors a WHERE b.a_id=a.a_id");
$arr = array();
while($row=mysql_fetch_assoc($query)){
//storing books by author
$arr[$row['author_name']][]=$row['book_name'];
}
//so now we have an array like ['A1'=>'ABC','DEF'],['A2'=>'GHI']
?>
<table cellpadding="0" cellspacing="0" border="0">
<thead>
<tr>
<th>S.No</th>
<th>Book Name</th>
</tr>
</thead>
<tbody>
<?php
//let's print out the contents of our array in table format
foreach($arr as $author=>$val){
echo "<tr>
<td style='background:none;'><u>".$author."</u></td>
<td></td>
</tr>";
foreach($val as $ind=>$book_name)
{
echo "<tr>
<td>".$ind."</td>
<td>".$book_name."</td>
</tr>";
}
}
?>
</tbody>
</table>
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Related
Im trying to list the result from MySQl results as a Table in my HTML.
My PHP file:
$stmt = $this->get('database_connection')
->executeQuery(
'SELECT * FROM members'
);
while (false !== ($objMember = $stmt->fetch(\PDO::FETCH_OBJ)))
$template->listTable= implode(', ', $objMember['firstname']);
return $template->getResponse();
And in HTML:
block('content'); ?>
<p><?= $this->listTable ?></p>
<?php $this->endblock(); ?>
But I dont get any reults in the html file. What is the correct way to list all results from SQL to a Table?
I don't know if it is the right way or not but it works as this :
I create some html table
<table class="table">
<thead class=" text-primary">
<th>table header</th>
<th>table header 2</th>
</thead>
<tbody>
In here my PHP begins
<?php
$query = mysqli_query($mysql_connection, "SELECT * FROM tbale WHERE conditions");
while ($array = mysqli_fetch_array($query)) {
$k_exmaple_1 = $array['column1'];
$k_exmaple_2 = $array['column2'];
echo "
<tr>
<td>$k_exmaple_1</td>
<td>$k_exmaple_2</td>
</tr>
";
}
?>
PHP Ends
I connected the table in MySQL, and selected my rows then print it with echo in html format.
</tbody>
</table>
Table ends
So I'm trying to use php and mysql to put data in my datatables on my website. I wrote some code at the top of my file to confirm that I am accessing my database correctly. The table is displayed correctly when i manually entered some data, but with my php code, the table says "No data available in table". Any thoughts on whats wrong with my php?
$q = "SELECT tickets.ticket_id, tickets.section, tickets.row, tickets.price, users.first_name as first_name, users.last_name as last_name
FROM tickets
LEFT JOIN users
ON tickets.seller_id = users.umid
Where(tickets.game_id = '$g')";
$r = #mysqli_query ($dbc, $q);
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Section</th>
<th>Row</th>
<th>Price</th>
<th>Seller</th>
</tr>
</thead>
<tbody>
<?php
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
echo '
<tr>
<td>'.$row["section"].'</td>
<td>'.$row["row"].'</td>
<td>'.$row["price"].'</td>
<td>'.$row["first_name"]. " ". $row["last_name"]. '</td>
</tr>
';
}
?>
</tbody>
</table>
This is what the table looks like
Link to the webpage
Figured out the problem. I looped through my row earlier in my code, so when i wanted to put the info in the table, it was at the end of the array.
I have two queries which is working fine and it would retrieve 3 rows each query. I am trying to display a query result on a table using foreach with two(2) queries inside a foreach loop. I tried putting two result() on foreach but its an error. How can i display a two result() on a single foreach loop? I don't know how can i achieve this.
Query 1 would be on column "Investor Name" then query 2 will be on "Amount".
Here is the code:
<?php
$query5 = $this->db->query("SELECT * FROM ".tbl_investors." WHERE id IN (SELECT MAX(investor_id) FROM ".tbl_investors_ledger." GROUP BY investor_id ) AND deleted = 0");
$query6 = $this->db->query("SELECT * FROM ".tbl_investors_ledger." WHERE id IN (SELECT MAX(id) FROM ".tbl_investors_ledger." GROUP BY investor_id ) AND deleted = 0");
?>
<table class="table table-striped table-bordered table-hover" id="dataTables">
<thead>
<tr>
<td>Investor Name</td>
<td>Amount</td>
</tr>
</thead>
<tbody style="text-align: center;">
<?php
foreach ($query5->result() as $row) && ($query6->result() as $row2){
?>
<tr>
<td><?php echo $row->last_name.', '.$row->first_name; ?></td>
<td><?php echo $row2->amount; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
You can't use two array_expressions on foreach loop. It is better to use join on your query to make it one. something like
$query = "SELECT `tbl_investors`.* , `tbl_investors_ledger`.*
FROM `tbl_investors`
LEFT JOIN `tbl_investors_ledger`
ON `tbl_investors`.id = `tbl_investors_ledger`. investor_id
WHERE `tbl_investors`.deleted = 0 AND `tbl_investors_ledger`.deleted = 0
GROUP BY `tbl_investors_ledger`.investor_id
ORDER BY `tbl_investors_ledger`.id DESC ";
As far as I know, a foreach loop can only handle one query. I see two options out of this, really..
Option 1
Create two different foreach loops, not inside each other since that would make double results, but outside each other. That might not do what you want to, but it could be worth a shot, like so:
<!-- FIRST LOOP -->
<?php
foreach ($query5->result() as $row) {
?>
<td> Your data goes here </td>
<?php
}
?>
<!-- SECOND LOOP -->
<?php
foreach ($query6->result() as $row) {
?>
<td> Your data goes here </td>
<?php
}
?>
Option 2
Create only one query, requiring only one of the loops, by taking use of "JOIN"
See answer at this post
I have a foreach loop to show all of the usernames from my database.
When I run the loop I get, '10' is the rank.
Daniel 10
Daniel 10
Daniel 10
Daniel 10
Daniel 10
This is the loop that I have
<?php
include_once 'dbconfig.php';
if(!$user->is_loggedin())
{
$user->redirect('index.php');
}
$user_id = $_SESSION['user_session'];
$stmt = $DB_con->prepare("SELECT * FROM users ");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
?>
<h1>Players</h1>
<table>
<tr>
<th>Battletag</th>
<th>Preferred Role</th>
<th>Rank</th>
</tr>
</tr>
<?php var_dump($row)?>
<?php foreach($userRow as $row): ?>
<td> <?php print($row['user_name']); ?></td>
<td> <?php print($row['user_rank']); ?></td>
</tr>
<?php endforeach; ?>
Home
</table>
I don't see why it is looping the 1 user 5 times, instead of looping through all users once
OK 3 things. First, you don't need parameter binding in
$stmt->execute(array(":user_id"=>$user_id));
so, instead of that, use:
stmt->execute();
Next, instead of fetch, use fetchAll function. You need this in order to get all rows for your query from database, instead of only first one.
And finally, in the loop the problem is that you are using $userRow instead of $row inside for loop. Try:
<?php foreach($userRow as $row): ?>
<td> <?=$row['user_name']?></td>
<td> <?=$row['user_rank']?></td>
</tr>
<?php endforeach; ?>
I think this might work for you. It's not a for each loop though. If you're set on using a for each loop then disregard.
$sql = "SELECT user_name, user_rank,
FROM XXX//your database//";
$result = $conn->query($sql);
//Display results
if ($result->num_rows > 0) {
echo '<table>
<tr>
<th>User Name</th>
<th>User Rank</th>
</tr>';
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row["user_name"]. "</td>
<td>" . $row["user_rank"]. "</td>
</tr>";
}
echo "</table>";
} else {
$message = "0 results";}
$conn->close();
?>
I'm trying to use if-statement to change <td>-s color.
Basically, I have a simple query to retrieve information from the database.
Additionaly, I have a column there which keeps the information like if the task is accomplished or not. When I retrieve the information I get all of them, but I need the accomplished tasks to be green, and others without any color.
I've searhed for the answer, but I couldn't find anything that satisfies me.
For example:
$qry = mysql_query("select * from table");
$recs = array();
while($row = mysql_fetch_array($qry))
$recs[]=$row;
mysql_free_result($qry);
I've tried to add while statement to the code above, but I was confused and it didnt work :(
I'm printing the results using heredoc:
How to give them color here?
<?php
$last_id=0;
foreach($recs as $rec)
{
$html=<<<HTML
<tr>
<td><b>Номер</b></td>
<td>$rec[0]</td>
</tr>
<tr>
<td><b>Номер документа</b></td>
<td>$rec[1]</td>
</tr>
<tr>
<td><b>Дата регистрации</b></td>
<td>$rec[8]</td>
</tr>
<tr>
<td><b>От кого</b></td>
<td>$rec[2]</td>
</tr>
<tr>
<td><b>По</b></td>
<td>$rec[4]</td>
</tr>
<tr>
<td><b>Краткое содержание</b></td>
<td>$rec[3]</td>
</tr>
<tr>
<td><b>Исполнитель</b></td>
<td>$rec[5]</td>
</tr>
<tr>
<td><b>Срок исполнения</b></td>
<td>$rec[6]</td>
</tr>
<tr>
<td><b>Срок исполнения продлен до</b></td>
<td><b>$rec[10]</b></td>
</tr>
<tr>
<td><b>Прислан</b></td>
<td>$rec[9]</td>
</tr>
<tr>
<td><b>Примечание</b></td>
<td>$rec[7]</td>
</tr>
<tr>
<td bgcolor="#838B83"> </td>
<td bgcolor="#838B83"> </td>
</tr>
HTML;
print $html;
if($rec[0]>$last_id)
$last_id=$rec[0];
};
$new_id=$last_id+1;
?>
rather than colour use a class, so you can change it in CSS
<td<?php if($row['complete']) echo ' class="complete"'; ?>>data</td>
<table>
<tr>
<td>column heading</td>
</tr>
<?php
$qry=mysql_query("select * from table");
while($row=mysql_fetch_array($qry)) {
if($row['urcolumnn']==1)
{
echo "<tr bgcolor=green>";
}
else
{
echo "<tr>";
}
?>
<td>
<?php echo $row['urcolumn']; ?>
</td>
</tr>
<?php } ?>
</table>
This is an example code. think this will help you. here i give the background color to <tr> like this if u want to give color to <td> use this <td style="background-color:green;">
I would suggest you to use ternary operator, rather than using IF statement, or your could use another workaround to use arrays to define colors, this would help you to define various colors for each status value globally, please find an example below:
$aryColor = array(
'complete' => 'green',
'incomplete' => "red",
'pending' => 'orange'
.....
);
//you can specify values for all of your status, or leave them blank for no color, the keys in the array are the possible values from your status field
foreach($recs as $rec) {
echo '<tr bgcolor="'.$aryColor[$rec['status_field']].'">
<td>'.$rec['title_field'].'</td>
</tr>';
}
I hope this helps you out, and you can easily edit this for HEREDOC.
first you should change your column values change its structure to int and set default value as "0".so when your task is complete the field value should be change to "1".
now come to your code:
$qry = mysql_query("select * from table");
while($row = mysql_fetch_assoc($qry)){
if($row['status']==1){
echo "<td color="green">Data</td>"
}
else{
echo "<td color="white">Data</td>";
}
}
Hence you can get the rows in green which status is==1 means complete and white for incomplete.