Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    May 2019
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    getElementByID not working with PHP through function

    I'm working on a form right now in PHP and when a user tries to register a user as an already registered username, I want to then show the data in my table>tr>th>td data. Or change the data at least. Here is my code:
    Script tag at top of the page in header

    Code:
    <script src = "js/myScript.js"></script>
    filepath:

    js/myScript.js

    js function:

    Code:
    function UserTaken(){
    	document.getElementById("userTaken").innerHTML = "That username is taken..";
    }
    phpcode:
    Code:
    if(isset($_POST['username'])){//if the username is set
    							$sql = "SELECT username FROM user WHERE 1;";
    							$checkuser = mysqli_query($con, $sql);
    					
    							while($row = mysqli_fetch_assoc($checkuser)){//check for same username
    									if($_POST['username'] == $row['username']){//if a username is found in the database
    										echo "<script type = 'text/javascript' >
    											 UserTaken();
    											</script>";
    ;
    										$handle[] = "Error 4: User is taken";
    									}
    							}
    						}

  2. #2
    New to the CF scene
    Join Date
    May 2019
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts
    This is my form:

    Code:
    	<form action = "register.php" method = "POST">
    					<table>
    					<tr><th><p>Username       		    </th><th> <input type = "text"      name = "username"  size="15" maxlength="25"/><td id = 'userTaken'>fg</td></th></tr>
    					<tr><th><p>Password &nbsp; 		   	</th><th> <input type = "password"  name = "password"  size="15" maxlength="50"/><td id = 'IncorrectPassword'>fg</td></th></tr>
    					<tr><th><p>Confirm Password &nbsp; 	</th><th> <input type = "Cpassword" name = "Cpassword" size="15" maxlength="50"/><td id = 'IncorrectPassword'>fg</td></th></tr>
    						
    						
    						<th><br><p><input name = "submit" type = "submit"   name = "submit"   value = "Register"/></th></tr>
    					</table>
    				</form>

  3. #3
    Senior Coder deathshadow's Avatar
    Join Date
    Feb 2016
    Location
    Keene, NH
    Posts
    3,504
    Thanks
    4
    Thanked 503 Times in 491 Posts
    You fail to close your P, what makes what should be LABEL's be paragraphs, you have excess whitespace that many browsers will ignore your attributes for (the extra spaces around the = are not a HTML thing), and what makes LABEL and INPUT be tabular data?

    Much less, why the blazes is this any of JavaScript's business? You want the form to not tell people why it was rejected?

    Also "WHERE 1" is always true, so why is that in the query? Why aren't you checking for the username in the query instead of pulling every Joe-blasted user wasting memory and processing time?!? Do it in the query, retrieving COUNT (which is faster than pulling the actual row)...


    So something like:

    Code:
    $errors = []; // so we can store any errors for display.
    
    if (
    	array_key_exists('password', $_POST) &&
    	array_key_exists('confirmPass', $_POST) &&
    } {
    	if ($_POST['password'] != $_POST['confirmPass'])
    		$errors['confirmPass'] = 'Passwords do not match';
    } else $errors['confirmPass'] = 'You must enter a password';
    
    if (array_key_exists('username', $_POST)) {
    	if (!$errors) { // no sense in doing this if no password
    		$stmt = $con->prepare('
    			SELECT COUNT(*)
    			FROM user
    			WHERE username = ?
    		');
    		$stmt->bind_param('s', $_POST['username']);
    		$stmt->execute();
    		$stmt->bind_result($count);
    		if (!($stmt->fetch() && $count)) $errors['username'] = 'Error 4, Username is taken';
    	}
    } else $errors['username'] = 'You must enter a username';
    Mind you in production you may want to check for things like username length and password complexity.

    With the form /template being along the lines of this:

    Code:
    function template_registerInput($name, $label, $errors, $showPost = false) {
    
    	echo '
    			<label for="register_', $name, '">', $label, '</label>
    			<input
    				type="text"
    				name="', $name, '"
    				id="register_', $name, '"';
    			
    	if ($showPost && array_key_exists($name, $_POST)) echo '
    				value="', htmlspecialchars($_POST[$name]), '"';
    			
    	echo '
    			>';
    	
    	if (array_key_exists($name, $errors)) echo '
    			<span class="error">', $errors[$name], '</span>';
    			
    	echo '
    			<br>';
    
    } // template_registerInput
    
    function template_register($errors) {
    
    	echo '
    		<form action="register.php" method="post" id="register">
    			<fieldset>
    				<legend>Register New Account</legend>';
    				
    	template_registerInput('username', 'Username', $errors, true);
    	template_registerInput('password', 'Password', $errors);
    	template_registerInput('confirmPass', 'Confirm Password', $errors);
    	
    	echo '
    				<button>Register</button>
    			</fieldset>
    		</form>';
    		
    } // template_register
    If you don't like how hard LEGEND is to style, use the appropriate depth heading. Anything else you want done for appearance -- such as columns -- goes in the CSS, not the markup. HTML exists to say what things are grammatically, structurally and semantically, NOT for saying what things look like. Hence "tables for layout" being "bad".

    Now, that said, if this is actually a registration form, I'd be handling the creation of the user and/or rejection by name in the query, NOT as separate queries. Just make sure username is UNIQUE in the table, then:

    Code:
    $errors = []; // so we can store any errors for display.
    
    if (
    	array_key_exists('password', $_POST) &&
    	array_key_exists('confirmPass', $_POST) &&
    } {
    	if ($_POST['password'] != $_POST['confirmPass'])
    		$errors['confirmPass'] = 'Passwords do not match';
    } else $errors['confirmPass'] = 'You must enter a password';
    
    if (!array_key_exists('username', $_POST)) {
    	$errors['username'] = 'You must enter a username';
    } else if (!$errors) { // no sense in doing this if no password
    		$stmt = $con->prepare('
    			INSERT INTO user (
    				username, password
    			) VALUES (
    				?, ?
    			)
    		');
    		$pass = hash('sha512', $_POST['password']);
    		$stmt->bind_param('ss', $_POST['username'], $pass);
    		$stmt->execute();
    		if ($stmt->errNo) $errors['username'] = (
    			$stmt->errNo == 1062 ?
    			'Error 4, Username is taken' :
    			'There was an unexpected database error, try again.'
    		);
    	}
    }
    
    // do whatever else you need to check here.
    
    if ($errors) { // remember, empty array == loose false
    	template_register(); // call the form
    } else {
    	// user was created, do normal "user created' page here.
    }
    One query to do the verify AND the creation. Error 1062 is duplicate field, so as long as 'username' is the only unique field in the table we would try to assign values to, that's all we need to check.

    Either way, none of this is anything that has any real business being done in client side scripting.

    Warning, drive-by post during insomnia, may be typos in code.
    Last edited by deathshadow; May 5th, 2019 at 10:49 AM.
    “There are two ways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies and the other way is to make it so complicated that there are no obvious deficiencies.” – C.A.R. Hoare, The 1980 ACM Turing Award Lecture
    http://www.cutcodedown.com


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •