我繼續破解我的新手php/mySQL'Invoicer'應用程序。提交一個或另一個查詢
我現在有一個表單頁面,我想在其中運行兩個查詢之一 - INSERT或UPDATE,具體取決於ID是否存在。如果有, 該ID用於檢索該記錄並預填充相應的表單,這是我工作的。我現在的問題是,我的條件位是 顯然是不正確的,因爲在任何情況下,當提交表單時INSERT查詢運行,無法運行UPDATE,並且我已經用盡我的理解(和猜測) 。
我很想知道爲什麼這不起作用,即使它不是最好的方法,我肯定願意將查詢移動到process.php, 等。我也是想知道是否應該使用'if(isset($ _ GET ['ID'])''來簡單地包含一個區塊或其他區域。最佳實踐/安全性一旦我有導線連接了廣招)
歡呼聲,S
<?php
// CASE I: 'EDIT RECORD':
// If there's an ID ...
if (isset($_GET['ID']) && is_numeric($_GET['ID'])) {
$id = $_GET['ID'];
echo "<p class=\"status\"><strong>ID IS SET ... ergo we're editing/UPDATING an existing record</strong></p>";
// ... retrieve the record ....
$query = sprintf("SELECT * FROM Invoices WHERE ID = %s", $id);
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result);
// ... assign variables to pre-populate the form
$id = $row['ID'];
$invNumber = $row['invNumber'];
$invDate = $row['invDate'];
// [ snip: more variables > field data ]
// on submit: get the form values ...
// no worky: if (isset($_GET['ID']) && isset($_POST['submit'])) {
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
// ... and UPDATE the db:
$qUpdate = "UPDATE Invoices SET invNumber='$invNumber', invDate='$invDate', projNumber='$projNumber', client='$client', task='$task', issueDate='$issueDate', subTotal='$subTotal', tax='$tax', invTotal='$invTotal', datePaid1='$datePaid1', datePaid2='$datePaid2', comments='$comments' WHERE ID='3'";
$result = mysql_query($qUpdate) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: RECORD UPDATED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE I: ID present
// CASE II: 'NEW RECORD'; query = INSERT
elseif (empty($_GET['ID'])) {
echo "<p class=\"status\"><strong>No ID ... ergo we're INSERTING a new record:</strong></p>";
// on submit: get the form values ...
if (isset($_POST['submit'])) {
$invNumber = $_POST['invoice-number'];
$invDate = $_POST['invoice-date'];
$projNumber = $_POST['project-number'];
// [ snip: more variables > field data ]
$qInsert = "INSERT INTO Invoices (invNumber,invDate,projNumber,client,task,issueDate,subTotal,tax,invTotal,datePaid1,datePaid2,comments)
VALUES('$invNumber','$invDate','$projNumber','$client','$task','$issueDate','$subTotal','$tax','$invTotal','$datePaid1','$datePaid2','$comments')";
$result = mysql_query($qInsert) or die(mysql_error());
if($result) {
echo "<p class=\"status\"><strong>SUCCESS: NEW RECORD INSERTED!</strong></p>";
}
else die("DAMMIT JIM I'M A DOCTOR NOT A DB ADMIN!" . mysql_error());
} // CLOSE '(isset($_POST['submit']))
} // END CASE II: No ID present
?>
和:
<form id="invoiceData" method="post" action="/html/form.php">
將GET ID參數轉換爲int並將基本安全性添加到此完整代碼中可能會對他有所幫助 – regilero
謝謝mellamokb - 這確實有效,並且正在啓動(也很好地知道我的語法可以正常工作) 。非常感激! – shecky
@ regilero ...是的,它會;) – shecky