PHP if else statement not executing code when value is true - php

This is for a quiz application.
This is my comparison where $number is the question number and will increase every time the user submits an answer and we will assume $totalquestions = 3 for now as the category has only 3 questions.
I've echoed both values to make sure they are what I expect them to be and done var_dump($number == $totalQuestions); which returns true when $number = 3 but does not execute my code to redirect to the finish page once all questions are done and I have no clue why.
Any help would be great as I've been staring at this problem for hours!
<?php include('server.php'); ?>
<?php
if(!isset($_SESSION['geoScore'])){
$_SESSION['geoScore'] = 0;
}
//Get quiz category
$activeCategoryID = (int) $_GET['c'];
$query = "SELECT * FROM `category` WHERE CategoryID = $activeCategoryID";
$result = mysqli_query($db, $query);
$categoryName = mysqli_fetch_assoc($result);
echo $categoryName['CategoryName'];
//Get question number
$number = (int) $_GET['n'];
$query = "SELECT * FROM `questions` WHERE QuestionID = $number AND CategoryID = $activeCategoryID";
$result = mysqli_query($db, $query);
$question = mysqli_fetch_assoc($result);
//Get choices for question
$query = "SELECT * FROM `answers` WHERE QuestionID = $number";
$choices = mysqli_query($db, $query);
//Get total questions for category
$query = "SELECT * FROM `questions` WHERE CategoryID = $activeCategoryID";
$result = mysqli_query($db, $query);
$totalQuestions = mysqli_num_rows($result);
echo $totalQuestions;
echo $number;
var_dump($number == $totalQuestions); // returns true because values are equal
$result = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($result);
$correctChoice = $row['AnswerID'];
echo $correctChoice;
if($_SERVER["REQUEST_METHOD"] == "POST"){
$number = $_POST['number'];
$selectedChoice = $_POST['choice'];
$next = $number+1;
$activeCategory = $_POST['activeCategoryID'];
$query = "SELECT * FROM `questions` WHERE CategoryID = activeCategoryID";
$result = mysqli_query($db, $query);
$totalQuestions = mysqli_num_rows($result);
//Get correct choice
$query = "SELECT * FROM `answers` WHERE QuestionID = $number AND Correct = 1";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($result);
$correctChoice = $row['AnswerID'];
if($correctChoice == $selectedChoice){
$_SESSION['geoScore']++;
}
//Check to see if questions have finished
if($number == $totalQuestions){
header("Location: finish.php");
}else{
header("Location: geoQuiz.php?n=".$next."&c=".$activeCategory);
}
}
?>
EDIT: Previous working version that did not dynamically get the quiz category
<?php
if(!isset($_SESSION['geoScore'])){
$_SESSION['geoScore'] = 0;
}
//Get question number
$number = (int) $_GET['n'];
$query = "SELECT * FROM `questions` WHERE QuestionID = $number AND CategoryID = 1";
$result = mysqli_query($db, $query);
$question = mysqli_fetch_assoc($result);
//Get choices for question
$query = "SELECT * FROM `answers` WHERE QuestionID = $number";
$choices = mysqli_query($db, $query);
//Get total questions for category
$query = "SELECT * FROM `questions` WHERE CategoryID = 1";
$result = mysqli_query($db, $query);
$totalQuestions = mysqli_num_rows($result);
if($_SERVER["REQUEST_METHOD"] == "POST"){
$number = $_POST['number'];
$selectedChoice = $_POST['choice'];
$next = $number+1;
$_SESSION['activeCategory'] = "Geography";
$query = "SELECT * FROM `questions` WHERE CategoryID = 1";
$result = mysqli_query($db, $query);
$totalQuestions = mysqli_num_rows($result);
//Get correct choice
$query = "SELECT * FROM `answers` WHERE QuestionID = $number AND Correct = 1";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($result);
$correctChoice = $row['AnswerID'];
echo $correctChoice;
echo $selectedChoice;
if($correctChoice == $selectedChoice){
$_SESSION['geoScore']++;
}
echo $geoScore;
//Check to see if questions have finished
if($number == $totalQuestions){
header("Location: finish.php");
}else{
header("Location: geoQuiz.php?n=".$next);
}
}
?>
The above code was my previous version which worked but I would needed to have had multiple php pages for each quiz category so I tried to change this to take the category using $_GET[] in the link from index page and it seems to all work apart from when the questions are finished and to head to finish.php

Related

prevent insert same id if the user/student not put timeout

i have two button on my homepage one is time-in and the other is time-out,
i want to prevent the user/student to time-in using same id if he did not put time-out on his last time-in to create valid entry. Hope you can help me.
here is my php code:
<?php
include_once('connection.php');
if(isset($_POST['submit0'])){
$rfid = $_POST['rfid'];
$time=date("H:i:s");
$sql = mysqli_query($conn, "SELECT * FROM stud WHERE rfid_num = '$rfid'");
$count = mysqli_num_rows($sql);
if ($count == 0 ) {
header("location:notexist.php");
} elseif (empty($row['timeout'])) {
header("location:page say the user/student need to put timeout first before time-in again");
} else {
while( $row = mysqli_fetch_array($sql)) {
$rfid=$row['rfid_num'];
$id=$row['id'];
$name0 = $row['name'];
$course0 = $row['course'];
$image = $row['image'];
$InsertSql = "INSERT INTO student_att(rfid_num,id,name,course,image,timein) VALUES ('$rfid','$id','$name0','$course0','$image','$time')";
$res = mysqli_query($conn, $InsertSql);
}
}
}
?>
this is my answer just wanna share it, i just add select student_att table
to fetch the data and check if timeout column is empty.
<?php
include_once('connection.php');
if(isset($_POST['submit0'])){
$rfid = $_POST['rfid'];
$time=date("H:i:s");
$sql = mysqli_query($conn,"select * from stud where rfid_num ='$rfid' ");
$count = mysqli_num_rows($sql);
if ($count == 0) {
header("location:notexist.php");
}else{
while( $row = mysqli_fetch_array($sql)) {
$rfid=$row['rfid_num'];
$id=$row['id'];
$name0 = $row['name'];
$course0 = $row['course'];
$image = $row['image'];
$sql1 = mysqli_query($conn,"select * from student_att where rfid_num ='$rfid' order by number DESC limit 1 ");
while( $row = mysqli_fetch_array($sql1)) {
if(empty($row['timeout'])){
header("location:logout.php");
}else{
$InsertSql = "INSERT INTO student_att(rfid_num,id,name,course,image,timein) VALUES ('$rfid','$id','$name0','$course0','$image','$time')";
$res = mysqli_query($conn, $InsertSql);
}
}
}
}
}
?>

How to draw an image into QR code with PHP

In my project I am trying to generate a QR code with an image in it based on stored blobs (1 Qr code + 1 logo) in my SQL table.
I have thw following code but can't seem to store the new image into my table.
Any help is appreciated.
<?php
//for connection
$sName = "localhost";
$sUser = "Username";
$sPass = "Password";
$sDb = "Database";
$Conn = new mysqli ($sName, $sUser, $sPass, $sDb);
//variables i pass from another app
$Email = mysqli_real_escape_string($Conn, $_POST["PassEmail"]);
$qContent = addslashes(file_get_contents($_FILES["file"]["tmp_name"]));
$qOverlay = addslashes (file_get_contents($_FILES["overlay"]["tmp_name"]));
$Sql = "SELECT * FROM `userprofile_login` INNER JOIN `userprofile_personalprofile` ON userprofile_login.userid = userprofile_personalprofile.userid WHERE userprofile_login.email = '".$Email."' ";
$Result = mysqli_query($Conn, $Sql);
if (mysqli_num_rows ($Result) > 0) {
$Row = mysqli_fetch_assoc ($Result);
$qCheckSql = "SELECT `userid` FROM `userprofile_qr` WHERE userid = '".$Row['userid']."' ";
$qCheckResult = mysqli_query($Conn, $qCheckSql);
$Row2 = mysqli_fetch_assoc($qCheckResult);
if (mysqli_num_rows ($qCheckResult) < 1) {
//if there 0 result from previous query, insert new data
$InsertSql = "INSERT INTO `userprofile_qr` (`userid`, `qrcode`, `overlay`)
VALUES ('".$Row['userid']."', '$qContent', '$qOverlay')";
$InsertResult = mysqli_query($Conn, $InsertSql);
} else {
//is there ia a result from the previous query, update data
$UpdateSql = "UPDATE `userprofile_qr` SET
`qrcode` = '$qContent',
`overlay` = '$qOverlay'
WHERE userid = '".$Row2['userid']."' ";
$UpdateResult = mysqli_query($Conn, $UpdateSql);
}
The first part works, the problem is the bottom part where I want to combine the QR code and the logo:
$qSql = "SELECT `qrcode`, `overlay` FROM `userprofile_qr` WHERE userid = '".$Row2['userid']."' ";
$qSelect = mysqli_query($Conn, $qSql);
include 'phpqrcode/qrlib.php';
$qRow = mysqli_fetch_assoc($qSelect);
$tImage = "<img src='data:image/png;base64,".base64_encode($qRow['qrcode'])."'/>";
$tOverlay = "<img src='data:image/png;base64,".base64_encode($qRow['overlay'])."'/>";
header("Content-type: image/png");
$aQr = imagecreatefromjpeg($tImage);
$QrWidth = imagesx($aQr);
$QrHeight = imagesy($aQr);
$aOverlay = imagecreatefrompng($tOverlay);
$OverlayWidth = imagesx($aOverlay);
$OverlayHeight = imagesy($aOverlay);
$OverlayQrWidth = $QrWidth / 3;
$OverlayQrHeight = $OverlayHeight / ($OverlayWidth / $OverlayQrWidth);
imagecopyresampled($aQr, $aOverlay, $OverlayQrWidth, $OverlayQrHeight, 0, 0, $OverlayQrWidth, $OverlayQrHeight, $OverlayWidth, $OverlayHeight);
imagepng($aQr);
$oImage = "<img src='data:image/png;base64,".base64_encode($aQr)."'/>";
$UpdateCombineSql = "UPDATE `userprofile_qr` SET
`combine` = '$oImage'
WHERE userid = '".$Row2['userid']."' ";
$CombineResult = mysqli_query($Conn, $UpdateCombineSql);
echo "Success";
}
?>

PHP SQL Result stored as var in new sql query

So its a php game etc...
This is the main part of my script;
$sql = "SELECT * from search1 WHERE username='Hitachi'";
$result = mysqli_query($connection, $sql);
while ($rows = mysqli_fetch_array($result)) {
$timeleft = $rows['time'];
$target55 = $rows['target'];
$id = $rows['id'];
$status = $rows['status'];
$hours = $rows['hours'];
$started = $rows['started'];
$deletetime = $started - 86400;
mysqli_query($connection, "DELETE FROM search WHERE started<'$deletetime'");
$starttime = $started;
$time1 = $starttime + 10800;
$a_query = mysqli_query($connection, "SELECT * FROM BG WHERE username='$target55' AND status='Ready'");
$check_found = mysqli_num_rows($a_query);
if ($check_found >= 1) {
$bg = mysqli_query($connection, "SELECT * FROM BG WHERE status='Ready' AND username='$target55' ORDER by slot DESC LIMIT 1");
while ($i = mysqli_fetch_object($bg)) {
$bg1 = $i->bodyguard;
}
echo "This user has a bodyguard called <b>$bg1</b>!";
if ($time1 < time() && $hours >= 3 || $userlevel >= 14) {
$sql2 = "SELECT * from users WHERE username='$target55'";
$result2 = mysqli_query($connection, $sql2);
while ($rows2 = mysqli_fetch_array($result2)) {
$target_country = $rows2['country'];
}
mysqli_query($connection, "UPDATE search1 SET status='2', location='$target_country', found='$target_country' WHERE id='$id'");
}
mysqli_query($connection, "DELETE FROM BG WHERE username='$target55'");
This does nothing at all regardless if there is a bodyguard or not.
If i remove the check for the bodyguard etc then it works however i need it to check?

Problems updating correct row in databse with php

I'm trying to create a voting system for artists played on my radio station. I'm using the source code from: http://dl.howcode.org/download/97ff383c7d4dc9939c65c9e6fab2a5dc
The problem I have found is that the votes update using the number from the first row in the database no matter which option is selected, thus if for instance the first row has 3 votes in and the user tries to vote on someone with 0 votes, it will change the votes for the correct artist to 4 instead of 1... I hope that makes sense?
The code I have is:
[EDIT] I have changed the queries to fetch assoc to make it easier to understand.
<?php
$voteID = $_GET['voteID'];
$connect = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT * FROM listenervotes WHERE voteID='$voteID'" ;
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($q)){
$id = $row["id"];
$voteTitle = $row["voteTitle"];
$voteID = $row["voteID"];
$ipaddress = $row["ipAddress"];
echo "<h3>$voteTitle</h3>";
?>
<table>
<form action="" method="POST">
<?php
$artists = "SELECT * FROM artists WHERE voteID='$voteID'" ;
$q2 = mysqli_query($connect, $artists);
while($r = mysqli_fetch_assoc($q2)){
$artist = $r["artistName"];
$votes = $r["votes"];
$genre = $r["genre"];
$ip = $_SERVER['REMOTE_ADDR'];
$newIpAddress = $ipaddress."$ip, ";
$newVotes = $votes + 1;
if (isset($_POST['vote'])) {
$voteOption = $_POST['voteOption'];
if ($voteOption == ""){
die("You haven't selected anyone!");
}else{
$ipaddressE = explode(",", $ipaddress);
if(in_array($ip, $ipaddressE)){
die("You have already voted!");
}else{
mysqli_query($connect, "UPDATE artists SET votes='$newVotes' WHERE voteID='$voteID' AND artistName='$voteOption'");
mysqli_query($connect, "UPDATE listenervotes SET ipaddress='$newIpAddress' WHERE voteID='$voteID'");
die('You voted successfully!<br><tr><td>'.$artist.'</td><td>'.$genre.'</td><td>'.$votes.' Votes</td></tr>');
}
}
}
echo '<tr><td>'.$artist.'</td><td>'.$genre.'</td><td><input type="radio" name="voteOption" value="'.$artist.'"</td></tr>';
}
}
?>
I could be missing something obvious, in my mind I'm thinking that I somehow need to iterate through the rows before setting the new value, if so, how and where?
It looks like you are always looping over all rows and updating the relevant row with the first value found. Adding a check on the ID should do:
<?php
$voteID = $_GET['voteID'];
$connect = mysqli_connect('xxx', 'xxx', 'xxx', 'xxx');
$query = "SELECT * FROM listenervotes WHERE voteID='$voteID'" ;
$q = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($q)){
$id = $row["id"];
$voteTitle = $row["voteTitle"];
$voteID = $row["voteID"];
$ipaddress = $row["ipAddress"];
echo "<h3>$voteTitle</h3>";
?>
<table>
<form action="" method="POST">
<?php
$artists = "SELECT * FROM artists WHERE voteID='$voteID'" ;
$q2 = mysqli_query($connect, $artists);
while($r = mysqli_fetch_assoc($q2)){
$artist = $r["artistName"];
$votes = $r["votes"];
$genre = $r["genre"];
$ip = $_SERVER['REMOTE_ADDR'];
$newIpAddress = $ipaddress."$ip, ";
$newVotes = $votes + 1;
if (isset($_POST['vote'])) {
$voteOption = $_POST['voteOption'];
if ($voteOption == ""){
die("You haven't selected anyone!");
}else{
$ipaddressE = explode(",", $ipaddress);
if(in_array($ip, $ipaddressE)){
die("You have already voted!");
}elseif ($voteOption === $artist) { // Don't run UPDATE when we're on the wrong row.
mysqli_query($connect, "UPDATE artists SET votes='$newVotes' WHERE voteID='$voteID' AND artistName='$voteOption'");
mysqli_query($connect, "UPDATE listenervotes SET ipaddress='$newIpAddress' WHERE voteID='$voteID'");
die('You voted successfully!<br><tr><td>'.$artist.'</td><td>'.$genre.'</td><td>'.$votes.' Votes</td></tr>');
}
}
}
echo '<tr><td>'.$artist.'</td><td>'.$genre.'</td><td><input type="radio" name="voteOption" value="'.$artist.'"</td></tr>';
}
}
?>

Undefined variable, unsure why

<?php
$tid = $_GET['tid'];
$id = $_SESSION['userid'];
$sql1 = "SELECT * FROM topics WHERE id='$tid' LIMIT 1";
$res1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
while ($row = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$title = $row['topic_title'];
$creator = $row['topic_creator'];
}
$sql = "SELECT * FROM users WHERE id='$creator' LIMIT 1";
$user_query = mysqli_query($connect, $sql) or die(mysqli_error($connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$name = $row["first"].$row["last"];
}
echo $name;
?>
I'm a little new to PHP, but I've done things exactly like this, but this time I'm getting an error. Everything here works except for $name. I checked my SQL tables and made sure users exist and that there's first and a last area. I don't see what else could be wrong.
Notice: Undefined variable: name in * on line **
Thank you.
Try this code on for size:
<?php
$tid = $_GET['tid'];
$id = $_SESSION['userid'];
$tid = mysqli_escape_string($connect, $tid);
$sql1 = "SELECT * FROM topics WHERE id='{$tid}' LIMIT 1";
$res1 = mysqli_query($connect, $sql1) or die(mysqli_error($connect));
// Check for rows first.
if($res1 and mysqli_num_rows($res1)){
// Use if as while is pointless on LIMIT 1
if($row = mysqli_fetch_array($res1, MYSQLI_ASSOC)) {
$title = $row['topic_title'];
$creator = $row['topic_creator'];
$creator = mysqli_escape_string($connect, $creator);
$sql = "SELECT * FROM users WHERE id='{$creator}' LIMIT 1";
$user_query = mysqli_query($connect, $sql) or die(mysqli_error($connect));
// Check for rows first.
if($user_query and mysqli_num_rows($user_query)){
// Use if as while is pointless on LIMIT 1
if ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$name = $row["first"].$row["last"]; // NO HIT!
}
echo $name;
}else{
echo 'no rows found (query 2).';
}
}
}else{
echo 'no rows found (query 1).';
}
?>
Variable $name is undefined because the $name = ...; line is not reached. So make sure you $sql query actually returns results. It has to in order to define $name.

Categories