简体   繁体   中英

Validate the username in Edit form while id is gone when the Edit form is submitted

require_once "../config.php";

#Editing user's Id
if(isset($_GET['id'])){
    $id = $_GET['id'];
    $queryT = "SELECT * FROM teachers WHERE t_id = $id";
    $results = mysqli_query($link, $queryT);
    $myRow = mysqli_fetch_array($results);
}

$userName = htmlspecialchars($_POST['username']);

if(isset($_POST['submit'])){
if(empty($userName)){
        $userNameErr = "<span>Username is required!.</span>";
    }elseif($rowcount == 1 AND $userName != $myRow['username']){
        $userNameErr = "<span>That username is taken!.</span>";
    }

it all went well but when i submit the edited form the previous Get id fades and $myRow['username'] becomes undefined variable

You can test whether the index is set with if (isset($myRow['username']))

And you should always declare a variable in the scope that you want to use it. Php is not strict so that means you have to be.

$myRow = [];

if(isset($_GET['id'])){
    $id = $_GET['id'];
    $queryT = "SELECT * FROM teachers WHERE t_id = $id";
    $results = mysqli_query($link, $queryT);
    $myRow = mysqli_fetch_array($results);
}

To preserve the get variable you can store it in a hidden field of your form and do something like

$id = (isset($_GET['id'])  
    ? $_GET['id'] 
    : isset($_POST['id']) 
        ? $_POST['id'] 
        : 0;
if($id !== 0){
    $queryT = "SELECT * FROM teachers WHERE t_id = $id";
    $results = mysqli_query($link, $queryT);
    $myRow = mysqli_fetch_array($results);
}

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