2017-07-14 55 views
0

我需要的原因很複雜,但我有一個當前正在工作的HTML表單,它將一行插入到我的MYSQL數據庫中。但是...我需要將這兩個單獨的進程合併到一個HTML文件中,但經過許多嘗試安排代碼後,無法找到可行的解決方案。希望有人能指出我正確的方向。將單獨的HTML和PHP MYSQL表單合併爲一個文件

下面是HTML文件:

<form method="post" action="process.php"> 
<input type="text" name="id" placeholder="Enter ID" /><br /> 
<input type="hidden" name="user_text" id="hiddenField" value="x" /><br /> 
<input type="submit" value="Submit" /> 
</form> 

下面是相關process.php文件:

<?php 
if ($_SERVER["REQUEST_METHOD"] == "POST") { 

    //mysql credentials 
    $mysql_host = "localhost"; 
    $mysql_username = "*"; 
    $mysql_password = "*"; 
    $mysql_database = "*"; 

    $u_name = $_POST["id"]; 
    $u_text = $_POST["user_text"]; 

    if (empty($u_name)){ 
     die("Please enter your id"); 
    } 

    //Open a new connection to the MySQL server 
    $mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database); 

    //Output any connection error 
    if ($mysqli->connect_error) { 
     die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); 
    } 

    $statement = $mysqli->prepare("INSERT INTO users_data (contractor_id, status) VALUES(?, ?)"); //prepare sql insert query 
    $statement->bind_param('ss', $u_name, $u_text); //bind values and execute insert query 


} 
?> 

我知道這是不是做的事情以正確的方式,但它不是對於公共場所而言,更多是個人記錄項目。先進的謝謝!

+0

那麼,什麼是真正的問題?即使您只是將這兩個代碼片段一個接一個地複製並粘貼到文件中,它應該基本上工作 - 除了事實上您沒有實際執行查詢,但在這方面它不會與代碼一起工作如兩個單獨的文件所示。對該行執行查詢的評論_saying_實際上並不如此。 – CBroe

回答

0

你可以簡單地有一個這樣的文件:

<?php 

if ($_SERVER["REQUEST_METHOD"] == "POST") { 
    process(); 
} 
else { 
    show_form(); 
} 


function show_form() { 
?> 
<form method="post"> 
    <input type="text" name="id" placeholder="Enter ID" /><br /> 
    <input type="hidden" name="user_text" id="hiddenField" value="x" /><br /> 
    <input type="submit" value="Submit" /> 
</form> 
<?php 
} 

function process() { 

    //mysql credentials 
    $mysql_host = "localhost"; 
    $mysql_username = "*"; 
    $mysql_password = "*"; 
    $mysql_database = "*"; 

    $u_name = $_POST["id"]; 
    $u_text = $_POST["user_text"]; 

    if (empty($u_name)){ 
     die("Please enter your id"); 
    } 

    //Open a new connection to the MySQL server 
    $mysqli = new mysqli($mysql_host, $mysql_username, $mysql_password, $mysql_database); 

    //Output any connection error 
    if ($mysqli->connect_error) { 
     die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); 
    } 

    $statement = $mysqli->prepare("INSERT INTO users_data (contractor_id, status) VALUES(?, ?)"); //prepare sql insert query 
    $statement->bind_param('ss', $u_name, $u_text); //bind values and execute insert query 


} 

如果不設置action的形式,在默認情況下,它提交給自己

+0

嗨,那正是我在尋找的謝謝!然而,它在第5行返回語法錯誤,但我找不到原因。有任何想法嗎? – scotty6861

相關問題