0

我对php有点新,所以我需要帮助。在一个页面上,我有一个带有名字和姓氏字段的小表格。在提交时,我将其发送到外部 .php 脚本,我想在其中检查数据库中是否已经存在同名的人。如果数据库中已经有输入姓名的人,我想取消写入数据库,并返回html页面。我已经这样做了,但是我想显示 JS 消息框“具有此名称的人已经存在于 db 中!”,并且如果取消了对基础的写入,我希望我的输入字段显示最后写入的值。我读了很多文学作品,我迷路了。无论如何感谢您的帮助:)

这是我的表格:

<form name="form" action="write.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
<input type="submit">
</form>

我的PHP代码:

<?php
$con=mysqli_connect("localhost","root","","phptest");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if (isset($_POST['firstname'])) { 
$firstname = $_POST['firstname'];
}
if (isset($_POST['lastname'])) { 
$lastname = $_POST['lastname'];
}
$duplicate=mysqli_query($con,"SELECT * FROM persons WHERE FirstName='$firstname'");
if(mysqli_num_rows($duplicate)>0)
{
die('Name already exists' );//I want that this message shows in html file, as alert
}
else{
$sql="INSERT INTO Persons (FirstName, LastName)
VALUES('$firstname','$lastname')";
$result=mysqli_query($con,$sql);
if (!$result)
{
die('Error: ' . mysqli_error());
}
}
header( 'Location://localhost/ivanda.php' ) ;
mysqli_close($con);

?>
4

1 回答 1

-1

这一行:

if(mysqli_num_rows($duplicate)>0)
{
die('Name already exists' );//I want that this message shows in html file, as alert
}

将其更改为此代码:

if(mysqli_num_rows($duplicate)>0)
{
echo "<script>alert('Name already exist!!!'); </script>";
echo "<script>window.location.assign('ivanda.php'); </script>"; //add this line instead of header


}

-------------------------已编辑------------------------ ----------

试试这个:

    $duplicate=mysqli_query($con,"SELECT * FROM Persons WHERE FirstName='$firstname' limit 1");
    if(mysqli_num_rows($duplicate)>0)
    {

    $row = mysqli_fetch_assoc($duplicate);

    echo "<script>alert('Name already exist!!!'); </script>";
    echo "<script>window.location.assign('ivanda.php?firsName=".$row['FirstName']."&lastName=".$row['LastName']."'); </script>"; //add this line instead of header

    }
    else{
    $sql="INSERT INTO Persons (FirstName, LastName)
    VALUES('$firstname','$lastname')";
    $result=mysqli_query($con,$sql);
    if (!$result)
    {
    die('Error: ' . mysqli_error());
    }
    }

有了这个,您将通过 GET 在 url 上发送 var ...然后在您的表单中,您应该有如下内容:

<form name="form" action="write.php" method="post" onSubmit="return Validate()">
Firstname: <input type="text" name="firstname" value="<?php if(isset($_GET['firsName'])){echo $_GET['firsName'];} ?>">
Lastname: <input type="text" name="lastname" value="<?php if(isset($_GET['lastName'])) {echo $_GET['lastName'];} ?>">
<input type="submit">
</form>

PS:去 mysqli o PDO,记住它...mysql 扩展很快就会被弃用

萨卢多斯。

于 2013-03-25T20:10:34.047 回答