Help with mysqli_fetch_array()

I could use some help understanding how mysqli_fetch_array() works.

Let’s say I have this query in my PHP…


	// Check if Email and Username are available.
	$q = "SELECT email, username
			FROM users
			WHERE email = '$e' OR username = '$u'";
	$r = mysqli_query($dbc, $q);

And later on I have this code:


	// One or both may be taken.
	$row = mysqli_fetch_array($r, MYSQLI_NUM);
	if(($row[0] == $_POST['email']) && ($row[1] == $_POST['username'])){
	}

To make the code clearer to me, could I change it to this?


	// One or both may be taken.
	$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
	if(($row[email] == $_POST['email']) 
		&& ($row[username] == $_POST['username'])){
	}

I guess my question is, “Can you assign the key a value in the array or does that have to be assigned when it is created?”

Debbie

Hi Debbie,

Not exactly, you could change it to this…


// One or both may be taken.
    $row = mysqli_fetch_array($r, MYSQLI_ASSOC);
    if(($row['email'] == $_POST['email'])
        && ($row['username'] == $_POST['username'])){
    }

Ideally though, you should just check the number of ‘rows’ returned.


<?php
// Check if Email and Username are available.
    $q = "SELECT email, username
            FROM users
            WHERE email = '$e' OR username = '$u'";
    $r = mysqli_query($dbc, $q);
    
    if(0 < mysqli_num_rows($r)){
      #taken
    }

Well, Anthony, since you offered some coding improvements, how about looking at the entire code segment?! :smiley:

(I think what the author did is loopy?!)

If you don’t mind, see if you can follow his IF-THE-ELSE logic…


		// Check for form errors.
		if (empty($reg_errors)){
			// No form errors.
			// Check if Email and Username are available.
			$q = "SELECT email, username
						FROM users
						WHERE email = '$e' OR username = '$u'";
			$r = mysqli_query($dbc, $q);
			$rows = mysqli_num_rows($r);
			if ($rows == 0){
				// No records found.
				// Email and Username are available.
				
				// Build query.
				$q2 = "INSERT INTO users(username, email, pass, first_name, last_name, date_expires)
							VALUES('$u', '$e', '" . get_password_hash($p)
											. "', '$fn', '$ln', SUBDATE(NOW(), INTERVAL 1 DAY))";
				
				// Add User to the database.				
				$r2 = mysqli_query($dbc, $q);
				
				// The user's type does not need to be set because if no value is
				// provided for an ENUM column, then the first enumerated value
				// (i.e. "member") will be used.
				
				// As a security measure, the User-Type can only ever be "member",
				// after going through Registration.  To create an "administrator",
				// this must be done manually in the back-end database.
				
				// Check if User was added.
				if (mysqli_affected_rows($dbc) == 1){
					// Insert was successful.
					
					// Get (auto_increment) ID generated during INSERT.
					$uid = mysqli_insert_id($dbc);
					
					// Assign User ID to the Session.
					$_SESSION['reg_user_id'] = $uid;
					
					// Display thank you message.
					echo '<h3>Thanks!</h3>
								<p>Thank you for registering!  To complete the process, 
								please now click the button below so that you may pay for 
								your site access via Pay Pal.  The cost is US$10 per year 
								<strong>Note: When you complete your payment at PayPal, 
								please click the button to return to this site.</strong></p>';
								
					// Add PayPal Payment Button.
					echo '<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
									<input type="hidden" name="cmd" value="_s-xclick">
									<input type="hidden" name="hosted_button_id" value="K5LLXSA7Z54YW">
									<input type="image" src="https://www.sandbox.paypal.com/en_US/i/btn/btn_subscribeCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
									<img alt="" border="0" src="https://www.sandbox.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
								</form>';
								
					// Create email body.
					$body = "Thank you for registering at <whatever site>.  Blah blah blah.\
\
";
					
					// Send registration confirmation email to User.
					mail($_POST['email'], 'Registration Confirmation', $body,
								'From: [email]admin@example.com[/email]');
								
					// Get Footer file.
					include ('includes/footer.html');
					
					// Stop page to prevent registration page from being shown again.
					exit();
				} else {
					// Insert failed.
					// There was either a database or query error.
					// Generate an error (using custom error-handler).
					trigger_error('You could not be registered due to a system error.
													We apologize for any inconvenience.');
				}
			} else {
				// Email or Username NOT available.
				if ($rows == 2){
					// BOTH Email and Username taken.
					$reg_errors['email'] = 'This email address has already been registered.
																	If you have forgotten your password, use the link
																	at the right to have your password sent to you.';
																	
					$reg_errors['username'] = 'This username has already been registered.
																		Please try another.';
				} else {
					// One or both may be taken.
					$row = mysqli_fetch_array($r, MYSQLI_NUM);
					if(($row[0] == $_POST['email']) && ($row[1] == $_POST['username'])){
						// Both match.
						$reg_errors['email'] = 'This email address has already been registered.
																		If you have forgotten your password, use the link
																		at the right to have your password sent to you.';
																		
						$reg_errors['username'] = 'This username has already been registered
																			with this email address.  If you have forgotten
																			your password, use the link at the right to have
																			your password sent to you.';
					} elseif ($row[0] == $_POST['email']){
						// Emails match.
						$reg_errors['email'] = 'This email address has already been registered.
																		If you have forgotten your password, use the link
																		at the right to have your password sent to you.';
					} elseif ($row[1] == $_POST['username']){
						$reg_errors['username'] = 'This username has already been registered.
																			Please try another.';
					}
				}
			} // END (Check if Email and Username available)

I’m not sure how to bold code inside the above code markup, but if you look for this block…


			} else {
				// Email or Username NOT available.
				if ($rows == 2){
					// BOTH Email and Username taken.
					$reg_errors['email'] = 'This email address has already been registered.
																	If you have forgotten your password, use the link
																	at the right to have your password sent to you.';
																	
					$reg_errors['username'] = 'This username has already been registered.
																		Please try another.';

…and then look down a little farther, you’ll see this…


				} else {
					// One or both may be taken.
					$row = mysqli_fetch_array($r, MYSQLI_NUM);
					if(($row[0] == $_POST['email']) && ($row[1] == $_POST['username'])){
						// Both match.
						$reg_errors['email'] = 'This email address has already been registered.
																		If you have forgotten your password, use the link
																		at the right to have your password sent to you.';
																		
						$reg_errors['username'] = 'This username has already been registered
																			with this email address.  If you have forgotten
																			your password, use the link at the right to have
																			your password sent to you.';

The second block seems totally redundant to me unless I’m missing something…

Debbie