Sql query store in a variable and use the variable to add something using PHP

0 Nathan Moland · August 23, 2015
how to store a sql query to a variable to add 1 to its current value. I already have a code but it doesn't add 1 to the current value in the select query ['eCorrect'] instead the result will be 2 after submitting the form. And it show this error Object of class mysqli_result could not be converted to int. I have set my 'eCorrect' field to data type INT. I don't know where my error is please help thanks in advance.

html code here

<form method="post" action="elQ2.php">
<p>Question: sample question sample question sample question sample question</p>
<input type="radio" name="Ctwo" value="wrong">Choice A<br>
<input type="radio" name="Ctwo" value="wrong">Choice B<br>
<input type="radio" name="Ctwo" value="correct">Choice C<br>
<input type="radio" name="Ctwo" value="wrong">Choice D<br>
<input type="submit" name="submit" value="Submit" class="pull-right">
</form>
</div>

php code here


<?php
$correctResult = $db->query("SELECT eCorrect FROM elearn WHERE eID=1");
$wrongResult = $db->query("SELECT eWrong FROM elearn WHERE eID=1");

$addC = $correctResult;
$addW = $wrongResult;
if(isset($_POST['submit'])) {

if(!empty($_POST['Ctwo'])){
if($_POST['Ctwo']=="correct") {

$eAns = $_POST['Ctwo'];
$eAns= $addC + 1 ;
if($update = $db->query(" UPDATE elearn SET eCorrect = '".$eAns."' WHERE eID=1 ")) {
}else{
die($db->error);
}
echo "Correct Answer";

}else{
//Wrong answer
$eAns = $_POST['Ctwo'];
$eAns = $addW + 1 ;
if($update = $db->query(" UPDATE elearn SET eWrong = '".$eAns."' WHERE eID=1 ")) {
}else{
die($db->error);
}
echo "Wrong answer";
}
} else{
echo "You must choose an answer";
}
}
?>


Post a Reply

Replies

Oldest  Newest  Rating
0 jethro daniel · August 23, 2015
Okay, it's been long since I did php, as I recently switched to c#. But I think the problem is from the first two lines. While using the query method of mysqli to select data from the database, it returns an msqli_result object.so after the select query, you have to make a call to the mysqli_result object and select the first returned value + u can also cast it to int using (int) + you're variable so it would behave exactly like an integer. So I think!!
0 jethro daniel · August 23, 2015
something like this $finalValue = (int) $correctResult->fetch_row()[0]; and do thesame for the wrong result.
0 jethro daniel · August 23, 2015
something like this $finalValue = (int) $correctResult->fetch_row()[0]; and do thesame for the wrong result.
  • 1

PHP

107,238 followers
About

Server-side, HTML embedded scripting language used to create dynamic Web pages.

Links
Moderators