简体   繁体   中英

Updating html after php call to a stand-alone php file

I am trying to implement a user login system for my website. I have a newMember.html file that has a form like this:

<form method="post" action="nameValidation.php">
    <p>Username:</p>
    <input type="text" name"user" required>
    <input name="submitButton" type="submit" value="Create account"/>
</form>

inside nameValidation, I check if the username is available. If it's not, i want some way to show a red text next to my input field where you type in your username. I tried something like this, but got a server error:

(inside nameValidation.php)

<?php
    //connect to database, check the value of the username to see if it exists
    if (username already exists) {
        //keep the page that i had the way it was, 
        //just add a red sentence saying "username is already taken"
    }
    else {
       //tell the user he was successful in making an account,
       //and redirect him to my login page (already implemented)
    }       
?>

I didn't want to use inline php for two reasons.

1) it looks cluttered and confusing (at least to me)

2) I read in other stackoverflow posts that it's not good practice.

I will use inline php if i have to, but any and all help will be greatly appreciated!

Use a web framework like CakePHP , Laravel , Symfony or any other framework that suits you.

A PHP framework uses templates to accommodate dynamic pages. They usually allow special shortcuts in your code, so that you do not have to write any 'inline PHP'.

This is the MVC (Model View Controller) mentality: the controllers control the actual data being used in your view, and not the view.


Enough about web frameworks.

To answer your question, first rename your file to end in .php , to show that the file contains PHP.

Next, edit the code such that it checks if a user exists. The most beautiful inline PHP code gets created by doing all the work at the top of the page, and using the generated data in the page itself.

So, for your HTML:

<?php

/* For example: */
$username = $_POST['username'];
$db = new DB(/* ... */);
$userNameExists = $db -> userNameExists ($username);

?>

<!-- The rest of the code of the page -->

<form method="post" action="nameValidation.php">
    <p>Username:</p>
    <input type="text" name"user" required value="<?php echo $username; ?>"><?php echo $userNameExists ? '<span class="error">Username already exists</span>' : '' ?>
    <input name="submitButton" type="submit" value="Create account"/>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM