Jump to content

I must be using the mysql_fetch_array wrong, any help?


EricOnAdventure

Recommended Posts

This is my login page, and as you can see I am trying to make sure people are logged in, and have paid. but I am getting nothing from my mysql_fetch_array lines related to payment and givenname. Any advice?

<?php
    
$studentname =filter_var($_POST['Username'], FILTER_SANITIZE_SPECIAL_CHARS);
$psw =filter_var($_POST['Password'], FILTER_SANITIZE_SPECIAL_CHARS);
session_start();
require_once 'dbstart.php';
require_once 'functionhome.php';

$link  =  mysql_connect ( $servername ,  $username ,  $password )
    or die( 'Could not connect: '  .  mysql_error ());

 mysql_select_db ( $dbname ) or die( 'Could not select database' );


 $query  =  "SELECT * FROM $mylogin where
 studentname='$studentname'
 and psw='$psw'
  " ;
 $result  =  mysql_query ( $query ) or die( 'Query failed: '  .  mysql_error ());

 if ( $line  =  mysql_fetch_array ( $result ,  MYSQL_ASSOC )) {
  $res=true;
 
  if (!isset(mysql_fetch_array($result, MYSQL_ASSOC)['payment'])){
          $_SESSION['login'] = "Payment has not yet been confirmed. If you have paid and you are still getting this message please wait 24 hours. If you are still getting this message please <a href='contact.html'>Contact Us</a>. ";
        header("location: login.php");
  }
 
   
$GIVENNAME = mysql_fetch_array($result, MYSQL_ASSOC)['givenname'];
 
 
$_SESSION['post']['GIVENNAME'] = capitalize($GIVENNAME);
          //header("location: members.php");
        echo $GIVENNAME;
        echo $_SESSION['post']['GIVENNAME'];
echo "<pre>". print_r(mysql_fetch_array). "</pre>";
 
 
 
 }else {
    $res=false;
        
        $_SESSION['login'] = "Error, Username or Password incorrect, try again. ";
        header("location: login.php");
}

 mysql_free_result ( $result );

 mysql_close ( $link );    
 
 
Link to comment
Share on other sites

You are using obsolete MySQL code that has been completely removed from PHP. You need to use PDO with prepared statements.

 

You also do not want to output server errors to the user. What is the user supposed to do with a server error message? It is also a security risk.

Edited by benanamen
Link to comment
Share on other sites

Since you are assigning mysql_fetch_array to $line, you can do $line['givenname']

 

 

$GIVENNAME = $line['givenname'];

 

the same goes for payment.

 

seriously, though.  use mysqli functions instead of mysql.  It's a one letter difference that literally updates your code.

Link to comment
Share on other sites

Ok, I did as you said and learned my_sqli, and changed my code, lots of hard work and I still ran into a problem. The $query fails...any idea?

<?php
	

$code =filter_var($_POST['code'], FILTER_SANITIZE_SPECIAL_CHARS);
session_start(); 

if( $code!=$_SESSION['code'] )
{
		$_SESSION['signup'] = "Your Captcha wasn't correct. ";
		header("location: signup.php");	
}
////////////
require_once 'dbstart.php';
////////////
if (isset($_POST['GIVENNAME'])){
    if (empty($_POST['GIVENNAME'])
	|| empty($_POST['FAMILYNAME'])
	|| empty($_POST['STUDENTTITLE'])
	|| empty($_POST['STUDENTEMAIL'])
	|| empty($_POST['PAYMENT'])
	|| empty($_POST['DEGREETYPE'])
	|| empty($_POST['USERNAME'])
	|| empty($_POST['PASSWORD'])){
        

		$_SESSION['signup'] = "Mandatory field(s) are missing, Please fill it again";

		header("location: signup.php");
    
}
////////////////
		$GIVENNAME = $_POST["GIVENNAME"];
		$FAMILYNAME = $_POST["FAMILYNAME"];
		$STUDENTTITLE = $_POST["STUDENTTITLE"];
		$STUDENTEMAIL = $_POST["STUDENTEMAIL"];
		$PAYMENT = $_POST["PAYMENT"];
		$USERNAME = $_POST["USERNAME"];
		$PASSWORD = $_POST["PASSWORD"];
		$DEGREETYPE = $_POST["DEGREETYPE"];
		$STUDENTWECHAT = $_POST["STUDENTWECHAT"];
		
		$GIVENNAME = mysqli_real_escape_string($db, $GIVENNAME);
		$FAMILYNAME = mysqli_real_escape_string($db, $FAMILYNAME);
		$STUDENTTITLE = mysqli_real_escape_string($db, $STUDENTTITLE);
		$STUDENTEMAIL = mysqli_real_escape_string($db, $STUDENTEMAIL);
		$PAYMENT = mysqli_real_escape_string($db, $PAYMENT);
		$USERNAME = mysqli_real_escape_string($db, $USERNAME);
		$PASSWORD = mysqli_real_escape_string($db, $PASSWORD);
		$PASSWORD = md5($PASSWORD);
		$DEGREETYPE = mysqli_real_escape_string($db, $DEGREETYPE);
		$STUDENTWECHAT = mysqli_real_escape_string($db, $STUDENTWECHAT);

		/////email check
		$sql="SELECT STUDENTEMAIL FROM mylogin WHERE STUDENTEMAIL='$STUDENTEMAIL'";
		$result=mysqli_query($db,$sql);
		$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
		if(mysqli_num_rows($result) == 1)
		{
		$_SESSION['signup'] = "Email already in use, try again. ";
		header("location: signup.php");
		}
		///////usercheck
		$sql2="SELECT USERNAME FROM mylogin WHERE USERNAME='$USERNAME'";
		$result2=mysqli_query($db,$sql2);
		$row2=mysqli_fetch_array($result2,MYSQLI_ASSOC);
		if(mysqli_num_rows($result2) == 1)
		{
		$_SESSION['signup'] = "Username already in use, try again. ";
		header("location: signup.php");
		}	
		else
		{
			$query = mysqli_query($db, "INSERT INTO mylogin 
(GIVENNAME, FAMILYNAME, STUDENTTITLE, STUDENTEMAIL, STUDENTWECHAT, PAYMENT, USERNAME, PASSWORD)
VALUES 
('$GIVENNAME', '$FAMILYNAME','$STUDENTTITLE','$STUDENTEMAIL','$STUDENTWECHAT','$PAYMENT','$USERNAME','$PASSWORD')
");

			if($query)
			{
				        $_SESSION['post']['PAYMENT'] = $PAYMENT;
						header("location: payment.php"); 
			}
			else 
			{
			$_SESSION['signup'] = "Something failed, please try again. ";
			//header("location: signup.php"); 
			echo 'failed';
			}	
		}
	}

?>


	

	
Link to comment
Share on other sites

here are three important things to do when learning php, developing php code, debugging php code, or asking for help with php code -

 

1) we are not sitting there with you. we don't know what you saw that leads you to believe that something didn't work. you mentioned that the $query fails, but you didn't state what error/message or symptom you got that leads you to believe that it failed. tell us exactly what did happen.

 

2) you need to set php's error_reporting setting to E_ALL and the display_errors setting to ON, in the php,ini on your development system, to get php to report and display ALL the errors it detects. putting these two settings into your code won't help with syntax errors in your main file since your code never runs in this case. you should also turn off php's output_buffering setting in the php.ini, since it hides problems in your code and you should only use output_buffering when you want to buffer output.

 

3) your code needs to ALWAYS test for and handle errors that can occur with statements. When developing and debugging code, you would display the errors, when running code on a live server, you would log the errors. by testing for and handling errors, your code will tell you when, where, and give you information about why it is failing.

 

if the error you are getting is your 'failed' message, having error handling in your code for the database statements would tell you why the query failed.

 

in one of your previous threads, you were told to use msyql_error() to get query error information. wouldn't that same advice apply, but using the equivalent mysqli statement? note: mysqli_error(....) statement requires the db connection link as a parameter.

 

the type of error handling you can use is dependent on what sort of statements you are using. the best choice is to use exceptions to handle errors. the mysqli statements you are using do support exceptions. assuming you have set php's error settings as suggested above, add the following two lines of code before you make a database connection, so that a connection error will also throw an exception - 

$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL; // <--- w/index checking; w/o index checking ---> MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT;

this will throw uncaught exceptions for the msyqli statements. with the php error settings that have been suggested, php will report and display the error information. on a live server, you would instead log the error information.

 


 

if i/others have time, i/we will make a list of things your code needs to do or do differently.

 

 

Edited by mac_gyver
Link to comment
Share on other sites

MaC_Gyver

Great info, the Mysqli report mode helps but I still ran into an issue.  My new problem is this:

 

Fatal error: Uncaught exception 'mysqli_sql_exception' with message 'Unknown column 'STUDENTEMAIL' in 'field list'' in C:\xampp\htdocs\efun\signupv.php:80 Stack trace: #0 C:\xampp\htdocs\efun\signupv.php(80): mysqli_query(Object(mysqli), 'SELECT STUDENTE...') #1 {main} thrown in C:\xampp\htdocs\efun\signupv.php on line 80

 

The problem is in the line

$sql="SELECT STUDENTEMAIL FROM mylogin WHERE STUDENTEMAIL='$STUDENTEMAIL'";

I'm not sure if I am doing this right, or why else the error might exist.

As for your questions,

1. Before you sent me the error reporting code I only knew it was failing because of the echo fail at the bottom.

2. error reporting is on for PHP, by default.
 

Link to comment
Share on other sites

first, here's a list of things to consider -

 

1) all the form processing code needs to be inside the conditional statement that controls the execution of the form processing logic - if(isset($_POST['some_field_name_here'])){ all form processing code goes here... }

 

2) you should test a (hidden) form field that uniquely identifies, either by field name or the value in a field, which form submitted to the form processing code.

 

3) if the current visitor is already logged in, you would skip/prevent displaying the registration form and processing the registration form data

 

4) avoid using the _once form of the require statement. your code should be organized, so that you know when and where it is requiring files and you don't need to use the _once form. php has also had a number of bugs with the include path and correctly resolving the actual file so that the _once part actually works one time.

 

5) i recommend NOT using UPPERCASE for most things in your code and database queries, i.e. your form field names and database column names should be lower case. only use uppercase when you are calling attention to something. a convention is to use uppercase for defined constants, so that they stand out from any code/text they are surrounded by, and for parts of sql query syntax, i.e. SELECT, FROM, WHERE, ...

 

6) all your header() redirects need an exit; statement after them to prevent the code from continuing to run. the header() doesn't stop program execution.

 

7) you should use an array to hold validation error messages. this will let your code detect and display more than one validation error at a time. if only some of the required form fields are empty, one of the other fields doesn't contain an expected value, and the username or email is already in use, you would want to display all these errors at once.

 

8) the captcha check should make sure that there is a $_SESSION['code'] value and that it's not empty

 

9) you should validate each 'required' input to insure that it contains either an expected/permitted value or format.

 

10) you should produce a separate and unique validation error message for each possible validation problem, i.e. don't combine all the empty() checks into one message.

 

11) you should trim all input data before using it. this will eliminate leading/trailing white-space characters. if you want to allow leading/trailing white-space characters as part of a password, exclude that from what you trim or get an untrimmed copy of the original $_POST data when using the password value.

 

12) your current code requires the captcha to match before doing any other processing. after making the suggested changes, it should still do that and skip all other processing, even the database connection, if it doesn't match.

 

13) whenever possible, dynamically process sets of data. your form fields are a set of data. you should avoid writing out line after line of code, repeated for each different form field. because the $_POST data is an array, you can use php's array functions on it when performing the same operation on each field. to do this, you would make an array of the form field names, then loop over this defining array and access the corresponding post data. you can expand on this and dynamically produce the form by including things like the form field type, label for the field, ... in the defining array.

 

14) only escape data right before using it in an sql query statement (or even better, use a prepared query with bound input parameters.)

 

15) it's unfortunate that you picked the mysqli extension, rather than the PDO extension. the PDO extension is more constant, easier to use, and has fewer gotchas then the msyqli extension, especially if using prepared queries.

 

16) running a SELECT query to test if the username/email is already in use allows a race condition where concurrent visitors can try to INSERT the same values. the fix for this is to have those two column defined as UNIQUE indexes, then just run the INSERT query and use the duplicate key index error information that will occur to tell the visitor that the username or email is already in use. the duplicate key error will report the first key that's duplicated, so, if someone does happen to repeat both values, it will take two form submission to detect this OR you could run a SELECT query after the INSERT query to find which or both of the values are duplicated.

 

17) if you put the form processing code and the form on the same page, it will eliminate all the session variables/header() redirects. the only place you would need a header() redirect is after you have successfully (no errors) processed the form data. you will also be able to repopulate the form fields (except you shouldn't repopulate the password field) when there is a validation error, rather the require the visitor to keep typing in the same information over and over.

 

18) after successfully, no errors, processing the form data, you should do a header() redirect to the exact same url that the form submitted to. this will cause a get request for the page, which will prevent the brower from throwing an error or trying to resubmit the form data if you reload the page or browse back to the url of the page.

 

 

as to why your db column name in your sql query statement doesn't match your table definition, i'm betting that your actual db column name isn't spelled exactly as you are using it in the sql query statement.

Link to comment
Share on other sites

afaik, only database names and table names are ever case sensitive, on case sensitive operating systems. column names are not and referencing a column in a query using a letter case that doesn't match doesn't throw a query error (it would be a problem when trying to fetch the data since the actual column name letter case is what would be present in the data.)

 

what does the result of running the query - SHOW CREATE TABLE `mylogin` produce?

 

add the following to the list above -

 

19) you should be using php's password_hash() and password_verify() for hashing/testing the hashed password.

Edited by mac_gyver
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.