Jump to content

gerrydewar

Members
  • Posts

    36
  • Joined

  • Last visited

    Never

Profile Information

  • Gender
    Not Telling

gerrydewar's Achievements

Newbie

Newbie (1/5)

0

Reputation

  1. Tried your solution but it was still the same. I manafed to solve the problem though. The first $row = mysql_fetch_array($result) was not required. I was limiting my displayed results i think. Seems to be working now.
  2. Hello troops, I have a problem with a while loop. I want to select data from a database table and display the results in a table on screen. With the while loop commented out the first record in the query is displayed. With the while loop present no records are displayed. Can someone have a look at the code and see what the problem is. My while loop appears to be broken somewhere. [code] <? if(isset($_POST['submit2'])){ require_once ('../mysql_connect.php');//Connect to db. //Retrieve the test result info for a class. $query = "SELECT class.classnum, users.first_name, users.last_name, test_score.test_score FROM test_score LEFT JOIN users ON test_score.user_id=users.user_id LEFT JOIN class ON users.class_id=class.class_id WHERE classnum = '".(trim($_POST['classes']))."'"; $result = @mysql_query($query);//Run the query $row = mysql_fetch_array($result);//Return a record, if applicable. echo"<h3 align='center'>Results for class '".$_POST['classes']."'</h3>"; echo '<table border="1" width="50%" cellspacing="3" align="center"> <tr> <td align="center" width="10%"><b><u>Class</u></b></td> <td align="center" width="20%"><b><u>First Name</u></b></td> <td align="center" width="20%"><b><u>Surname</u></b></td> <td align="center" width="10%"><b><u>Score</u></b></td> </tr>'; while ($row=mysql_fetch_array($result)){ //Display each record. echo " <tr> <td align=\"center\">{$row[0]}</td> <td align=\"center\">{$row[1]}</td> <td align=\"center\">{$row[2]}</td> <td align=\"center\">{$row[3]}</td> </tr>\n"; }//End while echo '</table>; <table align= "center"cellpadding="20"> <tr><td> <a href="admin.php">Admin Home</a></td> <td> <a href="queryresults.php">Carry out another query</a></td> </table> </p>'; mysql_close(); [/code]
  3. [!--quoteo(post=360939:date=Apr 2 2006, 07:28 PM:name=Desdinova)--][div class=\'quotetop\']QUOTE(Desdinova @ Apr 2 2006, 07:28 PM) [snapback]360939[/snapback][/div][div class=\'quotemain\'][!--quotec--] ok, just for the fun of it, place a border in the table. does the table itself look ok? or a bit twisted? and this is the exact code of what you are using? [/quote] Table looks fine. looks quite good with a border in it actually. Exact code is: [code] <body> <form name="testing"action="test1.php"method="POST"> <?php error_reporting(E_ALL); //Connect to db. require_once ('../mysql_connect.php'); //Select 10 random questions from database where the subject id is 1 $query = "SELECT question_id, question, answer, choice1, choice2, choice3 FROM questions WHERE subject_id = 1 ORDER BY RAND() LIMIT 10"; $result = @mysql_query ($query) or die('Problem with query:' . $query . '<br/>' . mysql_error()); //Run query //echo 'Number of records found: '.mysql_num_rows($result)."<br/>\n"; $randomiseAnswer=rand(1,5);//used for randomising answer echo '<table align="left" cellspacing="10" cellpadding="10">'; $ints=array(); $num = 1; while ($row=mysql_fetch_assoc($result)){          echo '<tr><td align=\"left\"><b>'.$questions.'</b></td></tr>     <tr><td align=\"left\"><input type="radio" name="choice['.$id.']"value="'.$opt1.'"/>'.$opt1.'</td></tr>     <tr><td align=\"left\"><input type="radio" name="choice['.$id.']"value="'.$opt2.'"/>'.$opt2.'</td></tr>     <tr><td align=\"left\"><input type="radio" name="choice['.$id.']"value="'.$opt3.'"/>'.$opt3.'</td></tr>     '."\n";     $num++; }//while echo '</table>'; $passedValue1 = serialize($ints); ?> <input type="hidden" name="ints" value="<? echo htmlentities($passedValue1)?>"/> <input type="submit" name="submit"value="Submit Answers"> </form> </body> [/code]
  4. [!--quoteo(post=360908:date=Apr 2 2006, 05:58 PM:name=Desdinova)--][div class=\'quotetop\']QUOTE(Desdinova @ Apr 2 2006, 05:58 PM) [snapback]360908[/snapback][/div][div class=\'quotemain\'][!--quotec--] for the first: ' . $num . ' ' . $question . ' for the second, I think your while loop is in a table, and your table is not properly closed when you echo the submit button (so your submit button probably shows up after a </tr> which positions it on top of the table). there :) [/quote] First one sorted thanks. Second one: My table start and end tags are outside the while loop. I do have a while loop inside my table though. The code looks like this [code] <form> <? echo '<table align="left" cellspacing="10" cellpadding="10">'; while ($row=mysql_fetch_assoc($result)){ echo '<tr><td align=\"left\"><b>'.$questions.'</b></td></tr> <tr><td align=\"left\"><input type="radio" name="choice['.$id.']"value="'.$opt1.'"/>'.$opt1.'</td></tr> <tr><td align=\"left\"><input type="radio" name="choice['.$id.']"value="'.$opt2.'"/>'.$opt2.'</td></tr> <tr><td align=\"left\"><input type="radio" name="choice['.$id.']"value="'.$opt3.'"/>'.$opt3.'</td></tr> '."\n"; $num++; }//while echo '</table>'; ?> <input type="submit" name="submit"value="Submit Answers"> </form> [/code]
  5. Hello again everyone. I have two little problems with my code that i'm sure won't take a great deal of fixing. Firstly i want to display 2 variables in my browser with a gap in between them. The code i have at the moment is as follows: [code] echo '<tr><td align=\"left\"><b>'.$num , $questions.'</b></td></tr>.......... [/code] When i view the output in my browser i get something like '2Question' when i actually would like '2 Question'. I tried to use the command but i must have used it incorrectly as nothing happened. The second problem concerns the position of a button when my code is viewed in my browser. I have a normal form that contains php code between the start and end form tags e.g. [code] <form name="testing"action="test1.php"method="POST"> <?php While loop to display my questions ?> <input type="submit" name="submit"value="Submit Answers"> </form> [/code] When i run this code and view it in my browser my 'Submit Answers' button is positioned at the top of my page. I would like it to be positioned centrally at the bottom of my page after my while loop has finished displaying my last question. For some reason i'm finding this task rather difficult. I'm sure it will be fairly straight forward. Can someone please put me out of my misery?
  6. I've tried to run these scripts without success. Now i've no doubt the error is on my part and not yours. My login.php page constantly gave me the invalid query result and header problems. So i got a bit adventurous and decided to mix and match your login script with the script you suggested we put at the top of every page. My login.php now looks like the following: [code] <?php if(isset($_POST['submit'])){ session_start(); $link = mysql_connect('localhost', 'root', '********') or die("MySQL: ".mysql_error()); mysql_select_db('project', $link) or die("MySQL: ".mysql_error()); // Since this may be the first time running the script we need to make sure we have a sessions table. // We will do it with a simple MySQL Query.  You can disect the following query to see how it works. mysql_query("CREATE TABLE IF NOT EXISTS `sessions` (`id` int(11) NOT NULL auto_increment,`uid` int(11) NOT NULL, `timeout` int(11) NOT NULL default '0', PRIMARY KEY  (`id`))", $link); // We are attempting to login now.   $row = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE email='".$_POST['Login_email']."' LIMIT 1", $link));   if(mysql_num_rows(mysql_query("SELECT * FROM sessions WHERE uid=".$row['user_id']." LIMIT 1", $link)) != 1 ) {     if ( $_POST['Password'] == $row['password'] ) {       // Username/Password pair verified change the session from guest to admin or user as the case may be.       // If you did not already have a session assigned to you create one now.       if (!is_array($session) ) {         mysql_query("INSERT INTO sessions (uid, timeout) values ('".$row['user_id']."', ".(time()+600).")", $link);         $session = mysql_fetch_assoc(mysql_query("SELECT * FROM sessions WHERE sid='".session_id()."' LIMIT 1", $link));       }       mysql_query("UPDATE sessions SET uid=".$row['user_id']." WHERE sid='".session_id()."' LIMIT 1", $link);       mysql_query("UPDATE sessions SET timeout=".(time()+600)." WHERE sid='".session_id()."' LIMIT 1", $link);       header("Location: logged_in2.php"); // We are logged in head over to the main page.     } else {       echo "<span class=\"error\">Invalid username/password.</span>\r\n";     }   } else {     echo "<span class=\"error\">User already logged in.</span>\r\n";     echo "<p>We do not allow multiple sessions for the same user. If this is your account this might mean that someone has gained access to your username and password without your consent. If this is the case, please contact an administrator about changing your password.</p>\r\n";   } mysql_close($link); }else{ ?> <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">     <head>     <meta http-equiv="content-type"content="text/html;charset=encoding"/>     <title>Login</title>     <h2>Login page</h2>     </head>     <body>         <form method="POST" action="<?php echo "$PHP_SELF";?>"<font face="Arial">         <fieldset>             <b><font size="2">Email: </font></b><input type="text" name="Login_email" size="40" maxlength="255"><br\>             <b><font size="2"><br>Password: </font></b><input type="password" name="Password" size="16" maxlength="255"><br\>             <input type="submit" name="submit" value="Login!"><font size="2"> </font>         </fieldset>         </form>         <p>If you have yet to register for an account please follow the link below to create one.</p><p><font face="Arial" size="2"><a href="register.php">Register for an account</a></font></p>     </body>     <?     }     ?> </html> [/code] Now i'm not really bothered about session id's or tracking ip's so i took that out. I needed to put the session_start at the top on my login page in order to get rid of my errors. I'll perhaps try to move it to after i have successfully matched passwords etc so a session does not start if i have any validation problems. One problem i am having is getting any info into my session table. I can create the session table when my login.php runs initially but when i log in then check the contents of my table all i get is an empty set. I cannot see where the problem lies. Any idea?
  7. [!--quoteo(post=354800:date=Mar 14 2006, 09:14 AM:name=txmedic03)--][div class=\'quotetop\']QUOTE(txmedic03 @ Mar 14 2006, 09:14 AM) [snapback]354800[/snapback][/div][div class=\'quotemain\'][!--quotec--] Now that you have your sessions table and your sessions up and running, you need a way for users to log in. You can use a form that gets submitted to a page to process the login or you could use the http authentication method. There is an example of this in the tutorials of this site and I would be happy to review the modifications to make this work with the snippets I am posting. Now this will be a page I will call login.php to process the login. Additionally, I have written this to restrict accounts to only one login per username. If this is not something you are interested in I can point out the specific lines to change. [code]<?php $link = mysql_connect('database host address', 'username', 'password') or die("MySQL: ".mysql_error()); mysql_select_db('database name', $link) or die("MySQL: ".mysql_error()); if ( isset($_GET['logout']) ) {   // We are logging out, but we want to maintain the session as a guest user.   mysql_query("UPDATE sessions SET uid=-1 WHERE sid='".session_id()."' LIMIT 1", $link);   mysql_query("UPDATE sessions SET timeout=".(time()+600)." WHERE sid='".session_id()."' LIMIT 1", $link);   mysql_query("UPDATE sessions SET level='0' WHERE sid='".session_id()."' LIMIT 1", $link);     header("Location: index.php"); // We are done head back to the main page. (This could also go to the refering page.) } else {   // We are attempting to login now.   $row = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE name='".$_POST['username']."' LIMIT 1", $link));   if ( mysql_num_rows(mysql_query("SELECT * FROM sessions WHERE uid=".$row['id']." LIMIT 1", $link)) != 1 ) {     if ( $_POST['password'] == $row['pass'] ) {       // Username/Password pair verified change the session from guest to admin or user as the case may be.       mysql_query("UPDATE sessions SET uid=".$row['id']." WHERE sid='".session_id()."' LIMIT 1", $link);       mysql_query("UPDATE sessions SET timeout=".(time()+600)." WHERE sid='".session_id()."' LIMIT 1", $link);       header("Location: index.php"); // We are logged in head over to the main page.     } else {       echo "      <span class=\"error\">Invalid username/password.</span>\r\n";     }   } else {     echo "      <span class=\"error\">User already logged in.</span>\r\n";     echo "      <p>We do not allow multiple sessions for the same user. If this is your account this might mean that someone has gained access to your username and password without your consent. If this is the case, please contact an administrator about changing your password.</p>\r\n";   } } mysql_close($link); ?>[/code] Now this won't function without having a table full of users. That's our next step, to create our users table and put some users in it so they can access the site. For right now, I must go and get some sleep. This will give you a chance to review everything and ask questions on anything you do not understand. I might write an actual tutorial later which will break the code down and explain it step by step. [/quote] This may sound like a stupid question but i'm going to ask it anyway. I have created this login page and added a form at the bottom where users can enter username and password. However, do i also require the session start script that creates the session table at the top of this login.php page? The reason i ask is surely this part of the code will always return nothing because the session table hasn't been created yet. [code] if ( mysql_num_rows(mysql_query("SELECT * FROM sessions WHERE uid=".$row['id']." LIMIT 1", $link)) != 1 ) { [/code] The login.php page is always going to be the first page called. How can you select all from session when session doesn't exist? Also session won't exist until someone logs in. When i try to run my login.php script with the code contained above i get a warning:mysql_num_rows():supplied argument is not a valid MySQL result resource on the line shown above. Can someone perhaps explain what code needs to be in my login page?
  8. [!--quoteo(post=359243:date=Mar 28 2006, 12:37 PM:name=thorpe)--][div class=\'quotetop\']QUOTE(thorpe @ Mar 28 2006, 12:37 PM) [snapback]359243[/snapback][/div][div class=\'quotemain\'][!--quotec--] Sessions cannot be shared accross users. So just because one user is logged in, doesn't meen your sessions are aware of another user attempting to login. In other words.... this [code] //check to see if anyone is logged in already if (isset($_SESSION['loggedin'])){ [/code] Does not check if ANY user is already logged in, but checks if the CURRENT user is logged on. What you would need to do is something like.... When a user logs in, set a field in your db to true. When another user attempts to login, check this field, if its true, deny them. [/quote] I thought that is what i had already done. I set [code] $_SESSION['loggedin']="TRUE"; [/code] then i check to see if it is true or not at the top of the script. I only ever want one user to be logged in at any time. I see what your saying about adding a field to the database but i thought this could be done without doing something like that.
  9. Having one problem with my session at the moment. I can log in ok and do what needs to be done. I can keep track of my users which is great. The problem i am having is once a user is logged in another user can then log in on top of them. Below is a copy of my code for my login page. If a user is logged in then another user should not be able to access the log in page properly. A message should be displayed telling them a user is currently logged in. This does not happen. What does happen is that everytime a user accesses the login page they always get a chance to enter their username and password. Can you see where my problem lies? Can anyone see where i'm going wrong? [code] <?php //check to see if anyone is logged in already if (isset($_SESSION['loggedin'])){     die("You are already logged in as $name. If you are not $name <br><a href='logout.php'>click here to logout</a> otherwise <a href='logged_in.php'>click here to continue</a>");     //if nobody logged in then....     }else{     if (isset($_POST['submit'])){         require_once ('../mysql_connect.php');         $username=$_POST['Login_email']; //Get the username the user has entered         $password=$_POST['Password']; //Get the password the user has entered         if($username && $password){         $result=mysql_query($sql);         //If the user gets to here, then they have typed both a username and password, so we may now go onto finding out if they exist in the DB         $sql="SELECT * FROM users WHERE email='$username' AND password='$password'"; //get rows where the username field matches the username or email field in the database with same password         $result=mysql_query($sql);             if(mysql_num_rows($result) > 0){             session_start(); //start the session             $_SESSION['loggedin']="TRUE"; //set the global session varible for loggedin to true             $row=mysql_fetch_array($result);             $_SESSION['username'] = $row[1];             $_SESSION['userid'] = $row[0];             $name = $row[1];             $userid = $row[0];             die("Welcome $name $userid. You are now logged in. <a href='logged_in.php'>Click here to continue</a>");             }else{             die("Incorrect Login! Your username or password do not match records stored in the database. Please try again. <a href='login2.php'>Click here to go back</a>");                }           }else{           die("You must enter a username and password!");         }     }//submit }//session ?> <!DOCTYPE html PUBLIC"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml">     <head>     <meta http-equiv="content-type"content="text/html;charset=encoding"/>     <title>Login</title>     <h2>Login page</h2>     </head>     <body>         <form method="POST" action="<?php echo "$PHP_SELF";?>"<font face="Arial">         <fieldset>             <b><font size="2">Email: </font></b><input type="text" name="Login_email" size="40" maxlength="255"><br\>             <b><font size="2"><br>Password: </font></b><input type="password" name="Password" size="16" maxlength="255"><br\>             <input type="submit" name="submit" value="Login!"><font size="2"> </font>         </fieldset>         </form>         <p>If you have yet to register for an account please follow the link below to create one.</p><p><font face="Arial" size="2"><a href="register.php">Register for an account</a></font></p>     </body> </html> [/code]
  10. Genius. That has solved the problem. Thanks Ken
  11. Tried those changes and the count starts at zero now which is great. It still doesn't increment properly though when a user gets a question right. I can send the database files to you.
  12. I've tried resetting $row[0] to be "" everytime the loop gets to the end so that it is empty but i still get a score of 10 as my initial score when no answers are selected. There is a problem with my for loop somewhere i think but can't see it. Do i need an else in the if statement?
  13. Hello everyone, I'm trying to compare 2 strings and increment a counter everytime i have a match. Basically the answer given by a user matched with the correct answer from the database. Sounds easy but for some reason my score starts at 10 and works its way down instead of starting at zero and going up. For example, if i click on my submit button with no answers radio buttons selected my score is 10. If i select one correct answer and nothing else i get 9, 2 correct gives me 8 and so on. However, it gets down to 4 and sticks for a while. In the end 10 correct answers gives me a score of 3, sometimes 4. The code is below: [code] //Transferring question_ids from source page if(isset($_POST['submit'])){ $ints = unserialize(stripslashes($_POST['ints'])); echo "<pre>\n"; print_r($ints); echo "</pre>\n"; } //Transferring radio button values selected by user on source page if (array_key_exists('submit',$_POST)){ $description = $_POST['choice']; echo "<pre>\n"; print_r($description); echo "</pre>\n"; } //Comparing users answer with correct answer and adding one to total score each time $score = 0; //Connect to db. require_once ('../mysql_connect.php'); for($counter = 0; $counter < 10; $counter++){ $query = "SELECT answer FROM questions WHERE question_id = '$ints[$counter]'"; //Run query $result = @mysql_query ($query) or die('Problem with query:' . $query . '<br/>' . mysql_error()); while($row=mysql_fetch_array($result)){ //echo $row[0]; } $answer = $row[0]; $guess = $description[$counter]; if($answer==$guess){ $score++; } $row[0] = ""; }// end loop echo $score; mysql_close(); [/code] Any ideas why this might be happening?
  14. Just tried to post my code on the help forum and get the same error :-(
  15. Thanks for that. I thought i'd managed to break something this end.
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.