I new at php programming and the question I have is about counting. I search around different website and could not come up direct answers on counting. Now what I am trying to do is make a website where you enter data and displays a table with that information in it. I got it to work for must part in displaying data now. Now I need it to count or sum one column in my database and display the answer in another field on the table when data comes up a second or third time.
Here is example of my code that I am working with:
$sql = "Select * FROM modems";
$query = $db->prepare( $sql );
$query->execute();
$results = $query->fetchAll( PDO::FETCH_ASSOC );
$return = "Select SUM(maddress) FROM modems";
$query = $db->prepare( $return);
$query->execute();
?>
<!---Table class that creates a table--->
<table class="table">
<caption>Modem Results Page</caption>
<tr>
<th>Mac Address</th>
<th>Modem Model Number</th>
<th>Date</th>
<th>Reported Problem</th>
<th>Good or Bad</th>
<th>Initials</th>
<th>Times Returned</th>
</tr>
<input type='button' value='Return to Modems Page' onclick="location.href='modems.php'"><br><br>
<!---Populates data in the table--->
<?php foreach( $results as $row){
echo "<tr><td>";
echo $row['maddress'];
echo "</td><td>";
echo $row['mmodel'];
echo "</td><td>";
echo $row['date'];
echo "</td><td>";
echo $row['mproblem'];
echo "</td><td>";
echo $row['good_bad'];
echo "</td><td>";
echo $row['initials'];
echo "</td><td>";
echo $row['SUM(maddress)'];
echo "</td>";
echo "</tr>";
}
?>
</table>
The problem that I have is nothing displaying in times returned part of website, I know that problem is the second query not sure how to end it to get it to display correctly and any help would be appreciated.
Thanks Jonathan
Related
I'm making a sports solution to retrieve data from play by play to webpage.
And now I am stuck with a moment to retrieve player name from mysql db, put to boxscore table (that was done), and then retrieve all stats based on this name.
As example - how many points he made, how many assists were associated with his name, etc.
At the end I want to get this kind of table (all formating /styling done and ready):
Here is a php code, question based in the "echo" point.
I cant finnd proper way to count how many assists a.e. player made in the same request.
<?php
require "connection.php";
$game_id = 1760;
$player = 'KURBANOV, NIKITA';
$team = 'CSKA Moscow';
$stmt = $pdo->prepare('SELECT * FROM game_results WHERE game_id = :game_id AND team = :team AND action = "Assist" ORDER BY player DESC');
$stmt->execute(array('game_id' => $game_id, 'team' => $team ));
$result = $stmt -> fetchAll();
echo '<table class="table table-condensed table-hover"><tbody>';
echo '<thead>
<tr>
<th>Name</th>
<th>POS</th>
<th>MIN</th>
<th>PTS</th>
<th>OREB</th>
<th>DREB</th>
<th>TREB</th>
<th>AST</th>
<th>STL</th>
<th>TOV</th>
<th>Fm</th>
<th>Fc</th>
</tr>
</thead>';
foreach( $result as $row ) {
echo '<tr>';
echo '<td>'.$row['player'].'</td>';
echo '<td>'.$row['action'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '<td>'.$row['game_id'].'</td>';
echo '</tr>';
}
echo '</tbody></table>';
Here is the db data example:
DB example
Ok after your edit I think I guessed what you want to do.
You want to count how many entrys you have in your table of a specific player and a specific action.
SELECT player,
Count(CASE action
WHEN 'Assist' THEN 1
ELSE 0
end) AS assists,
Count(CASE action
WHEN '<other case>' THEN 1
ELSE 0
end) AS other_case
FROM `game_results`
WHERE 1
GROUP BY player
This above SQL Select should do what you want, replace other case with what ever you else have.
EDIT:
You should be able to print it out just like you did before:
<?php
// your other code ...
echo '<table class="table table-condensed table-hover"><tbody>';
echo '<thead>
<tr>
<th>Name</th>
<th>assists</th>
<th>other case</th>
</tr>
</thead>';
foreach( $result as $row ) {
echo '<tr>';
echo '<td>'.$row['player'].'</td>';
echo '<td>'.$row['assits'].'</td>';
echo '<td>'.$row['other_case'].'</td>';
echo '</tr>';
}
echo '</tbody></table>';
I have a webpage that displays cars from the first car in the table to the last car with a while loop.
I have the following columns: Make, Model, Price. In my syntax I have an anchor tag around the Make rows that links to the description page of the Make you click on.
I want my <h> tags to change to the Model of the corresponding Make.
I've spent over an hour trying to achieve this but all I could come up with is this:
<?php
$query = "SELECT Model FROM inventory;";
$Vtitle = $conn->query($query);
$Vtitle_ar = mysqli_fetch_assoc($Vtitle);
echo "<h1>".$Vtitle_ar['Model']."</h1>";
?>
This works to an extent.
Every anchor I click replaces the <h> tags with only the first result under the Model column in my database.
Here is my code for the the entire car inventory page
<?php
$query = "SELECT * FROM inventory;";
/* Try to query the database */
if ($result = $conn->query($query)) {
// Don't do anything if successful.
}
else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
// Create the table headers
echo "<table id='Grid' style='width: 80%'><tr>";
echo "<th style='width: 50px'>Make</th>";
echo "<th style='width: 50px'>Model</th>";
echo "<th style='width: 50px'>Asking Price</th>";
echo "</tr>\n";
$class = "odd"; // keep track of whether a row was even or odd, so we can style it later
// Loop through all the rows returned by the query, creating a table for each row
while ($result_ar = mysqli_fetch_assoc($result)) {
echo "<tr class=\"$class\">";
echo "<td><a href='viewcar.php?VIN=".$result_ar['VIN']."'>".$result_ar['Make']."<a></td>";
echo "<td>".$result_ar['Model']."</td>";
echo "<td>".$result_ar['ASKING_PRICE']."</td>";
echo "</td></tr>\n";
// if the last row was even, make the next one odd and vice-versa
if ($class=="odd") {
$class = "even";
}
else {
$class = "odd";
}
}
echo "</table>";
$conn->close();
?>
Does anyone how I can do this?
I'm new to programming and I'm trying to use this for an actual project I'm working on for a hair salon's website
Add a WHERE clause to the query.
$vin = $_GET['VIN'];
$stmt = $conn->prepare("SELECT Model FROM inventory WHERE VIN = ?");
$stmt->bind_param("s", $vin);
$stmt->execute();
$stmt->bind_result($model);
$stmt->fetch();
echo "<h1>$model</h1>";
Though not a solution resolved with the use of a where clause as given by #Barmar whilst formatting the code I did find an error within the HTML which was not immediately obvious
The line echo "</td></tr>\n"; has an extra </td> which would break the flow of the html and can have detrimental effects. Also, // Don't do anything if successful. makes no sense - if there are results then process the recordset otherwise show the error ;-)
<?php
$query = "SELECT * FROM inventory;";
if ( $result = $conn->query( $query ) ) {
echo "
<table id='Grid' style='width: 80%'>
<tr>
<th style='width: 50px'>Make</th>
<th style='width: 50px'>Model</th>
<th style='width: 50px'>Asking Price</th>
</tr>";
$i=0;
while( $result_ar = mysqli_fetch_assoc( $result ) ) {
$class = $i %2 == 0 ? 'even' : 'odd';
echo "
<tr class='$class'>
<td><a href='viewcar.php?VIN={$result_ar['VIN']}'>{$result_ar['Make']}<a></td>
<td>{$result_ar['Model']}</td>
<td>{$result_ar['ASKING_PRICE']}</td>
</tr>";
$i++;
}
echo "</table>";
} else {
echo "Error getting cars from database:" .$conn->error()."<br>";
}
$conn->close();
?>
For styling alternate table rows ( the above uses a modulus function to calculate odd/even ) you can do it with some simple CSS - such as
tr:nth-child( odd ){/* rules */}
I am trying to get my code to display in an HTML table using the while loop. However, I can't get my table to display. Is there something wrong with the way I am trying to echo the table out?
<?php
#-----call includes-----# include('E:/includes/database.php');
include('E:/includes/sendmail.php');
ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors','on');
$do = $_REQUEST['do'];
$queryOrders = "select t2.SlpName As 'Seller', t1.SWW As 'Vendor', t0.DocDate As 'Date',t0.DocTotal As 'Total'
from twh.dbo.OINV t0
inner join twh.dbo.inv1 t1 on t0.DocEntry = t1.DocEntry
inner join twh.dbo.OSLP t2 on t1.SlpCode = t2.SlpCode
where t0.DocDate > DATEADD (month, -2, getdate())
order by t0.DocTotal desc";
$resultItemData = sqlsrv_query($con, $queryOrders);
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Seller</th>";
echo "<th>Vendor</th>";
echo "<th>Date</th>";
echo "<th>Total</th></tr>"
while($rowItemData = sqlsrv_fetch_array($resultItemData)){
echo "<tr><td>";
echo "$resultItemData";
echo "</td></tr>";
endwhile;
}
echo"</table>";
Modified a little bit. Check this:
while($rowItemData = sqlsrv_fetch_array($resultItemData)) :
echo "<tr><td>";
echo $rowItemData[ColumnValue]; //In your code, didn't access the column value earlier
echo "</td></tr>";
endwhile;
There's a combination of problems at play:
First, you open the while with {, but close with endwhile; - while technically not a problem, it's not consistent - if you open with {, it's best practice to close with }.
Second, you're attempting to echo an entire array, which won't work properly.
Third, no need to put the value inside of quotes: echo "$resultItemData"; could simply be echo $resultItemData.
Fourth, you're attempting to echo $resultItemData, which is a resource, not the row data. You want to echo $rowItemData values.
And finally, you'll likely want the results in an associative array, rather than a numerically-indexed array, so you might consider using sqlsrv_fetch_array( $resultItemData, SQLSRV_FETCH_ASSOC).
Below is your code, revised to work, and follow a bit better practices:
// columns: 'Seller',Vendor, 'Date', 'Total'
while( $rowItemData = sqlsrv_fetch_array( $resultItemData, SQLSRV_FETCH_ASSOC ) ) {
echo "<tr><td>";
echo "<td>$rowItemData['Seller']</td>";
echo "<td>$rowItemData['Vendor']</td>";
echo "<td>$rowItemData['Date']</td>";
echo "<td>$rowItemData['Total']</td>";
echo "</tr>";
}
You should specify the indexes of the array $rowitemdata.
For example:
echo"<tr><td>".$rowitemdata['Vendor']."
I haven't gone through your full code, but I can see wrong syntax for while
while($rowItemData = sqlsrv_fetch_array($resultItemData)){
echo "<tr>";
echo "<td>".$resultItemData['Seller']."</td>";
echo "<td>".$resultItemData['Vendor']."</td>";
echo "<td>".$resultItemData['Date']."</td>";
echo "<td>".$resultItemData['Total']."</td>";
echo "</tr>";
}
or
while($rowItemData = sqlsrv_fetch_array($resultItemData)) :
echo "<tr>";
echo "<td>".$resultItemData['Seller']."</td>";
echo "<td>".$resultItemData['Vendor']."</td>";
echo "<td>".$resultItemData['Date']."</td>";
echo "<td>".$resultItemData['Total']."</td>";
echo "</tr>";
endwhile;
Update:
still you can optimize the code, I just gave sample working
Let's assume your query actually produces a result, because you don't check that it does:
$resultItemData = sqlsrv_query($con, $queryOrders);
$header = <<<HEREDOC
<table border="1" align="center">
<tr>
<th>Seller</th>
<th>Vendor</th>
<th>Date</th>
<th>Total</th>
</tr>
HEREDOC;
echo $header;
while($rowItemData = sqlsrv_fetch_array($resultItemData)) {
echo "<tr>
<td>{$rowItemData['Seller']}</td>
<td>{$rowItemData['Vendor']}</td>
<td>{$rowItemData['Date']}</td>
<td>{$rowItemData['Total']}</td>
</tr>";
}
echo '</table>';
To actually check that the query works, you might want to do this instead. This is just to debug/illustrate error checking for the query execution. You wouldn't want to output an error to the screen, but rather log it. You probably want to just output the table header/footer and skip the while/loop entirely.
$resultItemData = sqlsrv_query($con, $queryOrders);
if (resultItemData === false) {
die(print_r(sqlsrv_errors(), true));
}
I have a table in database name Accounts in which i have many rows and many columns, i want to show a column Account (all values) in my html table. I have tried many method to show a specific column values without using index in html using php and I am using MySql.
$storeArray = Array();
while($rowval = mysql_fetch_array($whole, MYSQL_ASSOC))
{
$storeArray[] = $rowval['Account'];
$status= $rowval['status'];
$ph1= $rowval['Phone1'];
$ph2= $rowval['Phone2'];
}
by using <?php echo $storeArray[0]; ?> and <?php echo $storeArray[1]; ?> in <td> i got the solution. My question is there any way, it automatically show all values without providing any index?
$conn=new mysqli("localhost","root","","your_db");
$rows=$conn->query("select username from User");
echo "<table border='1'>";
echo "<tr><th>Username</th></tr>";
while(list($username)=$rows->fetch_row()){
echo "<tr><td>$username</td></tr>";
}
echo "</table>";
This is a pretty elaborate question. I think the best I can do is point you in the right direction. There is a good tutorial for this on w3schools.com. You should at least read these:
PHP - Connect to MySQL
PHP - Select Data From MySQL
and maybe
PHP - Limit Data Selections From MySQL
**file user.php**
<?php
$conn=new mysqli("localhost","root","","your_db");
$rows=$conn->query("select id,username from User");
echo "<table border='1'>";
echo "<tr><th>Username</th></tr>";
while(list($id,$username)=$rows->fetch_row()){
echo "<tr>";
echo "<td>";
echo "<form action='user_details.php' target='_blank' method='post'>";
echo "<input type='hidden' name='txtId' value='$id' />";
echo "$id - $username";
echo "<input type='submit' name='btnView' value='View' />";
echo "</form>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
**file user_details.php**
<?php
if(isset($_POST["btnView"])){
$id=$_POST["txtId"];
$conn=new mysqli("localhost","root","","your_db");
$row=$conn->query("select id,username,email,phone from User where id='$id'");
list($id,$username,$email,$phone)=$row->fetch_row();
echo $id," ",$username," ",$email," ",$phone;
}
?>
if you want to fetch more than one database column in your html table column.
$conn=new mysqli("localhost","root","","your_db");
$rows=$conn->query("select col1,col2 from Tablename");
echo "<table border='1'>";
echo "<tr><th>col1</th><th>col2</th></tr>";
while(list($col1, $col2)=$rows->fetch_row())
{
echo "<tr><td>$col1</td><td>$col2</tr>";
}
echo "</table>";
I am building a table on a wordpress site that displays data that is sorted from one table.
What I cannot get right is to change the title to a URL, that is changeable (slug) from the same db.
The basic url stays the same only the slug changes
ie wwww.thesite.com/job/view/ --- and then the slug.
Here is my code so far.
function dbTEST($atts, $content = null) {
// Get all the data from the "job board" table
$result = mysql_query("SELECT * FROM wpjb_job WHERE job_country='72' ORDER BY job_title")
or die(mysql_error());
echo "<table border='1'>";
echo "<tr> <th>Job</th> <th>Company</th> </tr>";
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table
echo "<tr><td>";
#---------- I need this job_title to url link to the job_slug
echo $row['job_title'];
echo $row['job_slug'];
echo "</td><td>";
echo $row['company_name'];
echo "</td></tr>";
}
echo "</table>";
}
Try this:
echo "".$row['job_title'].""