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

因此,该网站的想法是,当您按下按钮时,它会从数据库中删除相应的行。但是,我的代码的问题在于,在第一次按下按钮后,按钮将填充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 = "";

}

千万里不及你
浏览 140回答 3
3回答

烙印99

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

忽然笑

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/

largeQ

我已经纠正和美化了所有代码,最小化了它,现在应该是它:<?php$servername = "localhost";$username = "root";$password = "";$dbname = "myDB";$sql = "CREATE DATABASE myDB";$conn = new mysqli($servername, $username, $password, $dbname);if ($conn->connect_error) {&nbsp; &nbsp; die("Connection failed: " . $conn->connect_error);}&nbsp;$sql = "CREATE TABLE freezerinventory (id INT AUTO_INCREMENT PRIMARY KEY,&nbsp;item VARCHAR(30) NOT NULL,reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)";if(isset($_POST['itemx'])) {&nbsp; $itemvar = $_POST["itemx"];&nbsp; $stmt = $conn->prepare("INSERT INTO freezerinventory (item) VALUES ('?')");&nbsp; $stmt->bind_param("s", $itemvar);&nbsp; $stmt->execute();} else {&nbsp; &nbsp; //the 'itemx' post parameter isn't set, make an alert or something}mysqli_close($conn);?><!doctype html><html>&nbsp; <head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1">&nbsp; &nbsp; <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">&nbsp; &nbsp; <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>&nbsp; &nbsp; <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>&nbsp; &nbsp; <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>&nbsp; &nbsp; <title>Untitled Document</title>&nbsp; &nbsp; <style>&nbsp; &nbsp; &nbsp; table {&nbsp; &nbsp; &nbsp; &nbsp; font-family: arial, sans-serif;&nbsp; &nbsp; &nbsp; &nbsp; border-collapse: collapse;&nbsp; &nbsp; &nbsp; &nbsp; width: 100%;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; td, th {&nbsp; &nbsp; &nbsp; &nbsp; border: 1px solid #dddddd;&nbsp; &nbsp; &nbsp; &nbsp; text-align: left;&nbsp; &nbsp; &nbsp; &nbsp; padding: 8px;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; tr:nth-child(even) {&nbsp; &nbsp; &nbsp; &nbsp; background-color: #dddddd;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; </style>&nbsp; </head>&nbsp; <body>&nbsp; &nbsp; <div class="container-fluid">&nbsp; &nbsp; <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">&nbsp; &nbsp; <div class="form-group">&nbsp; &nbsp; &nbsp; <label for="uname"></label>&nbsp; &nbsp; &nbsp; <input type="text" class="form-control" id="itemx" placeholder="Enter an item for the freezer here" name="itemx" required>&nbsp; &nbsp; &nbsp; <div class="valid-feedback">Valid.</div>&nbsp; &nbsp; &nbsp; <div class="invalid-feedback">Please fill out this field.</div>&nbsp; &nbsp; </div>&nbsp; &nbsp; <button id = "SubmitButton" name = "SubmitButton" type="button submit" class="btn btn-primary">Add to list</button></form>&nbsp; &nbsp; </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) {&nbsp; &nbsp; die("Connection failed: " . $conn->connect_error);}&nbsp;if(isset($_POST['id'])) {&nbsp; $delete = $con->prepare("DELETE FROM freezerinventory WHERE id= ?");&nbsp; $delete->bind_param("s", $_POST['id']);&nbsp; $delete->execute();}$sql = "SELECT * FROM freezerinventory";$result = mysqli_query($aVar, $sql);echo "<table><tr>&nbsp; &nbsp; <th>Item name</th>&nbsp; &nbsp; <th>Date added</th>&nbsp;&nbsp; &nbsp; <th>remove</th>&nbsp; </tr>&nbsp; &nbsp; ";&nbsp;while($row = mysqli_fetch_array($result))&nbsp; &nbsp;{&nbsp; echo "&nbsp; &nbsp; &nbsp; <tr><td>" . $row['item'] . "</td><td>" . $row['reg_date'] . "</td><td><form action='' method='POST'>&nbsp; &nbsp; <div class= 'input-group' > <div class='input-group-append'>&nbsp; &nbsp; &nbsp; &nbsp; <button class='btn btn-danger'&nbsp; onclick='deleteitem(".$row['id'].")' id='delete'>Remove</button>&nbsp; &nbsp; &nbsp; &nbsp; <input type='hidden' name='id'/>&nbsp; &nbsp; </div></div>&nbsp; &nbsp; </form></td></tr>";}&nbsp; &nbsp; echo "</table>";?><script>function deleteitem (id_data) {&nbsp; $.post('<?php echo $_SERVER["PHP_SELF"];?>', {id: id_data}, function(data) {&nbsp; &nbsp; console.log(data);&nbsp; //callback data&nbsp; });}function myFunction() {&nbsp; confirm("I am an alert box!");}(function() {&nbsp; 'use strict';&nbsp; window.addEventListener('load', function() {&nbsp; &nbsp; // Get the forms we want to add validation styles to&nbsp; &nbsp; var forms = document.getElementsByClassName('needs-validation');&nbsp; &nbsp; // Loop over them and prevent submission&nbsp; &nbsp; var validation = Array.prototype.filter.call(forms, function(form) {&nbsp; &nbsp; &nbsp; form.addEventListener('submit', function(event) {&nbsp; &nbsp; &nbsp; &nbsp; if (form.checkValidity() === false) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; event.stopPropagation();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; form.classList.add('was-validated');&nbsp; &nbsp; &nbsp; }, false);&nbsp; &nbsp; });&nbsp; }, false);})();</script></body></html>它可能仍然需要一些修复,我在那里留下了一些未使用的html元素,但从理论上讲,这应该有效。它利用 将数据发送到 。您不必使用,但从理论上讲,这应该可以解决您的问题。如果您遇到任何问题,请在我的答案下发表评论。ajaxphpajax注意:只是为了澄清,我没有尝试这样做,因此可能存在一些错误。
打开App,查看更多内容
随时随地看视频慕课网APP