How to address every line of a mysql table? - php

To create a dynamic table within php, I set the variable $count from a query, which counts the rows in specific table. Then I would like to create a table with the exact number of rows as a html table:
for($i=1;$i=<$count;$i++){
echo"<tr><td>$name</td><td>$rights</td></tr>";
}
That's the way i want the table to be displayed. But everytime the for-loop is called, the values of $name and $rights should be taken from the database-table. But how should i handle this? I thought about a simple query selecting the name from the line where ID equals i. But then i remembered that always when i delete an entry from the table there will be gaps.
For example when there 3 entries and i delete the second one. There just are 2 entries; so the name of the second row, which ID is 3, will never be selected. Is there any way of handling this problem in an appropriated way?

You wouldnt use a for you would use a while or a foreach with the results from the query.
<?php
$db = new PDO($dsn, $user, $pass);
$stmt = $db->query('SELECT id, rights FROM the_table');
?>
<table>
<thead>
<tr>
<th>Id</th>
<th>Rights</th>
</tr>
</thead>
<tbody>
<?php if($stmt !== false): ?>
<?php foreach( $stmt as $row): ?>
<tr>
<td><?php echo $row['id'] ?></td>
<td><?php echo $row['rights'] ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>

Related

How to make a member list with database?

How do I make a member list with PHP and MySQL?
I have user accounts, login and that stuff. How do I make a page that shows all the members?
I can provide code!
NOTE: Your question is not clear. You have not included any code or query snippet. I will try my best to answer your question.
As per my knowledge I think your users are nothing but the members. Just write a query to pull all the users from the users table and display.
NOTE : I will use mysqli_* function without any escaping please help yourself.
<?php
include_once 'db_connect.php'; /Line to include the database connection file, which had $link as resource */
$membersQuery = mysqli_query($link, "SELECT * FROM users");
$members = array();
if(mysqli_num_rows($membersQuery) > 0){
while($row = mysqli_fetch_assoc($membersQuery)){
$members[] = $row; //Get all the members row by row and store in $members array
}
}
?>
<table>
<thead>
<tr>
<th>Firstname</th>
</tr>
</thead>
<tbody>
<?
if(count($members) > 0){
foreach($members as $member){
<tr>
<td><?php echo $member['firstname']; ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
Even while looping in table you can use the following command
<tbody>
<?
if(mysqli_num_rows($membersQuery) > 0){
while($member = mysqli_fetch_assoc($membersQuery)){
<tr>
<td><?php echo $member['firstname']; ?></td>
</tr>
<?php
}
}
?>
</tbody>

Creating arrays from columns in database that I can echo in html

Im sorry if this has been answered before but I am new to PHP and MySQL and I can't figure this out.
Pretty much every time I alter my code to include an array I get a fatal error. What I am trying to do is display all the data in 3 columns from my table.
I have my site set up where you log in and I store that user's name as a "code" in a session. I have a table that has multiple user form entries that are differentiated by the user's code because in my form, I grab the code as a hidden field and add it to the entry in the table.
So far I have been able to isolate those entries by the users code, in one column I have the sum of all of the user's numerical data and I am able to echo this as a total.
I want the other 3 columns to display all the values in their columns and for each value have a line break in between them. And I am trying to print or echo these results in specific parts on a confirmation page.
I have seen examples with PDO using fetch_all and other examples of storing arrays but I can't seem to figure it out with my existing code.
Here is my existing code:
<?php
$user = *****;
$pass = *****;
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
$stmt = $dbh->prepare("SELECT sum(price),part_number,location,price FROM products WHERE code = :usercode");
$stmt->bindParam(':usercode', $_SESSION['MM_Username']);
if ($stmt->execute()) {
$user = $stmt->fetch(PDO::FETCH_ASSOC);
}
?>
And here is where I want to display the results:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
</tbody>
</table>
Try like this:
<table style="margin:0 auto;" cellspacing="7" width="100%">
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><? echo $user['part_number']; ?></td><!--all column values-->
<td><? echo $user['location']; ?></td><!--all column values-->
<td><? echo $user['price']; ?></td><!--all column values-->
<td><? echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>
There are a few things in your question that jumped out at me.
It looks like you're attempting to display both raw data (each row) and aggregate data (the sum of prices). It can be simpler to fetch the information separately instead of in the same request.
You had mentioned fetch_all in PDO, but the method is fetchAll.
Instead of working with PDO within the HTML (like iterating through while calling fetch), write code so that you're simply iterating over an array.
Based on your description of the problem, it sounds like you want to separate the total price from the raw data, so you can reduce your table down to three columns and use the table footer to show the total price.
Based on those, I have the following solution that
Separates the calls to get data into descriptive functions
Use money_format to better display prices
Removes any database-specific manipulation from the view itself.
<?php
function getTotalPriceForUser(PDO $database_handler, $user_code)
{
// If no rows are returned, COALESCE is used so that we can specify a default
// value. In this particular case, if there aren't any products that would
// match, we'd still get a result with a value of 0.
$sql = 'SELECT COALESCE(SUM(price), 0) FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// This fetches the first row of the result; the result is given as an array with numerical keys.
$result = $stmt->fetch(PDO::FETCH_NUM);
// [0] refers to the first column
return $result[0];
}
function getProductsForUser(PDO $database_handler, $user_code)
{
$sql = 'SELECT part_number, location, price FROM products WHERE code = ?';
$stmt = $database_handler->prepare($sql);
$stmt->execute(array($user_code));
// fetchAll returns all rows, with each row being an associative array (where part_number, location and price are the keys)
return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// Set up the database information
$user = '*****';
$pass = '*****';
$dbh = new PDO('mysql:host=localhost;dbname=*****', $user, $pass);
// money_format to use the below money formatting; this makes sure there's a dollar sign to represent USD, for example
setlocale(LC_MONETARY, 'en_US.UTF-8');
// Store $_SESSION['MM_Username'] in a local variable
$user_code = $_SESSION['MM_Username'];
// Get the list of products associated with this user code
$products = getProductsForUser($dbh, $user_code);
// Get the total cost of the products
$total_cost = getTotalPriceForUser($dbh, $user_code);
?>
<table style="margin:0 auto;" cellspacing="7" width="100%">
<thead>
<tr>
<th>Part Number</th>
<th>Location</th>
<th>Cost</th>
</tr>
</thead>
<tfoot>
<tr>
<td style="text-align: right" colspan="2">Total:</td>
<td style="text-align: right; border-top: 1px solid #999"><?= money_format('%.2n', $total_cost) ?></td>
</tr>
</tfoot>
<tbody>
<?php foreach($products as $product): ?>
<tr>
<td><?= $product['part_number'] ?></td>
<td><?= $product['location'] ?></td>
<td style="text-align: right"><?= money_format('%.2n', $product['price']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
Change to this
<? echo
to
<?php echo
Try this:
...
$keys = array_keys($user);
foreach ($keys as $k) :
?>
<td><?= $user[$k]?></td>
<?php endforeach?>
<table>
<tbody>
if ($stmt->execute()) {
while($user = $stmt->fetch( PDO::FETCH_ASSOC )){
<tr>
<td><?php echo $user['part_number']; ?></td><!--all column values-->
<td><?php echo $user['location']; ?></td><!--all column values-->
<td><?php echo $user['price']; ?></td><!--all column values-->
<td><?php echo "Total:", $user['sum(price)']; ?><br></td><!--this is ok-->
</tr>
}
}
</tbody>
</table>

Foreach loop with two queries inside

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

Matching id's from two database tables to get username from one

I am wanting to match my user_id column from my announcements table to the id column in my users table. I then want to get the username from the users table where the id's match.
I initially had the following query
if ($announcements_stmt = $con->prepare("SELECT * FROM announcements"))
I am getting the following error with my current code..
Warning: mysqli_stmt::bind_result(): Number of bind variables doesn't match number of fields in prepared statement in
Which I know what this means, but do I need to add in every column table from my users table for this to work or is there another way to do this? If I do need to add all of the columns as variables in my bind_result, does it matter which order I put them in? Announcements first or users or vise versa?
if ($announcements_stmt = $con->prepare("SELECT * FROM announcements
INNER JOIN users
ON announcements.user_id = users.id")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id,
$announcements_user_id, $announcements_messages, $announcements_date);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
$announcements_stmt->store_result();
$announcements_result = array();
?>
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
}
update..
if ($announcements_stmt = $con->prepare("SELECT announcements.id, announcements.user_id, announcements.messages, announcements.date, users.username FROM announcements
INNER JOIN users
ON announcements.user_id = users.id")) {
$announcements_stmt->execute();
$announcements_stmt->bind_result($announcements_id,
$announcements_user_id, $announcements_messages, $announcements_date, $announcements_username);
if (!$announcements_stmt) {
throw new Exception($con->error);
}
$announcements_stmt->store_result();
$announcements_result = array();
?>
Current Announcements
<table>
<tr>
<th>ID</th>
<th>Username</th>
<th>Message</th>
<th>Date</th>
</tr>
<?php
while ($row = $announcements_stmt->fetch()) {
?>
<tr>
<td><?php echo $announcements_id; ?></td>
<td><?php echo $announcements_username; ?></td>
<td><?php echo $announcements_messages; ?></td>
<td><?php echo $announcements_date; ?></td>
</tr>
<?php
}
?>
}
</table>
<?php
}
}
The warning indicates when you are binding the result fields into variables, the number of variables does not match the number of fields in the result set:
$announcements_stmt->bind_result($announcements_id, $announcements_user_id, $announcements_messages, $announcements_date, $announcements_username);
The easy way around this is to always specify the fields in the SELECT statement (just an example):
SELECT t1.id, t1.user_id, t1.messages, t1.date, t2.username
Instead of:
SELECT *

Put records next to eachother in columns using mysql_fetch_array?

I use mysql_fetch_array to fetch data from a mysql results set:
while($row = mysql_fetch_array($qry_result)){
Next I would like to place the data into columns in a table, but maximum of two columns at each row.
So using a table:
<table>
<tr>
<td>Record Here</td>
<td>Record Here</td>
</tr>
<tr>
<td>Record Here</td>
<td>Record Here</td>
</tr>
<tr>
<td colspan="2">Record Here</td>
</tr>
As you see above, I want to loop the results and create table columns in the loop.
This so that the records line up two and two on a results page.
Remember, if there is an odd number of records, then the last table column would need a colspan of 2, or perhaps just use an empty column?
Anybody know how to do this?
If I use a for loop inside the while loop, I would just be lining up the same records x times for each while loop. Confusing...
Any ideas?
Thanks
Implement a (1-indexed) counter within the while loop. Then add (after the loop):
if ($counter%2)
echo '<td></td>';
This will leave an additional blank cell in your table if the last column contains only one row.
Something like this should work...
<table>
<?php
while(true) {
$row1 = mysql_fetch_array($qry_result);
if($row1 === false) break;
$row2 = mysql_fetch_array($qry_result);
if($row2 !== false) {
echo "<tr><td>$row1</td><td>$row2</td></tr>";
} else {
echo "<tr><td coslspan=\"2\">$row1</td></tr>";
break; // output the final row and then stop looping
}
}
?>
</table>
<table>
<tr>
<?
$i=1;
$num = mysql_num_rows($qry_result);
while($row = mysql_fetch_array($qry_result)){
if($i%2==1)
?>
<tr>
<?
?>
<td <? if($i==$num && $i%2==1)echo 'colspan="2"';?>><?=$row['keyName']?></td>
<?
if($i%2==0)
{
<?
</tr>
?>
}
$i++;
}
?>

Categories