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

必须按下按钮才能激活php代码?

必须按下按钮才能激活php代码?

PHP
千万里不及你 2022-08-05 16:07:01
因此,该网站的想法是,当您按下按钮时,它会从数据库中删除相应的行。但是,我的代码的问题在于,在第一次按下按钮后,按钮将填充id变量,然后在下次按下时执行php。我该如何避免这种情况,并让他php适合并在第一次按下按钮时执行php?包括嵌入了php的HTML页面:<!doctype html><html><head><meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1">  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script><title>Untitled Document</title>    <style>table {  font-family: arial, sans-serif;  border-collapse: collapse;  width: 100%;}td, th {  border: 1px solid #dddddd;  text-align: left;  padding: 8px;}tr:nth-child(even) {  background-color: #dddddd;}</style></head><body>    <div class="container-fluid">    <h2 style"text-align:center";>Please enter the item you want to add to the list below </h2><?php$servername = "localhost";$username = "root";$password = "";$dbname = "myDB";$sql = "CREATE DATABASE myDB";$conn = new mysqli($servername, $username, $password, $dbname);if ($conn->connect_error) {    die("Connection failed: " . $conn->connect_error);} $sql = "CREATE TABLE freezerinventory (id INT AUTO_INCREMENT PRIMARY KEY, item VARCHAR(30) NOT NULL,reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)";if(isset($_POST['itemx'])) {$itemvar = $_POST["itemx"];$sql = "INSERT INTO freezerinventory (item)VALUES ('$itemvar')";    $add =  mysqli_query($conn, $sql);}else {    $sql = "";}
查看完整描述

3 回答

?
烙印99

TA贡献1829条经验 获得超13个赞

您可以创建单独的处理脚本,并将表单提交到按钮的 URL 路径“onClick”。不能使用 JS 代码直接调用 PHP 函数。


查看完整回答
反对 回复 2022-08-05
?
忽然笑

TA贡献1806条经验 获得超5个赞

PHP是一种仅在服务器端运行的语言。它不同于在客户端(浏览器上)运行的javascript。

如果您可能注意到,您将永远不会在其他网站上看到PHP代码,因为(如果网站使用PHP)它是在服务器端处理的,并且返回的只是HTML + CSS。

如今,我们不会创建这样的页面。我们将使用PHP创建我们所谓的API。我们将使用 REST-API 策略。

假设我们将在此地址上托管此 APIwww.mywebsite.com/myapi/myfreezerendoint.php

我们将使用JS请求或发布到这个端点,并使用名为.fetch("www.mywebsite.com/myapi/myfreezerendoint.php", { ... })

我发现了这个关于以MySQL为数据库的PHP API的有趣教程:https://webdamn.com/create-simple-rest-api-with-php-mysql/


查看完整回答
反对 回复 2022-08-05
?
largeQ

TA贡献2039条经验 获得超7个赞

我已经纠正和美化了所有代码,最小化了它,现在应该是它:


<?php

$servername = "localhost";

$username = "root";

$password = "";

$dbname = "myDB";

$sql = "CREATE DATABASE myDB";


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

if ($conn->connect_error) {


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

$sql = "CREATE TABLE freezerinventory (

id INT AUTO_INCREMENT PRIMARY KEY, 

item VARCHAR(30) NOT NULL,

reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)";


if(isset($_POST['itemx'])) {

  $itemvar = $_POST["itemx"];

  $stmt = $conn->prepare("INSERT INTO freezerinventory (item) VALUES ('?')");

  $stmt->bind_param("s", $itemvar);

  $stmt->execute();

} else {

    //the 'itemx' post parameter isn't set, make an alert or something

}

mysqli_close($conn);

?>

<!doctype html>

<html>

  <head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

    <title>Untitled Document</title>

    <style>

      table {

        font-family: arial, sans-serif;

        border-collapse: collapse;

        width: 100%;

      }


      td, th {

        border: 1px solid #dddddd;

        text-align: left;

        padding: 8px;

      }


      tr:nth-child(even) {

        background-color: #dddddd;

      }

    </style>

  </head>

  <body>

    <div class="container-fluid">

    <h2 style"text-align:center";>Please enter the item you want to add to the list below </h2>

<form action="<?php echo $_SERVER["PHP_SELF"];?>" class="needs-validation" novalidate method="post">


    <div class="form-group">

      <label for="uname"></label>


      <input type="text" class="form-control" id="itemx" placeholder="Enter an item for the freezer here" name="itemx" required>


      <div class="valid-feedback">Valid.</div>


      <div class="invalid-feedback">Please fill out this field.</div>


    </div>


    <button id = "SubmitButton" name = "SubmitButton" type="button submit" class="btn btn-primary">Add to list</button>

</form>

    </div>

<?php


$servername = "localhost";

$username = "root";

$password = "";

$dbname = "myDB";

$aVar = mysqli_connect('localhost','root','','myDB');



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


if ($conn->connect_error) {

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


if(isset($_POST['id'])) {

  $delete = $con->prepare("DELETE FROM freezerinventory WHERE id= ?");

  $delete->bind_param("s", $_POST['id']);

  $delete->execute();

}


$sql = "SELECT * FROM freezerinventory";

$result = mysqli_query($aVar, $sql);

echo "<table><tr>

    <th>Item name</th>

    <th>Date added</th> 

    <th>remove</th>

  </tr>    "; 


while($row = mysqli_fetch_array($result))   {

  echo "      <tr><td>" . $row['item'] . "</td><td>" . $row['reg_date'] . "</td><td><form action='' method='POST'>

    <div class= 'input-group' > <div class='input-group-append'>

        <button class='btn btn-danger'  onclick='deleteitem(".$row['id'].")' id='delete'>Remove</button>

        <input type='hidden' name='id'/>

    </div></div>

    </form></td></tr>";

}

    echo "</table>";

?>

<script>

function deleteitem (id_data) {

  $.post('<?php echo $_SERVER["PHP_SELF"];?>', {id: id_data}, function(data) {

    console.log(data);  //callback data

  });

}


function myFunction() {

  confirm("I am an alert box!");

}


(function() {

  'use strict';

  window.addEventListener('load', function() {


    // Get the forms we want to add validation styles to


    var forms = document.getElementsByClassName('needs-validation');


    // Loop over them and prevent submission


    var validation = Array.prototype.filter.call(forms, function(form) {

      form.addEventListener('submit', function(event) {

        if (form.checkValidity() === false) {

          event.preventDefault();

          event.stopPropagation();

        }

        form.classList.add('was-validated');

      }, false);

    });

  }, false);

})();

</script>

</body>

</html>

它可能仍然需要一些修复,我在那里留下了一些未使用的html元素,但从理论上讲,这应该有效。它利用 将数据发送到 。您不必使用,但从理论上讲,这应该可以解决您的问题。如果您遇到任何问题,请在我的答案下发表评论。ajaxphpajax


注意:只是为了澄清,我没有尝试这样做,因此可能存在一些错误。


查看完整回答
反对 回复 2022-08-05
  • 3 回答
  • 0 关注
  • 139 浏览

添加回答

举报

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