I have a query that I am going to display as a table. But I would like the integer value within my table to be displayed as something else within the table.
For example:
Thw query will display Product ID, and Product completion.
Production completion within my table is stored as either 1 or 0.
So in the table, I would have instead of a 1 or 0, a "yes" or "no" respectively.
How can I do this?
Simple I know, but I have been searching to no avail. I'm sure its because I don't know what the term is for what I'm looking to do.
I'm almost certain this has been asked before, but I cannot figure it out.
If you are just trying to display "Yes" or "No" then I would use a ternary operator.
<table>
<tr>
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
</tr>
<tr>
<td><?=$var == 1 ? 'Yes' : 'No'?></td>
<td>Col 2 data</td>
<td>Col 3 data</td>
</tr>
</table>
The ternary operator says, if $var==1 display Yes else display No.
There is alot of unknows with this question.
But assuming you have queried the database and have a value returned
and all you need to do is switch 0 and 1 to yes or no then you can just do an if statement and insert that into the table.
// assuming $value = 1
<td><?php if($value){echo "yes";}else{echo "No";}?></td>
or have it in whatever format you want
There are many good answers to choose from, that have been given.
This is one/another way of doing this:
$query = mysqli_query($conn,"SELECT * FROM your_table");
while($row = mysqli_fetch_array($query)) {
$column = $row['ID'];
if ($column == "1") {
$column = "Yes";
echo $column;
}
else{
$column = "No";
echo $column;
}
}
Getting a result into a variable, and using it with an IF statememt is a solution.
A boolean variable can be hardcoded all right.
If the boolean is TRUE you echo a Yes or else a NO.
This may help you out a little, depending on how far you are. This assumes you are using mysqli and that your connection string has a variable of $con (adjust as needed)
<?php
$sql="select product_id, product_completion from tbl";
$sql_result = mysqli_query($con,$sql);
?>
<table>
<tr>
<th>Product ID</th>
<th>Completed</th>
</tr>
<?php $z=0; while ($row = mysqli_fetch_array($sql_result)) { ?>
<tr>
<td><?php echo $row['product_id']; ?></td>
<td><?php if ($row['product_completion'] == 1) echo 'yes'; else echo 'no'; ?></td>
</tr>
<?php $z++; } ?>
</table>
Also change your query to your actual query and the column names to your actual column names, and "tbl" to you actual table name, etc.
Related
I really can't figure out what I'm doing wrong here. I'm doing a query to check whether there are records in a DB table called 'newCards'.
With $count I check how many results it's returning: it shows me '1'. But the while loop isn't returning ANY thing. The only things I'm seeing are the <th>'s at the top of the table, but no table records are present, while $count is giving '1' as a result. Which is true, cause there is actually 1 record present in DB.
How can I fix this?
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if(empty($query->fetch())){
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
$query->fetch() already fetches a record. So next call to fetch() fetches next record or nothing if there're no records. In your case with one record second fetch() fetches nothing, so while never starts.
You can change your code to:
if($count){?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
// show row
}?>
</table>
} else {
// echo that no rows found
}
I think fetch in first if is executed so that is why second returns empty,
try to assign it to var before conditions or check wit $cont var
I believe you want to return an array indexed by column names with
->fetch(PDO::FETCH_ASSOC)
More information can be found here http://php.net/manual/en/pdostatement.fetch.php
Because fetch() fetches the first row, even when checking in empty(), it will try to fetch the next row when you use while($result = $query->fetch()){. You can either check the value from $count (like shown by u_mulder), but you should beware of the note in the manual for rowCount() (emphasis mine)
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behavior is not guaranteed for all databases and should not be relied on for portable applications.
You can use a do..while structure and check if the fetch was successful or not instead. If you change out if(empty($query->fetch())){ with if (!$row = $query->fetch()) {, you check if there was a row fetched or not (as fetch() returns null on an empty result). Then $row is ready to use, and you can use it before the first loop takes place.
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if (!$row = $query->fetch()) {
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
do {
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
} while ($result = $query->fetch());
?>
</table>
<?php
}
PHP.net on PDOStatement::rowCount()
PHP.net on do..while
I want to put same value in one column in whole table.
The table looks like this
Table Image
For suppose, I want to put status as Community owner for all Lvl7's.
Here's the table code,
<table class="table" id="myTable">
<thead>
<tr class="header">
<th width="60%"></th>
<th width="20%"></th>
<th width="20%"></th>
</tr>
</thead>
<?php
$query = $config->prepare("SELECT playerName, playerLevel FROM `playerdata` WHERE playerLevel = 7 ORDER BY playerName DESC");
$query->execute();
while($data = $query->fetch())
{
echo "<tr><td>".$data['playerName']."</td>";
echo "<td>".$data['playerLevel']."</td></tr>";
}
?>
</table>
How do I put the value as community owner for this table.
I have same tables like these for all levels.
I dont know how to echo the third column using and or print the same value for all rows in Status column.
When I tried to code, it only printed the value Community Owner to the last row of table.
P.S:- I am rookie in all this stuff, any type of help is appreciated.
while($data = $query->fetch())
{
echo "<tr><td>".$data['playerName']."</td>";
echo "<td>".$data['playerLevel']."</td>";
switch ($data['playerLevel'])
{
case 7:
echo "<td>Community owner</td></tr>";
break;
default:
echo "<td>Not defined</td></tr>";
break;
}
}
//Changed data['playerLevel'] to $data['playerLevel'] from the original post in switch statement, it worked :D
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
}
?>
So I'm trying to make a HTML table that gets data from a MySQL database and outputs it to the user. I'm doing so with PHP, which I'm extremely new to, so please excuse my messy code!
The code that I'm using is: braces for storm of "your code is awful!"
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysql_connect("localhost", "notarealuser", 'notmypassword');
for ($i = 1; $i <= 20; $i++) {
$items = ($mysqli->query("SELECT id FROM `items` WHERE id = $i"));
echo ("<tr>");
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['id'];
}</td>");
$items = ($mysqli->query("SELECT name FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['name'];
}</td>");
$items = ($mysqli->query("SELECT descrip FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['descrip'];
}</td>");
$items = ($mysqli->query("SELECT reward FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['reward'];
}</td>");
$items = ($mysqli->query("SELECT img FROM `items` WHERE id = $i"));
echo ("
<td>
while ($db_field = mysqli_fetch_assoc($items)) {
print $db_field['img'];
}</td>");
echo ("</tr>");
}
?>
</tbody>
</table>
However, this code is not working - it simply causes the page to output an immediate 500 Internal Server Error. IIS logs show it as a 500:0 - generic ISE. Any ideas?
You are mixing mysql and mysqli, not closing php code block and you are not selecting a database. Plus you don't have to run a query for each field
Try this:
<table class="table table-striped table-hover ">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = new mysqli("host","user", "password", "database");
$execItems = $con->query("SELECT id, name, descrip, reward, img FROM `items` WHERE id BETWEEN 1 AND 20 ");
while($infoItems = $execItems->fetch_array()){
echo "
<tr>
<td>".$infoItems['id']."</td>
<td>".$infoItems['name']."</td>
<td>".$infoItems['descrip']."</td>
<td>".$infoItems['reward']."</td>
<td>".$infoItems['img']."</td>
</tr>
";
}
?>
</tbody>
</table>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Description</th>
<th>Reward</th>
<th>Column heading</th>
</tr>
</thead>
<tbody>
<?php
$con = mysqli_connect("hostname","username",'password');
$sql= "SELECT * FROM `items` WHERE id <20 ";
$items = (mysqli_query($sql));
while ( $db_field = mysqli_fetch_assoc($items) ) {?>
<tr><td><?php echo $db_field['id'];?></td></tr>
<tr><td><?php echo $db_field['name'];?></td></tr>
<tr><td><?php echo $db_field['descrip'];?></td></tr>
<tr><td><?php echo $db_field['reward'];?></td></tr>
<tr><td><?php echo $db_field['img'];?></td></tr>
<?php}
</tbody>
</table>
Try these, not tested
Where is the question?
There's many problems with this code.
First, you are confused between PHP and HTML.
Code between is PHP. It's executed on the server, you can have loops and variables and assignments there. And if you want some HTML there you use "echo".
Code outside is HTML - it's sent to the browser as is.
Second - what you seem to be doing is querying each field separately. This is not how you work with SQL.
Here's more or less what you need to do:
//Query all rows from 1 to 20:
$items = $mysqli->query("SELECT id,name,descrip,reward,img FROM `items` WHERE id between 1 and 20");
//Go through rows
while ( $row = mysqli_fetch_assoc($items) )
{
echo "<tr><td>{$db_field['id']}</td>";
//echo the rest of the fields the same way
});
I'm going to go ahead and assume that the code isn't working and that's because there's several basic errors. I'd strongly suggest doing some hard reading around the topic of PHP, especially since you're using databases, which, if accessed with insecure code can pose major security risks.
Firstly, you've set-up your connection using the procedural mysql_connect function but then just a few lines down you've switched to object-orientation by trying to call the method mysqli::query on a non object as it was never instantiated during your connection.
http://php.net/manual/en/mysqli.construct.php
Secondly, PHP echo() doesn't require the parentheses. PHP sometimes describes it as a function but it's a language construct and the parentheses will cause problems if you try to parse multiple parameters.
http://php.net/manual/en/function.echo.php
Thirdly, you can't simply switch from HTML and PHP and vice-versa with informing the server/browser. If you wish to do this, you need to either concatenate...
echo "<td>".while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}."</td>;
Or preferably (in my opinion it looks cleaner)
<td>
<?php
while($db_filed = mysqli_fetch_assoc($item)) {
print $db_field['id'];
}
?>
</td>
However, those examples are based on your code which is outputting each ID into the same cell which I don't think is your goal so you should be inserting the cells into the loop as well so that each ID belongs to its own cell. Furthermore, I'd recommend using echo over print (it's faster).
Something else that may not be a problem now but could evolve into one is that you've used a constant for you FOR loop. If you need to ever pull more than 20 rows from your table then you will have to manually increase this figure and if you're table has less than 20 rows you will receive an error because the loop will be trying to access table rows that don't exist.
I'm no PHP expert so some of my terminology might be incorrect but hopefully what knowledge I do have will be of use. Again, I'd strongly recommend getting a good knowledge of the language before using it.
Sorry I have had to submit this question again because I have had hardly any views as it is an old post. I am desperate though for this to be answered. Please help me.
I have an array which will fetch rows from the database. But what I want to do is to create a new empty row in the table where if $row['StudentAnswer'] equals $row['AnswerContent'] then new field (lets say its called $row['StudentAnswerWeight']) = $row['Weight%'] else $row['StudentAnswerWeight'] = '0'.
For example: $row['Answercontent'] = Leeds (This is the correct answer for the question.) $row['StudentAnswer'] = Leeds (This is what the student has put for the answer.) The $row['weight%'] is the percentage of the mark for the correct answer. Lets say that the answer for the above example = 5% of the total marks. Now as the above example shows that the student's answer has matched the correct answer it means that in the new field which I want to create (lets call it ($row['StudentAnswerWeight']) to display the wieght% percentage of the answer which is 5%. If the studnet got the answer wrong by lets say the Student put in his/her answer 'Manchester'. The studentanswerweight should = 0% as that the answer is wrong. I hope you now understand what I want to acheive.
Can't we make a new $row['...']($row['StudentAnswerWeight' is what the new $row['...'] will be called) and use an if statement. If $row['AnswerContent'] = $row['StudentAnswer'] then $row['...'] = $row['Weight%'] else $row['...'] = '0'. I was thinking along those lines but I could not get it to work, I hope you guys can figure it out :)
Below is the array and the fields in the table in php code:
<table border='1'>
<tr>
<th>Session ID</th>
<th>Question Number</th>
<th>Question</th>
<th>Correct Answer</th>
<th>StudentAnswer</th>
<th>Correct Answer Weight</th>
<th>Student Answer Weight</th>
<th>Student ID</th>
</tr>
<?php
while ($row = mysql_fetch_array($result)) {
echo "
<tr>
<td>{$row['SessionId']}</td>
<td>{$row['QuestionNo']}</td>
<td>{$row['QuestionContent']}</td>
<td>{$row['AnswerContent']}</td>
<td>{$row['StudentAnswer']} </td>
<td>{$row['Weight%']}</td>
<td>{$row['StudentAnswer'] = $row['AnswerContent']}</td>
<td>{$row['StudentId']}</td>
</tr>";
}
?>
Thank You
Add this before echo:
if ( $row['StudentAnswer'] == $row['AnswerContent'] ) {
$row['StudentAnswerWeight'] = $row['Weight%'];
} else {
$row['StudentAnswerWeight'] = '0';
}
And get rid of this {$row['StudentAnswer'] = $row['AnswerContent']}.
Try this: echo ($row['StudentAnswer']==$row['AnswerContent']) ? $row['Weight%'] : '0'
in your example:
<?php
while ($row = mysql_fetch_array($result)) {
echo "
<tr>
<td>{$row['SessionId']}</td>
<td>{$row['QuestionNo']}</td>
<td>{$row['QuestionContent']}</td>
<td>{$row['AnswerContent']}</td>
<td>{$row['StudentAnswer']} </td>
<td>{$row['Weight%']}</td>
<td>";
echo ($row['StudentAnswer']==$row['AnswerContent']) ? $row['Weight%'] : '0';
echo "</td><td>{$row['StudentId']}</td>
</tr>";
}
?>