My question is very simple. The code I have written here produces absolutely no output on the webpage. I've been at it all day and I'm sure that it's something very simple that I am being an idiot for missing. So I am appealing to your good-natured fresh eyes! If anyone can spot a reason why this isn't working, I'd be very grateful.
The premise:
This is a decision tree online survey that has the following conditions: if a user has already started the survey, it will find them in the database, find their last answered question and display the next one. But if they haven't started, it will display the first question.
All survey questions are held in the database as well as the decision tree logic (for instance, if the user chooses option 2 for question 1, they will be directed to question 3, not 2).
Please assume that for the moment, I am updating relevant info directly from the database and not automating it on the website.
Thanks :)
PHP:
<?php
//Find the latest question reached by the user for display on the page
$sql = mysql_query("SELECT QuestionNumberReached FROM User WHERE EmailAddress = '***'");
$sqlCount = mysql_num_rows($sql);
if ($sqlCount > 0) {
while ($row = mysql_fetch_array($sql)) {
$QuestionNumberReached = $row["QuestionNumberReached"];
}
}
?>
<?php
//Find the last question answered by the user from the database
$StartedQuery = mysql_query("SELECT LastQuestionAnswered FROM User WHERE EmailAddress = '***'");
//Count the number of rows that the query produces
$StartedQueryCount = mysql_num_rows($StartedQuery);
//If data is found, whether it be a number or null, define the value
if ($StartedQueryCount > 0) {
while ($row = mysql_fetch_array($sql)) {
$LastQuestionAnswered = $row["LastQuestionAnswered"];
//If the field has a value and is not null, find the next question from the database
if (!empty($LastQuestionAnswered)) {
//Find the User's ID and the ID of the last question answered
$sqlA = mysql_query("SELECT PKID, LastQuestionAnswered FROM User WHERE EmailAddress = '***'");
//If the operation produces an error, output an error message
if (!$sqlA) {
die('Invalid query for SQLA: ' . mysql_error());
}
//Count the number of rows output
$sqlACount = mysql_num_rows($sqlA);
//If rows exist, define the values
if ($sqlACount > 0) {
while ($row = mysql_fetch_array($sqlA)) {
$sqlAPKID = $row["PKID"];
$sqlALastQuestionAnswered = $row["LastQuestionAnswered"];
}
}
//Find the answer given by the user to the last answered question
$sqlB = mysql_query("SELECT Answer FROM Responses WHERE User = $sqlAPKID");
//If the operation produces an error, output an error message
if (!$sqlB) {
die('Invalid query for SQLB: ' . mysql_error());
}
//Count the number of rows output
$sqlBCount = mysql_num_rows($sqlB);
//If rows exist, define the values
if ($sqlBCount > 0) {
while ($row = mysql_fetch_array($sqlB)) {
$sqlBAnswer = $row["Answer"];
}
}
//Find the number of the next question to be answered based on the user's previous answer and the question they answered
$sqlC = mysql_query("SELECT NextQuestion FROM Answers WHERE QuestionNumber = $sqlALastQuestionAnswered AND PKID = $sqlBAnswer");
//If the operation produces an error, output an error message
if (!$sqlC) {
die('Invalid query for SQLC: ' . mysql_error());
}
//Count the number of rows output
$sqlCCount = mysql_num_rows($sqlC);
//If rows exist, define the values
if ($sqlCCount > 0) {
while ($row = mysql_fetch_array($sqlC)) {
$sqlCNextQuestion = $row["NextQuestion"];
}
}
//Find the question text pertaining to the ID of the next question that needs to be answered
$sqlD = mysql_query("SELECT QuestionText FROM Questions WHERE PKID = $sqlCNextQuestion");
//If the operation produces an error, output an error message
if (!$sqlD) {
die('Invalid query for SQLD: ' . mysql_error());
}
//Count the number of rows output
$sqlDCount = mysql_num_rows($sqlD);
//If rows exist, define the values
if ($sqlDCount > 0) {
while ($row = mysql_fetch_array($sqlD)) {
$SurveyStartedQuestionText = $row["QuestionText"];
}
}
//Set a string of information that will show the question number and question text as appropriate
$ToDisplay = '' . $QuestionNumberReached . ': ' . $SurveyStartedQuestionText . '<br /><br />Answer Text Here';
//If the value for QuestionNumberReached is null, the user has not started the survey
} else if (empty($LastQuestionAnswered)) {
//Find the question text of the first question in the survey
$sql3 = mysql_query("SELECT QuestionText FROM Questions WHERE PKID IN (SELECT FirstQuestion FROM Batch WHERE BatchNumber IN (SELECT BatchNumber FROM User WHERE EmailAddress = '***'))");
//Count the number of rows output
$sql3Count = mysql_num_rows($sql3);
//If rows exist, define the values
if ($sql3Count > 0) {
while ($row = mysql_fetch_array($sql3)) {
$SurveyNotStartedQuestionText = $row["QuestionText"];
}
}
//Set a string of information that will show the question number and question text as appropriate
$ToDisplay = '' . $QuestionNumberReached . ': ' . $SurveyNotStartedQuestionText . '<br /><br />Answer Text Here';
}
}
}
?>
HTML:
<body>
<?php
// Display the concatenated information that has been previously defined
echo $ToDisplay;
?>
</body>
This bit:
if ($StartedQueryCount > 0) {
probably evaluates to false, and there's no matching else tag that adds content.
Try changing:
}
?>
with:
}
else {
$ToDisplay = 'Error: no rows found to display!';
}
?>
Edit:
Also, this bit:
} else if (empty($LastQuestionAnswered)) {
Could be replaced with the more readable:
} else {
Since it does exactly the same thing.
And within your while loop, you are constantly redefining $ToDisplay, I assume this is wanted behaviour? Otherwise initialize the variable on top (before the while() loop) like so:
$ToDisplay = '';
And change the assignments within the loop to concatenations, like so:
$ToDisplay = 'text assignment';
To:
$ToDisplay .= 'text concat'; // look at the dot before =
Thank you for all your help! I really appreciate you all taking the time.
I finally realised what was wrong...
On Line 18 of my PHP code, I had the following:
while ($row = mysql_fetch_array($sql)) {
whereas it should of course have been this:
while ($row = mysql_fetch_array($StartedQuery)) {
Essentially I was calling the rows from the wrong query. And I feel a clot because of it!
Thanks again, everyone :)
Related
This question already has answers here:
How to pop an alert message box using PHP?
(9 answers)
Closed 1 year ago.
I have an online software that use php, html, js and MySQL as database.
I have two tables:
1- First table contains [name, imei, object_expire, object_expire_dt] - gs_objects
2- Second table contains [object_id, user_id, imei] - gs_user_objects
The code should be done in php where the user_id is got from the session, then the first query should get the imeis that matches the user_id from second table then it should get the expire date 'object_expire_dt' of each imei from the first table
after that it should check if there is an expire date that will expire within 20 days, if true, it should show alert message
Here is incomplete code that I tried to do
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."' ORDER BY `object_id` ASC";
$r2 = mysqli_query($ms, $q2);
while($row=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row['object_expire_dt'] > date('Y-m-d', strtotime($Date_e. ' - 20 days')))
{
alert("You have objects are going to expire soon");
}
}
}
the code didn't work, I need some help in it.
Thanks in advance
Here's how all this works: Your php program runs on your server, and accesses your database on the server. The purpose of your php program is to create programs to run on your users' browsers. Those programs written by php use the HTML, Javascript, and CSS languages.
If you want something to happen in a user's browser (like an alert box) that thing has to appear in a Javascript program written by your php program and sent to the browser. php doesn't have its own alert() function
Here's an easy, but somewhat sloppy, way to do that in your php program.
echo "<script type='text/javascript'>window.onload=function(){alert('$msg'))</script>";
What's going on here?
echo tells php to write its parameter to the html page
<script> whatever </script> is the way to embed Javascript in html
window.onload = function () { whatever } tells the browser to run a Javascript function when your html page finishes loading.
alert(message), in the function, pops up the alert message.
When you're troubleshooting this kind of thing, View Source ... is your friend.
you can use alert in javascript not in php
also you should use prepared statement.
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser'){
$user_id = $_SESSION["manager_id"];
}else{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM gs_user_objects WHERE user_id = ? ORDER BY object_id ASC";
if ($r = $connection->prepare($q)) {
// if user_id contains string and is not integer you must use "s"
$r->bind_param("i",$user_id);
if ($r->execute()) {
$result = $r->get_result();
// check if result match one condition
if ($result->num_rows > 0) {
echo "result found";
while ($row = $result->fetch_assoc()) {
echo $row['some_column_name'];
}
}
}
}
Thanks Nikolaishvili and Jones,
Your answers helped me a lot I needed more edit on the if statements,
I did the code and the result is as I expected and it is online now, here the code is below so others can check it
//notification for objects expiration
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
$expiry_flag = 0;
$inactive_flag=0;
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."'";
$r2 = mysqli_query($ms, $q2);
while($row2=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row2['object_expire_dt'] < date('Y-m-d', strtotime($Date_e. ' + 20 days')))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$expiry_flag = 1;
}
}
if ( $row2['object_expire_dt'] < date("Y-m-d"))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$inactive_flag = 1;
}
}
}
}
if ($expiry_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg1")';
echo '</script>';
}
if ($inactive_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg2")';
echo '</script>';
}
Thanks
Good day # all.
I've this code snippet which's aim is to display the Exam this user is qualified to take based on the courses registered for. It would display the Exam Name, Date Available, Passing Grade and either Take Exam link if he/she hasn't written or View Result if he/she has written previously.
/*Connection String */
global $con;
$user_id = $_SESSION['user_id']; //user id
$courses = parse_course($user_id); //parse course gets the list of registered courses (Course Codes) in an array
foreach ($courses as $list)
{
$written = false;
$list = parse_course_id($list); //parse_course_id gets the id for each course
$ers = mysqli_query($con, "Select * from exams where course_id = '$list'");
while ($erows = mysqli_fetch_assoc($ers)) {
$trs = mysqli_query($con, "Select * from result_data where user_id = '$user_id'");
while ($trows = mysqli_fetch_assoc($trs)) {
if ($trows['user_id'] == $user_id && $trows['exam_id'] == $erows['exam_id'])
$written = true;
else
$written = false;
}
if($written)
{
echo "<tr><td>".$erows['exam_name']."</td><td>".$erows['exam_from']." To ".$erows['exam_to']."</td><td>".$erows['passing_grade']."%</td><td>".'View Result '."</td></tr>";
$written = false;
}
else
{
echo "<tr><td>".$erows['exam_name']."</td><td>".$erows['exam_from']." To ".$erows['exam_to']."</td><td>".$erows['passing_grade']."%</td><td>".'Take Exam '."</td></tr>";
$written = false;
}
}
}
But It only displays one View Result entry even if I've taken more than one exam. It shows the recent entry. Please what am I missing?
Untested, but here's how I would do it.
I've assumed $user_id is an integer. I'm a bit worried about it being used in SQL without any sanitization. I can't guarantee anything else you're doing is secure either because I can't see your other code. Please read: http://php.net/manual/en/security.database.sql-injection.php
(Oh I see someone already commented on that - don't take it lightly!)
Anyway, my approach would be to collect the user's written exam IDs into an array first. Then loop through the available exams and check each exam id to see if it's in the array we made earlier.
I wouldn't bother looking into the join advice unless you find this is performing poorly. In many systems it would be common to have 3 functions in this situation, one that generates $users_written_exam_ids ones that pulls up something like $all_available_exams and then this code which compares the two. But because people are seeing both queries here together there is a strong temptation to optimize it, which is cool but you probably just want it to work :)
<?php
global $con;
// Get the user id. Pass through intval() so no SQL injection is possible.
$user_id = intval($_SESSION['user_id']);
// Parse course gets the list of registered courses (Course Codes) in an array
$courses = parse_course($user_id);
foreach ($courses as $list)
{
// Gets the id for each course
$list = parse_course_id($list);
$users_written_exam_ids = array();
$trs = mysqli_query($con, "SELECT exam_id FROM result_data WHERE user_id = '$user_id'");
while ($trows = mysqli_fetch_assoc($trs))
{
$users_written_exam_ids[] = $trows['exam_id'];
}
$ers = mysqli_query($con, "SELECT * FROM exams WHERE course_id = '$list'");
while ($erows = mysqli_fetch_assoc($ers)) {
echo '<tr><td>' . $erows['exam_name'] . '</td><td>' . $erows['exam_from']
. ' To ' . $erows['exam_to'] . '</td><td>' . $erows['passing_grade']
. '%</td><td>';
if (in_array($erows['exam_id'], $users_written_exam_ids))
{
echo 'View Result';
}
else
{
echo 'Take Exam';
}
echo '</td></tr>';
}
}
Im trying to sum up all the values in this data base but for some reason i cant do i, I looked all over stack overflow and tried multiple methods but none seem to work. My current code is
<?php
error_reporting(0);
//INCLUDES//
include 'config.php';
//INCLUDES//
//DATA FETCH//
$rank=$_POST['R'];
$drank=$_POST['DR'];
//DATA FETCH//
//MYSQL STUFF//
$con=mysqli_connect($ip,$login,$password,$dbname);
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i'");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
echo $row[0];
}
?>
It connects to the database no problem. When I use echo $row[0]; it prints all the values of the column in order. Ive tried putting it into an array and printing it but it seems that doesnt work either. The only way it seems to work is when I add ALL the values in the column by removing WHERE rank='$i' in the SQL code which I dont want to do. Please help !
Try the following query :
$rankarr = array();
for ($i = $rank; $i <= $drank; $i++) { // LOOP UNTIL 20 IS MET
$rankarr[] = $i;
}
$rankarr = implode(',', $rankarr);
$s=mysqli_query($con, "SELECT sum(rankprice) As myrank FROM cost WHERE rank in ($rankarr)");
if($s === FALSE) { //CHECK IF DATA IS THERE
die('Error: ' . mysqli_error($con)); // IF NOT THERE SEND ERROR
}
$row = mysqli_fetch_array($s); //PUT DATA IN ROW
You now want to get the sum value of rankprice in one same rank. So the result of sum() will differ from the rank in one sql. You should tell mysql by adding group by clause, which group the table by rank and get the sum() of each group.
$s=mysqli_query($con, "SELECT sum(rankprice) FROM cost WHERE rank='$i' GROUP BY rank ");
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Eperimenting PHP just for fun, But As being newbie, I'm unable to understand curcial parts of PHP....Please help me to sort out this problem which I'm explaining by example :
Suppose
$sql = "SELECT id, text,uid FROM feeds WHERE uid='".$ud."' LIMIT 10";
$items = mysql_query($sql);
echo mysql_error();
if (#mysql_num_rows($items) > 0)
{
while ($item = mysql_fetch_array($items))
{
$feed = $item[1];
$nick = getnick($item[2]);
}
}
So I want to display like this :
3 Records with uid details...
jay,vicky, sumair and 17 others like this.
Please help me to get output of something like this !!
Thanks !!
I can't stretch this enougth,
DO NOT USE MYSQL_* API anymore. [Read this]
It is VULNERABLE, mysqli_* functions are just as similar very little difference.
And You already are doing the things required for that output mysql_num_rows() already gives the number of total result. So:
if (mysql_num_rows($items) > 0)
{
$count = mysql_num_rows($items);
echo $count." Records with uid details..."; //Display the count of records
$threeNameHolder = array; // Hold the first three names on this
while ($item = mysql_fetch_array($items))
{
$feed = $item[1];
$nick = getnick($item[2]);
if(count($threeNameHolder) < 3) {
$threeNameHolder[] = $nick;
} else break; // End the loop here
}
//Now display the name
echo implode(",", $threeNameHolder). " and ".($count - 3)." others like this.";
}
Safer and MYSQLi Version
if (mysqli_num_rows($items) > 0)
{
$count = mysqli_num_rows($items);
echo $count." Records with uid details..."; //Display the count of records
$threeNameHolder = array; // Hold the first three names on this
while ($item = mysqli_fetch_array($items))
{
$feed = $item[1];
$nick = getnick($item[2]);
if(count($threeNameHolder) < 3) {
$threeNameHolder[] = $nick;
} else break; // End the loop here
}
//Now display the name
echo implode(",", $threeNameHolder). " and ".($count - 3)." others like this.";
}
To understand the basics fundaments, I really recommend the official documentation PHP
http://www.php.net/manual/en/ref.mysql.php
A simple sample to execute a query and display the output:
$query = mysql_query("SELECT a, b FROM table_name WHERE c='".$something."' LIMIT 10");
$num_rows = mysql_num_rows($query);
$test = array(); // create a empty array
/* while there is result */
while ($item = mysql_fetch_array($items)){
$columnA = $item[0];// first column (a)
$columnB = $item[1]); // second column (b)
$test[] = $columnB; // push_back a item on array
}
echo $num_rows. " Records with **" . $something . "**...";
echo implode($test, ", ") . "and some text";
I think my mind must be going through a Boxing Day mess.
I am building a basic comment section for every game a sports team plays.
So, when no comments are entered (in the MySQL DB), I simply want to display "Be the first to enter a comment"; otherwise, display the comment results table in html format.
I can easily display the comment result table.
For some reason, I can't get the IF no comments to work properly. Feel so amateurish right now . . . :-)
I have declared row count:
$row_count = 0;
I am adding to the count inside the while statement
while($row = mysql_fetch_array($result))
{
// adding to count
$row_count++;
My count is working as I can display the row number to the screen.
Here is IF / ELSE my code:
if ($row_count === 0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
} else {
// no need to show code as this already works!
you can use
mysql_num_rows($queryReference)
Hope this helps.
Thanks.
Please do one thing print this value using below function and tell me what is output
var_dump($row_count);
or you can use == instead of ===
$query = mysql_query("SELECT * FROM comments");
$c = mysql_num_rows($query);
if($c==0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
}
else {
while($row = mysql_fetch_array($query))
{
$vars = $row[index];
}
}
$row_count = 0;
I am adding to the count inside the while statement
while($row = mysql_fetch_array($result))
{
// adding to count
$row_count++;
}
My count is working as I can display the row number to the screen.
Here is IF / ELSE code:
if ($row_count == 0) {
echo "<p>Be the first to enter a game comment and earn points toward your next fan badge.</p>";
} else {
// no need to show code as this already works!
}