为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
HUWWW 2023-05-26 17:32:21
这是代码,不起作用 -<form method="post">    <input type="submit" name="zapis" id="zapisk" value="Запис" /><br/></form><?phpfunction 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();}?>如果我激活最后两行,此时作为评论,该功能将起作用。是否有可能,该功能可以在不使用最后两行的情况下工作。
查看完整描述

1 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

zapisk提交表单时必须调用函数。


<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();

}


// Check form submitted and post has zapis value. 

if(!empty($_POST['zapis'])){

   zapisk();

}


?>



或者您不使用函数并在 if 语句中编写代码:


<form method="post">

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

</form>


<?php


// Check form submitted and post has zapis value. 

if(!empty($_POST['zapis'])){

    $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();


}


?>


查看完整回答
反对 回复 2023-05-26
  • 1 回答
  • 0 关注
  • 102 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信