如何使用&#34运行多个SQL查询; if(isset($ _ POST [' Submit'])){"

时间:2016-08-10 20:01:43

标签: php

尝试制作CRUD,除了我的更新功能外,一切正常。我觉得问题出在第二个sql查询中。当我点击提交它只是刷新并且更改消失了。谁能告诉我如何找到我需要改变的东西/告诉我要改变什么?

    <head>
<title>Update</title>
</head>

<body>
</form>



<?php 

require_once('dbconnect.php');
$id =  $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);



if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo '<form action="" method="post">';
        echo "Company: <input type=\"text\" name=\"CName\" value=\"".$row['CName']."\"></input>";
        echo "<br>";
        echo "Contact: <input type=\"text\" name=\"Contact\" value=\"".$row['Contact']."\"></input>";
        echo "<br>";
        echo "City: <input type=\"text\" name=\"City\" value=\"".$row['City']."\"></input>"; 
        echo "<br>";
        echo "<input type=\"Submit\" = \"Submit\" type = \"Submit\" id = \"Submit\" value = \"Submit\">";
        echo "</form>";
    }
    echo "</table>";
} else {
    echo "0 results";
}
if(isset($_POST['Submit'])){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();

?>

2 个答案:

答案 0 :(得分:2)

不要在PHP内构建表单,只需在while循环中打开结束PHP标记,然后以干净的方式编写HTML,然后再次启动PHP。所以你不要犯任何错误。

您也可以从表单中提交$id

试试这个

<?php 

require_once('dbconnect.php');

$id =  $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);


if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
?>

    <form action="" method="post">

        <input type="hidden" name="id" value="<?= $id ?>" />

        Company: <input type="text" name="CName" value="<?= $row['CName'] ?>" />
        <br>

        Contact: <input type="text" name="Contact" value="<?= $row['Contact'] ?>" />
        <br>

        City: <input type="text" name="City" value="<?= $row['City'] ?>" /> 
        <br>

        <input type="Submit" name="Submit" id="Submit" value="Submit" />

    </form>

<?php

    } // end while loop

    echo "</table>";
} 
else {
    echo "0 results";
}

注意:您正在将未定义的变量传递到更新查询中。在提交表单时,必须在使用它们之前定义这些变量。

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

    $CName     =   $_POST['CName'];
    $Contact   =   $_POST['Contact'];
    $City      =   $_POST['City'];

    $id        =   $_POST['id'];

    $sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";

    $result = $conn->query($sql);
}

$conn->close();

答案 1 :(得分:0)

那个循环? ID主键与否?

也许你需要在桌面经销商中创建更多关键字,比如as_id

<input type="hidden" name="idform" value="$as_id">

in statment

if($_POST){
$idf = $_POST['idform'];
if(!empty($idf)){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where as_id=$idf";
$result = $conn->query($sql);
}
$conn->close();
}