Sum values from rows in PHP - php

I'm trying to add values from row['scores'].
For example, if I have 6 rows that have a value of 1 for each row .. I want to be able to echo -> value of rows = 6.
The += is not working for me: I still get only the values themselves, e.g. 1,2,3,4,5,6,7 but I want the sum of it, let's say 1+2+3+4+5+6+7=28.
Thanks
<?php include("connect.php"); ?>
<html>
<head>
<title>Score Predictions</title>
</head>
<body>
<div id = "id">
<?php
$query = "SELECT * FROM test";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
}
?>
<?php
if (isset($_POST['submit'])) {
$x = $_POST["test"];
mysql_query("INSERT INTO test (home, away, score) VALUES ('$home', '$away', '$x')");
}
?>
<?php echo $home," - ",$away; ?>
<form method = 'post' action = 'http://albsocial.us/test/index.php'>
<select name = 'test'>
<option value = "" selected = 'selected'></option>
<option VALUE = '1'>1</option>
<option VALUE = 'X'>X</option>
<option VALUE = '2'>2</option>
</select>
<INPUT TYPE = 'submit' name = 'submit' />
</form>
<?php
$query = "SELECT * FROM test";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$score = $row['score'];
if ($score == "1") {
echo $sum += $score - 1;
}
}
?>
</div>
</body>
</html>

$sum=0;
while($row=mysql_fetch_array($result)){
$id = $row['id'];
$score = $row['score'];
if ($score == "1"){
$sum = $sum+$score;
}
}
echo $sum;
try this.
it sume al $score values.

You have to remove the if condition and add the database value to $sum variable
$sum = 0;
while($row=mysql_fetch_array($result)){
$id = $row['id'];
$score = $row['score'];
$sum += (int)$score;
}
echo $sum;

Several problems here, as other answers mostly fix, but to make clear:
your if $score == 1 doesn't seem relevant to your purpose. Did you mean if $id == 1, or were you just trying to ignore zeros? (anything + zero stays the same anyway, so you don't need to)
there doesn't seem to be a reason for subtracting one in $sum += $score-1 either
you need to finish the adding up first, and then call echo once. Currently, you have an echo for every database row, which is why you're seeing multiple numbers output.
if you're only displaying the sum anyway, you don't need to do this in a loop at all, just get the DB to add up for you, e.g. SELECT SUM(score) AS total_score FROM test or SELECT id, SUM(score) AS total_score FROM test GROUP BY id

Related

Array ( ['1'] => 1 ) 1 Notice: Undefined offset: 1 in C:\xampp\htdocs\HR\functions\functions_applicants.php on line 152 2

The code below is to display the quiz(questions and answers)
When submitting, I am getting error:
"Array ( ['1'] => 1 ) 1
Notice: Undefined offset: 1 in C:\xampp\htdocs\HR\functions\functions_applicants.php on line 152
2".
<form method="post" action="index.php?results">
<?php
for($i=1; $i<27; $i++) {
$query = query("SELECT * FROM assess_questions WHERE question_id =$i");
confirm($query);
while($row = fetch_array($query)) {
?>
<div>
<h4><?php echo $row['question']; ?></h4>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=1><?php echo $row['A']; ?><br>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=2><?php echo $row['B']; ?><br>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=3><?php echo $row['C']; ?><br>
<input type="radio" name="quizcheck['<?php echo $row['question_id']; ?>']"
value=4><?php echo $row['D']; ?><hr>
</div>
<?php
}
}
?>
<input class="btn btn-info" type="submit" name="submit_answers"
value="Next">
</form>
THIS IS THE FUNCTION TO CHECK FOR THE ANSWER. THIS IS WHERE IM GETTING THE ERROR FROM. ITS THE $i that's causing the error.
if(isset($_POST['submit_answers'])) {
$result = 0;
$i = 1;
$average = 0;
$item = ($_POST['quizcheck']);
print_r($item) ;
$query = query("SELECT * FROM assess_questions");
confirm($query);
while($row = fetch_array($query)) {
print_r($row['answer_id']);
$checked = ($row['answer_id']) == $item[$i];
if($checked) {
$result++;
}
$i++;
}
}
The clue is in the contents of $item which you have done a print_r on and got the result:
Array(['1'] => 1)
You're getting this result because in your html your radio buttons are labelled quizcheck['n'] where n is the question id. So presumably in this case you have pressed the first radio button in the first question. You should change the line which gives the radio buttons a name to
<input type="radio" name="quizcheck[<?php echo $row['question_id']; ?>]" value=1><?php echo $row['A']; ?><br>
(i.e. remove the single quotes around <?php echo $row['question_id']; ?>). This will make $item look like:
Array ( [1] => 1 )
so the test
($row['answer_id']) == $item[$i];
will work. Note the parentheses around $row['answer_id'] are unnecessary.
The other issue you are going to run into is that your form obviously doesn't require the user to submit an answer to every question. This means that in your while loop you need to check whether the user has submitted an answer to be checked against the result. If you are not going to make it compulsory to answer all questions, you will need to put an array_key_exists check around the result checking code:
if (array_key_exists($i, $item)) {
$checked = $row['answer_id'] == $item[$i];
if ($checked) {
$result++;
}
}
you begin with $i = 1;
in which case you'll avoid $item[0]; (first position) and it will mismatch $checked = ($row['answer_id']).
start with $i=0; as if there's only one answer $i[1] will not exists but $i[0];
****EDIT****
first check your query result for not being void:
example, having this db connection function/method:
<?php
function connection(){
try{
//host, user, passwd, DB name)
$mysqli = new mysqli($host, $user, $passwd, $dbName);
return $mysqli;
}catch (Exception $mysqlin){
echo "Error establishing connection with ddbb ".$mysqlin->getMessage();
}
}
?>
And modifying your code:
if(isset($_POST['submit_answers'])) {
$result = 0;
//indexes must start at 0 unless you ensure that you don't need 0 value and your algorithm will not keep trying to get a value out of bounds / array offset
$i = 0;
$average = 0;
//i assume that $_POST['quizcheck'] is an array, otherwise the $item[$i] will be an out of bounds, which match with your issue (array offset). But i ensured some parts of your structure below for you to learn:
$item = ($_POST['quizcheck']);
print_r($item) ;
//you'll must prepare this statement after, for security
$sql = query("SELECT * FROM assess_questions");
//we get the result of this query on $result, if possible
if($result = connection()->query($sql)){
//we get the first row inside $rs (usually called Record Set) as associative (it means that you'll call the values as the column name on DB unless you use AS "Alias" on your query.
$rs = mysqli_fetch_assoc($result);
//if the record set is not void:
while($rs!="") {
//assuming that your DB col is called answer_id
print_r($rs['answer_id']);
//checked will get the value of matching those two arrays, so make sure you control nullables:
if($checked = ($rs['answer_id']) == $item[$i]){
//only if $checked value could be set
if($checked) {
$result++;
}
}
$i++;
}
//repeat this to get the next value, when it has no more values it will be void so it will escape from while loop.
$rs = mysqli_fetch_assoc($result);
}
}
Never assume that you'll get always a value.
Never assume that users will put numbers in some input only because you told them to do it.
Never use dates without checking.
Never state an algorithm with not-controlled vars/function outputs.
Control all data all over across your code and comment it, it will help you to avoid issues and modify your code months after you coded it.
Hope it helps you.
I recommend you to get a hosting to test/code in a controlled environment.

Quiz app score resetting

Hi here my processing file for my quizzer application. My code is realizing the answer to every question, however everytime I click the right answer and it sets the score to one. It goes to the next question, and then its resetting the session score to 0, and then adding one. The result is if I have a score of 3, I actually get a score of one. Where do i put the score variable so it doesent keep resetting everytime i process? If i echo $_SESSION['score']; at the end, I always get 0 or 1.
$_SESSION['score'] = 0;
if (isset($_POST['submit']))
{
$number = $_POST['number'];
$selected_choice = $_POST['choice'];
$next = $number + 1;
// get total questions
$query = "SELECT * FROM questions";
// get result
$results = mysqli_query($connection,$query);
$total = mysqli_num_rows($results);
// query to get right answer
$query = "SELECT * FROM choices WHERE question_number = $number AND is_correct = 1";
$result = mysqli_query($connection,$query);
$row = mysqli_fetch_assoc($result);
// set correct choice
$correct_choice = $row['id'];
// Compare
if($correct_choice == $selected_choice)
{
// answer is correct
$_SESSION['score']++;
}
// check is last question
if($number == $total)
{
header("Location:final.php");
exit();
} else
{
header("Location:question.php?n=$next");
}
}
which processes the question.php
<ul class = "choices">
<?php
while($row = mysqli_fetch_assoc($choices)): ?>
<li><input name = "choice" type = "radio" value = "<?php echo $row['id']; ?>" /> <?php echo $row['text']; ?></li>
<?php endwhile ?>
</ul>
<input type = "submit" name = "submit" value = "submit">
<input type = "hidden" name = "number" value = "<?php echo $number ?>" >
</form>
You are just saying yourself, that you reset the score to 0 on a new page load.
$_SESSION['score'] = 0;
And then you either do nothing to it or add 1 - so how could that score be anything different than 0 or 1? Stop resetting the score.
You're setting the value to 0 every time you load the page:
$_SESSION['score'] = 0;
Instead, check if the value exists before setting it. Perhaps something as simple as:
if (!isset($_SESSION['score'])) {
$_SESSION['score'] = 0;
}
That way whenever the page loads it will set the value only if it hasn't already been set.

php: get option select value by mysql

I'm trying to have an altas.php file for various html forms. This code is a html form with some mysql columns:
<div><label for="categoria">Categoría principal</label><select type="text" name="categoria">
<?php
$query = "select id, categoria from categorias";
$result = mysqli_query($mysql,$query);
if(!$result) echo 'Muy mal....';
$num_filas = mysqli_num_rows($result);
for ($i = 0; $i < $num_filas; $i++){
$row = mysqli_fetch_array($result);
?>
<option value "<?php echo $row['id']?>"><?php echo $row['categoria']?></option><?php
}
?>
</select></div>
On the other hand, if I make this:
foreach($_POST as $campo => $valor){
echo $campo ." = ". $valor ."\n";
}
I have no data in $row['categoria']. It should return the value, which is the categorias's id.
Another question:
How can I use the "foreach" whith an insert sentence?
For example:
foreach($_POST as $campo => $valor){
$query ="INSERT INTO $tabla ($campo) VALUES ('$valor')";
}
$tabla is sent via $_GET. This code make a new row for each $campo. Any idea?
I have try some suggestions, but nothing works.
You seem to be missing an = and closing semi-colons on this line:
<option value "<?php echo $row['id']?>"><?php echo $row['categoria']?></option><?php
Should be:
<option value="<?php echo $row['id']; ?>"><?php echo $row['categoria']; ?></option><?php
EDIT:
Also removed type from select list

for loop deducting a value from combobox

I have a dynamic combobox that displays Seat Numbers. I have a for loop that deducts a selected value from the combobox.
function display_seatNo() {
$query = "SELECT * FROM table1 WHERE ID = 1";
$result = mysql_query($query) or die("Failed to fetch records");
$rows = mysql_fetch_array($result);
$seatNo = $rows['SeatNo'];
$totalSeat = $rows['TotalSeats'];
$seatReserved = $rows['SeatsReserved'];
$remain = $totalSeat - $seatReserved;
$length = count($remain);
for($i=1; $i<=$remain-1; $i++){
echo "<option value=\"$i\" ";
echo " $i";
echo "> $i </option>";
}
}
<select name="cbSeatNo" id="cbSeatNo" class="cb1">
<?php display_seatNo(); ?>
</select>
Problem is that the selected value is not eliminating. Example:- Once Seat Number 1 is reserved, it shouldn't display in the combobox.
You loop through all numbers from 1 to $remain-1. That is a logic error. Example:
You have 10 seats. Seat 3 is taken. You loop through 1 to (10-1 = 9). Seat 3 will show in the list.
Instead you need to fetch the actually available (or taken) seats from your database, not just a count.
Instead of looping through the result set.
Better change your query to something like this
Select * from table1 where seatsReserved = false ;
For each reservation, set the seatsReserved value to false.
Search $seatReserved for $i then skip it.
$seatReserved = empty($seatReserved) ? array() : $seatReserved;
for($i=1; $i<=$remain-1; $i++){
if((array_search( $i, $seatReserved)) !== false) {
continue;
}
echo "<option value=\"$i\" ";
echo " $i";
echo "> $i </option>";
}
Edit: just in case 0 seats are reserved I gave $seatReserved a default value of array().

Display checked checkbox record from database

I have looked through similar problems and solution but somehow only half way help me with my problem. I'm trying to make a form to checked more than one record from MySQL database and display the checked record to another page. Somehow I managed to do the page with check boxes but I don't know how to display the record checked. It can only display the first row of the record or all the records regardless which box are checked.
This is checkbox page
$columns = count($fieldarray);
//run the query
$result = mysql_query(
"SELECT * FROM request_item
ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error());
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
{
$rows[] = $row['IllNo'];
}
foreach($rows as $value);
echo "";
echo " ";
echo $row['IllNo'];
echo "";
}
echo "";
?>
This is display record checked
$columns = count($fieldarray);
//run the query
$result = mysql_query(
"SELECT * FROM request_item
ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error());
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result))
{
$rows[]=$row['IllNo'];
foreach($rows as $value);
if ($rows= 'checked') {
echo "";
echo $value;
}
Any help are welcome. Thank you.
There's actually a lot of problems with that script including syntax errors, calling the wrong variable name, form not opening where it should, invoking PHP after you already have, etc...
To get a good answer to you, you should share what make $row['IllNo'] should equal to indicate if it should be checked or not.
I reformatted it a bit and this may give you a good start.
<form NAME ="form1" METHOD ="POST" ACTION ="dari.php">
<table>
<?php
$columns = count($fieldarray);
//run the query
$result = mysql_query("SELECT * FROM request_item ORDER BY request_item.IllNo DESC LIMIT 0, 6") or die(mysql_error()) ;
$row = mysql_num_rows($result);
while($row=mysql_fetch_array($result)) {
echo "<tr><td>";
echo "<Input type = 'Checkbox' Name ='ch1' value ='ch1'";
// check checked if it is. this will be checked if $row['IllNo'] has a value
// if there were a condition to make it checked, you would put the condition
// before the ?
echo $row['IllNo'] ? ' checked' : '';
echo ' />';
echo $row['IllNo'];
echo "</td></tr>";
}
?>
</table>
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Choose your books">
</FORM>

Categories