Making a HTML table based on SQL data in PHP - php

I am trying to make a dynamic HTML table with PHP, populating it with data from MySQL database. So far I have tried the while loop, but the result ends up in displaying the same first row it gets multiple times.
<div class = "container">
<p>Registered companies:</p>
<table border = "1px" align = "left">
<tr>
<th>Username</th>
<th>Company name</th>
<th>Company value1</th>
<th>Company value2</th>
</tr>
<?php
$compRowIncrement = 0;
while ($compRowIncrement < $companyRowCount) {
?>
<tr>
<td><?php echo $companyRow['user_name']?></td>
<td><?php echo $companyRow['company_name']?></td>
<td><?php echo $companyRow['company_value1']?></td>
<td><?php echo $companyRow['company_value2']?></td>
</tr>
<?php
$compRowIncrement++;
}
?>
</table>
</div>
It should display 3 rows of data for example (SQL query returns 3 different values). But so far I have achieved to get 3 rows (like I need) with the same data (first value it gets from the database).
How do I do it so each table row is populated with different data, as it is in the database.
I'm just learning, so if you don't mind ignore the css values in table :).
EDIT1 (Added query)//
$getPlayerCompanies = $MySQLi_CON -> query("SELECT DISTINCT *
FROM companies
LEFT JOIN player ON companies.player_id = player.player_id
LEFT JOIN users ON users.user_id = player.user_id
WHERE users.user_id =".$_SESSION['userSession']);
$companyRow = $getPlayerCompanies -> fetch_array();
$companyRowCount = $getPlayerCompanies -> num_rows;
Following query currently returns 3 rows, like it should.

where did the $companyRow values get populated?
I belive your code should be more like this (or with mysqli commands)
<?php
while ($companyRow = $getPlayerCompanies -> fetch_array() )
{
?>
<tr>
<td><?php echo $companyRow['user_name']?></td>
...
</tr>
<?php
}
?>

Related

Table data is not arranged

as i am a beginner so i want to ask how can i run the multiple queries using PHP for the same row to have multiple data in the table in html. i have tried many attempts but nothing worked i am using MYSQL as backend. I know that i have not written code for the first row and second column i.e. the second <td> on wicket keeper but the thing is that i want all rounder data to come in the second <td> of wicket keeper section. when running this code it is providing the output fine for wicket keeper but for all rounder column the data is starting after the end of wicket keeper data. i know why this problem is occurred but how can i solve this please tell??
CODE HERE:
<?php
$sql="select * from teams where role = 'WicketKeeper'";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
while($row=mysqli_fetch_assoc($result)){
?>
<tr>
<td><?php echo $row["name"] ?></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php } ?>
<?php
$sql="select * from teams where role = 'AllRounder'";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
while($row=mysqli_fetch_assoc($result)){
?>
<tr>
<td></td>
<td><?php echo $row["name"] ?></td>
<td></td>
<td></td>
</tr>
<?php } ?>
Here is a good way to generate the rows of the display you showed.
First, use this query:
SELECT name, role FROM teams ORDER BY role DESC;
It generates rows in the order you want them, wicketkeepers first.
Then, use this php code to generate your display.
<?php
$sql="SELECT name, role FROM teams ORDER BY role DESC";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
while($row=mysqli_fetch_assoc($result)){
$role = $row["role"];
$name = $row["name"];
$wicketkeeper = $role == "WicketKeeper" ? $name : "";
$allrounder = $role == "AllRounder" ? $name : "";
?>
<tr>
<td><?php echo $wicketkeeper ?></td>
<td><?php echo $allrounder ?></td>
<td></td>
<td></td>
</tr>
<?php } ?>
This renders the rows in the result set from your query, placing names in columns according to their roles.
In the general case, this task is known as pivoting a table.
Pro tip 1 Try to avoid SELECT * in queries. Instead give the names of the columns you need. This makes your code easier for a stranger to read, and it may make your queries run faster.
Pro tip 2 Anytime you catch yourself reusing the same query where it only varies by a WHERE clause, try to use a single query. This can make your application run faster.

Row within a row with JSON

I have a webpage where it shows the lists of Projects and the monitoring of its progress/finances for every quarter. As shown below:
As you can see, my table is comprises of Project Name and a lists of sub-title's underneath it. And a series of columns per each quarter. Thru PHP I was able to populate the list of sub-titles under the Project Name, which also being fetched from the server side. Here's the code:
$sql = mysqli_query($con," My SELECT Statement ");
$i=0;
while($row = mysqli_fetch_assoc($sql)){
$ptitle = $row['Title'];
$iname = $row['Item'];
if($i%1)
{
?>
<?php } else { ?>
<tr>
<?php } ?>
<td width="25%"><?php echo $ptitle; ?></td>
<td></td>
</tr>
<tr>
<td><?php echo "<ul style='list-style-type: none;'><li>".nl2br($iname)."</li></ul>"; ?></td>
<td contenteditable="true" name="v1"></td>
Note: ptitle = ProjectName and iname = Semi-title underneath the Project's name.
Now, as you can see, the Project Name column literally "conquer" a single row on the left. Yet, the rows under the column of each quarter, should have its own separately, and must be parallel to the every sub-title underneath the Project Name. (Please refer to the image above for this) the only problem am encountering is... how can I make an editable row from inside a row, without affecting mysqli result? coz basically my table right now is kinda look like this:
Anyone who's more experience on this? I need your help.
PS: ...and oh! You might be wondering why do I include JSON in the title? It is because, I originally use JSON for editing those table rows before I even use mysqli_fetch_array. But when I include the results of the array inside the <table> tag, everything's changed and JSON is no longer working. So as of now, I am force to do it manually, meaning typing each <td contenteditable=true> in all of those rows. Yet, its not the desired output since I need another row within an existing row. Ideas? Anyone?
Figure Two:
Figure Three:
Count the number of lines in $iname, and then use a loop to create that many rows of contenteditable cells. You can also use this in the rowspan attribute of the <td> containing the title and subtitles.
$rows = substr_count($iname, "\n") + 1;
for ($i = 0; $i < $rows; $i++) {
echo "<tr>";
if ($i == 0) { ?>
<td rowspan='<?php echo $rows;?>' width='25%'><?php echo $ptitle . "<br>" . nl2br($iname);?></td>
<?php }
?>
<td contenteditable="true" name="v1"></td><td contenteditable="true" name="v2"></td>...
</tr>
<?php }
DEMO

Dynamic MySQL query depending on dynamic PHP dropdown

I am looking for help with how to fetch different MySQL queries from database depending on the dynamic PHP dropdown. Below is everything I have done so far (1. created Database, 2. created PHP dynamic dropdown, 3. the struggle part - how to get the HTML/PHP form change it´s MySQL query depending on the dynamic drop-down selected in step 2).
Here is my Create Database:
CREATE TABLE computers (
id int(3) NOT NULL auto_increment primary key,
pc_make varchar(25) NOT NULL default '',
pc_model varchar(25) NOT NULL default ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO computers VALUES (1, 'Dell', 'Latitude');
INSERT INTO computers VALUES (2, 'Dell', 'Inspiron');
INSERT INTO computers VALUES (3, 'HP', 'Pavilion');
INSERT INTO computers VALUES (4, 'HP', 'Spectre');
INSERT INTO computers VALUES (5, 'Lenovo', 'Thinkpad');
INSERT INTO computers VALUES (6, 'Lenovo', 'Ideapad');
Here is the part that produces the dynamic drop-down (it gives me the result of 3 distinct records: "Dell", "HP" and "Lenovo"):
<?
$connect = mysqli_connect('localhost', '', '', '');
$sql="SELECT DISTINCT(pc_make) AS pc_make FROM computers ORDER BY pc_make ASC";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
$output= '<select name="listofpcmakes">';
while($rs = mysqli_fetch_array($result)){
$output.='<option value="'.$rs['id'].'">'.$rs['pc_make'].'</option>';
}
}
$output.='</select>';
echo $output;
?>
And below is my attempt to display only the records that match the selected pc_make (for instance Dell, which should result in 2 records) from the dynamically created dropdown. Looks like I am only hitting the wall here.
<html>
<body>
<form id="my_form" name="my_form" method="post">
<table class="table">
<thead>
<tr>
<th>id</th>
<th>pc_make</th>
<th>pc_model</th>
</tr>
</thead>
<tbody>
<?PHP
$sql_final="SELECT * FROM computers WHERE pc_make = (how to capture the 'selected pc_model' from the dynamically generated dropdown???) ";
$result_final = mysqli_query($connect, $sql_final);
while ($myrow = mysqli_fetch_array($result_final))
{
?>
<tr>
<td><?PHP echo $myrow["id"]; ?></td>
<td><?PHP echo $myrow["pc_make"]; ?></td>
<td><?PHP echo $myrow["pc_model"]; ?></td>
</tr>
<?PHP
}
?>
</body>
</html>
To restate the issue, how should I build the HTML form part, which only fetches records (pc_make, pc_model) for a single manufacturer (Dell, HP, or Lenovo) which is selected from the dynamically generated dropdown. I am trying to avoid creating static mysql queries, since the manufacturers list may considerably change in the future.
Thanks all in advance for providing helping hand...
When you select an option from your dropdown and submit the form, the result will be in $_POST superglobal. So, you need to check $_POST and retrieve the value of your dropdown.
At the top of the page:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$selected_pc_model = $_POST['listofpcmakes'];
}
You can now use $selected_pc_model in your SQL query:
$sql_final="SELECT * FROM computers WHERE pc_make = $selected_pc_model";
A more complete example using the code you submitted above:
<?php
if (($_SERVER['request_method']) == 'POST') { // Checking to see if form is submitted
$selected_pc_model = $_POST['listofpcmakes']; // Getting the selected PC model value
}
?>
<html>
<body>
<form id="my_form" name="my_form" method="post">
<table class="table">
<thead>
<tr>
<th>id</th>
<th>pc_make</th>
<th>pc_model</th>
</tr>
</thead>
<tbody>
<?php
if (isset($selected_pc_model)) { // if there is a $selected_pc_model
$sql_final="SELECT * FROM computers WHERE pc_make =" . $selected_pc_model;
$result_final = mysqli_query($connect, $sql_final);
while ($myrow = mysqli_fetch_array($result_final)) {
?>
<tr>
<td><?PHP echo $myrow["id"]; ?></td>
<td><?PHP echo $myrow["pc_make"]; ?></td>
<td><?PHP echo $myrow["pc_model"]; ?></td>
</tr>
<?php
}
} else { // else if there is NOT a $selected_pc_model
echo '<tr>
<td>Error: PC Model is not selected.</td>
</tr>';
}
?>
</tbody>
</table>
</body>
</html>
There is more to do when you write this kind of code such as data validation and error checking etc., but this should be enough to get you going. For more, you should read PHP tutorials and/or get a couple of courses.

Oracle Query not Successfully Run on PHP

Hi guys I have played around with Oracle SQL and PHP for only a short while so please forgive me if this sounds rookie.
I got this query in my PHP codes to join 4 tables together, here's the query:
SELECT P.PTY_ID,
P.PTY_UNITNUM,
P.PTY_STREET,
P.PTY_POSTCODE,
P.PTY_SUBURB,
P.PTY_CITY,
T.P_TYPE_NAME,
L.LIST_PRICE,
L.SALE_PRICE,
C.SELLER_FNAME,
C.SELLER_LNAME,
L.AVAILABILITY
FROM PROPERTY_TYPE T,
PROPERTY P,
CUSTOMER C,
LISTINGS L
WHERE P.P_TYPE_ID = T.P_TYPE_ID(+)
AND L.SELLER_ID = C.SELLER_ID(+)
AND L.PTY_ID = P.PTY_ID(+)
ORDER BY P.PTY_ID;
In nutshell what I want to achieve is to show the property details, listings information (prices, availability) and customer name all together in a single table. The query works perfectly in SQL developer and gave me the results I wanted, but it is not working in my PHP file and gave me no results but blank.
In order to debug I used another set of data and put in and it worked fine as well. Therefore I can tell the PHP codes are cool and go back to the query. But I can't find any problem in it. Can anyone help me? Did I use the join statements wrongly?
I just add my PHP code below in case you might be interested in it:
<!DOCTYPE html>
<html>
<head><title>Update/Delete Property</title></head>
<body>
<center><h2>Property Records</h2></center>
<?php
$conn = oci_connect("username","password","database");
$query = "SELECT P.PTY_ID, P.PTY_UNITNUM, P.PTY_STREET, P.PTY_POSTCODE, P.PTY_SUBURB, P.PTY_CITY, T.P_TYPE_NAME,
L.LIST_PRICE, L.SALE_PRICE,
U.SELLER_FNAME, U.SELLER_LNAME,
L.AVAILABILITY
FROM PROPERTY_TYPE T, PROPERTY P, CUSTOMER C, LISTINGS L
WHERE P.P_TYPE_ID = T.P_TYPE_ID(+)
AND L.SELLER_ID = U.SELLER_ID(+)
AND L.PTY_ID = P.PTY_ID(+)
ORDER BY P.PTY_ID";
$stmt = oci_parse($conn,$query);
oci_execute($stmt);
?>
<table border="2" align="center">
<tr>
<th><b>Property ID</th>
<th><b>Unit Number</th>
<th><b>Street</th>
<th><b>Postcode</th>
<th><b>Suburb</th>
<th><b>City</th>
<th><b>Property Type</th>
<th><b>Listing Price</th>
<th><b>Sale Price</th>
<th colspan = '2'><b>Seller Name</th>
<th><b>Availability</th>
<th><b>Checkbox</th>
</tr>
<?php
while ($row = oci_fetch_array($stmt))
{
?>
<tr>
<td><?php echo oci_result($stmt,"PTY_ID");?></td>
<td><?php echo oci_result($stmt,"PTY_UNITNUM");?></td>
<td><?php echo oci_result($stmt,"PTY_STREET");?></td>
<td><?php echo oci_result($stmt,"PTY_POSTCODE");?></td>
<td><?php echo oci_result($stmt,"PTY_SUBURB");?></td>
<td><?php echo oci_result($stmt,"PTY_CITY");?></td>
<td><?php echo oci_result($stmt,"P_TYPE_NAME");?></td>
<td><?php echo oci_result($stmt,"LIST_PRICE");?></td>
<td><?php echo oci_result($stmt,"SALE_PRICE");?></td>
<td><?php echo oci_result($stmt,"SELLER_FNAME");?></td>
<td><?php echo oci_result($stmt,"SELLER_LNAME");?></td>
<td><?php echo oci_result($stmt,"AVAILABILITY");?></td>
</tr>
<?php
}
oci_free_statement($stmt);
oci_close($conn);
?>
</table>
</body>
</html>
The query in this PHP code is similar so I did not change it. It was not running properly as well.
NEW PROGRESS..
So I tried to change one line of the code:
AND P.PTY_ID = L.PTY_ID(+)
I started to get something...But still not what I wanted:
New result
I am pretty sure it's about the query now and it's something about the connection between entities. SO again I am sending up my ERD here, which might help (focus on table LISTINGS, SELLER (which is called CUSTOMER now) and PROPERTY):
ERD of the entities

create table in html as per the condition given for a table to mysql database table

I want to create a table(in HTML) which will display rows and columns where i am calling from my query statement i.e.,
select id,name,city from contacts where enquiry_id=125
which will display 3 to 4 rows of data having enquiry_id=125.
The result will be displayed in HTML format for PHP.(or HTML)..
You can try this and do not forget to connect to the database:
while ($record = mysql_fetch_array($result, MYSQL_ASSOC)) {
?>
<tr>
<td><?=$record['id']; ?></td>
<td><?=$record['name']; ?></td>
<td><?=$record['city']; ?></td>
</tr>
<?
}
mysql_free_result($result);
?>
</table>

Categories