猿问

在 PHP 问题中插入数据库中的按钮和函数记录

这是代码,不起作用 -


<form method="post">

    <input type="submit" name="zapis" id="zapisk" value="Запис" /><br/>

</form>


<?php


function zapisk()


{$servername = "localhost";

    $username = "test";

    $password = "";

    $dbname = "myDB";


// Create connection

    $conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

    if ($conn->connect_error) {

        die("Connection failed: " . $conn->connect_error);

    }


    $sql = "INSERT INTO MyGuests (firstname, lastname, email)

VALUES ('John', 'Doe', 'john@example.com')";


    if ($conn->query($sql) === TRUE) {

        echo "New record created successfully";

    } else {

        echo "Error: " . $sql . "<br>" . $conn->error;

    }


    $conn->close();

}

//{echo "Your test function on button click is working";}


//if(array_key_exists('zapis',$_POST)){zapisk();}


?>

如果我激活最后两行,此时作为评论,该功能将起作用。是否有可能,该功能可以在不使用最后两行的情况下工作。


HUWWW
浏览 103回答 1
1回答

天涯尽头无女友

zapisk提交表单时必须调用函数。<form method="post">&nbsp; &nbsp; <input type="submit" name="zapis" id="zapisk" value="Запис" /><br/></form><?phpfunction zapisk(){&nbsp; &nbsp; $servername = "localhost";&nbsp; &nbsp; $username = "test";&nbsp; &nbsp; $password = "";&nbsp; &nbsp; $dbname = "myDB";// Create connection&nbsp; &nbsp; $conn = new mysqli($servername, $username, $password, $dbname);// Check connection&nbsp; &nbsp; if ($conn->connect_error) {&nbsp; &nbsp; &nbsp; &nbsp; die("Connection failed: " . $conn->connect_error);&nbsp; &nbsp; }&nbsp; &nbsp; $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";&nbsp; &nbsp; if ($conn->query($sql) === TRUE) {&nbsp; &nbsp; &nbsp; &nbsp; echo "New record created successfully";&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; echo "Error: " . $sql . "<br>" . $conn->error;&nbsp; &nbsp; }&nbsp; &nbsp; $conn->close();}// Check form submitted and post has zapis value.&nbsp;if(!empty($_POST['zapis'])){&nbsp; &nbsp;zapisk();}?>或者您不使用函数并在 if 语句中编写代码:<form method="post">&nbsp; &nbsp; <input type="submit" name="zapis" id="zapisk" value="Запис" /><br/></form><?php// Check form submitted and post has zapis value.&nbsp;if(!empty($_POST['zapis'])){&nbsp; &nbsp; $servername = "localhost";&nbsp; &nbsp; $username = "test";&nbsp; &nbsp; $password = "";&nbsp; &nbsp; $dbname = "myDB";// Create connection&nbsp; &nbsp; $conn = new mysqli($servername, $username, $password, $dbname);// Check connection&nbsp; &nbsp; if ($conn->connect_error) {&nbsp; &nbsp; &nbsp; &nbsp; die("Connection failed: " . $conn->connect_error);&nbsp; &nbsp; }&nbsp; &nbsp; $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')";&nbsp; &nbsp; if ($conn->query($sql) === TRUE) {&nbsp; &nbsp; &nbsp; &nbsp; echo "New record created successfully";&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; echo "Error: " . $sql . "<br>" . $conn->error;&nbsp; &nbsp; }&nbsp; &nbsp; $conn->close();}?>
随时随地看视频慕课网APP
我要回答