How to make a new field in an array? - php

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>";
}
?>

Related

Want to put same value in whole column in HTML-PHP table

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

Move to next colum if condition is true when create table with loop in Php

so, what i wanted to do is show the total clicks per Category id of the items only for 20 items order by the highest total clicks per day.
now i am using hard code and the result have to looks like this
so, if the item id and total clicks already fill up the
20columns (for item id and total clicks) + 2 for the tittle so means
22columns
it has to move to next row.
because i am reffering to my db, so i am using loop to create the table, and when i doing that way, i am getting this result....
the result will keep showing until the end in the left side. thats very hard to read for report purposes. so i wanted the result looks like the first figure that i've uploaded.
here is what i am doing now
include "Con.php";
//get the value from Get Method
$CatidValue = $_GET['CatIds'];
//(The date format would looks like yyyy-mm-dd)
$DateFrom = $_GET['DateFrom'];
$DateTo = $_GET['DateTo'];
//select the CatID
$SqlGet= "Select CatId from try where CatId = $CatidValue";
$_SqlGet = mysqli_query($connection,$SqlGet);
$TakeResultGet = mysqli_fetch_array($_SqlGet);
$CatIdTittle = $TakeResultGet ['CatId'];
echo"
For Category Id : $CatIdTittle
<br>
";
//For Loop purpose and break the value
$explodeValueFrom = explode("-",$DateFrom);
$explodeValueTo = explode("-",$DateTo);
$DateValueFrom = $explodeValueFrom[0].$explodeValueFrom[1].$explodeValueFrom[2];
$DateValueTo = $explodeValueTo[0].$explodeValueTo[1].$explodeValueTo[2];
//Loop through the date
for($Loop=$DateValueFrom; $Loop <= $DateValueTo; $Loop++){
$YearLoop= substr($Loop, 0,4);
$MonthLoop =substr($Loop, 4,2);
$DayLoop = substr($Loop, 6,2);
$DateTittleValue = $YearLoop."-".$MonthLoop."-".$DayLoop;
$trValue = "<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<table class='tg'>
<tr>
$trValue
</tr>
";
echo"
<table class='tg'>
<tr>
<td class='tg-yw4l'>Items Id</td>
<td class='tg-yw4l'>Total Clicks</td>
</tr>
";
//to get the item id and total clicks
$SqlSelect = "select `Item Id`,`Total Clicks`,Day from try where CatId = $CatidValue and Day = '$DateTittleValue' ORDER BY `try`.`Total Clicks` DESC limit 20";
$_SqlSelect = mysqli_query($connection,$SqlSelect);
foreach ($_SqlSelect as $ResultSelect) {
$Day = $ResultSelect['Day'];
$ItemId = $ResultSelect['Item Id'];
$TotalClicks = $ResultSelect['Total Clicks'];
echo"
<tr>
<td class='tg-yw4l'>$ItemId</td>
<td class='tg-yw4l'>$TotalClicks</td>
</tr>
";
}
}
?>
You dont need to declare your trValueTitle in the loop. Plus you need to concatenate it in your echo, try this :
$trValueTittle ="1"."<th class='tg-amwm' colspan='2'>$DateTittleValue</th>" ;
echo"<table class='tg'>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
echo"<tr>". $trValueTittle ."</tr>";
}
I don't know what you want to do with the "1", but I think this is what you want to do:
echo "<table class='tg'>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
$trValueTittle ="<th class='tg-amwm' colspan='2'>$DateTittleValue</th>";
echo"
<tr>
$trValueTittle
</tr>";
}
echo "</table>";
$trValueTittle ="1"."<th class='tg-amwm' colspan='2'>$DateTittleValue</th>" ;
echo"<table class='tg'>
<thead>
<tr>";
for($loopForTr=1; $loopForTr<=3; $loopForTr++){
echo $trValueTittle;
}
echo"</tr>
</thead>
</table>";
#Mantello, good answer, but i think it's better to keep out the "tr" from the loop, cause usually you don't want to place your tableheads (th) in different rows.
#Rax your Code won't work. You'll recive an error. You can't output a Variable the way you did in your echo.
echo"<tr> '.$trValueTittle.' </tr>";
would be fine. But there's also no need to define your variable inside the for loop. This way you slow up your script.

Table with database values and user input

So I've been wrestling with this issue on and off for quite a while now, and just like driving around lost in a strange city, I am finally breaking down for direction! I am developing table with values from a database, but also need a column that will process user input. I have been able to display the table but my input is not updating the necessary database element. Code below:
<?php
include("pogsatbetbuddy.inc.php");
$cxn=mysqli_connect($host,$username,$password,$db_name)
or die("Did Not Connect");
$query="SELECT * FROM $tbl2_name ORDER BY $tbl2_name.$col_name ASC";
$result=mysqli_query($cxn,$query)
or die("Query Not Working");
echo"<table border='1'
<form name='payments' action='' method='POST'>
<tr>
<td class='update' colspan='5'>
<button data-theme='b' id='submit' type='submit'>Update</button>
</td>
</tr>
<tr>
<th class='profile'>Last Name</th>
<th class='profile'>First Name</th>
<th class='profile'>Saturday Payment Owing</th>
<th class='profile'>Enter Payment</th>
<th class='profile'>Saturday Balance</th>
</tr>";
while ($row=mysqli_fetch_assoc($result))
{
extract ($row);
echo"<tr>
<td class='profile'>$lastname</td>
<td class='profile'>$firstname</td>
<td class='profile'>$owingsat</td>
<td class='profile'><input type='number' name='paidsat' value=''/></td>
<td class='profile'>$owingsat-$paidsat</td>
</tr>";
}
echo "</form>";
echo "</table>";
This displays the table in the way I want. Having worked through the results of the following code, it seems that I am returning a null value, so I am thinking I have an issue with either the form action or the submit Update button, but can not find the solution after much experimentation and searching. Balance of code below:
if(isset($_POST['paidsat']))
{
$paidsat = $_POST['paidsat'];
if(($paidsat) != null)
{
$stmt = $cxn->prepare("UPDATE $tbl2_name SET paidsat = ? WHERE firstname=? and lastname=?");
$stmt->bind_param('sss', $paidsat, $firstname, $lastname);
$status = $stmt->execute();
if($status === true) //To check if the execute was successful
{
echo("<p class='click'>You have successfully added the payment for $firstname $lastname\n<br /></p>");
}
}
else echo"Not Successful";
}
else echo "<p class='click'>Make your changes as required</p>";
mysqli_close($cxn);
Everything comes to a crashing halt at the second if statement.....or should I say, although things look pretty, they don't function! Thanks in advance, appreciate any help!
Be sure you have a proper value for $tbl2_name checking
var_dump($tbl2_name)
in your code before the update
and for debug try using a string concatenation like
"UPDATE " . $tbl2_name . " SET paidsat = ? WHERE firstname=? and lastname=?";
and try use
if( $paidsat != NULL )
and last check if you have proper value for update
paidsat = ? WHERE firstname=? and lastname=?
Try
var_dump( $paidsat);
var_dump( $firstname);
var_dump( $lastname);
and build a proper select for test if you value math the rows you think and
test this select in you db console

PHP echoing MySQL data into HTML table

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.

PHP + MySQL + HTML Displaying Different information onTable

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.

Categories