2017-06-01 116 views
0

如何從數據庫中獲取完全相同的「id」值(也就是我的HTML表格),並將其輸入到表單提交值中?表格輸入類型等於動態表格結果

這是我曾經做過迄今爲止:
我已經產生了兩件事情,工作正常:

  1. 從數據庫表生成從三列的結果的HTML表格
  2. 一「賣」 提交按鈕到每一行

IMAGE OF THE TABLE

正如你可以在下面的代碼中看到的。所以每當我推「賣出」按鈕「ID」的值被固定爲3的值,1個單位被添加到產品的量列編號爲3

問題:
我真正想要的是根據特定行的值來動態變化。
如果我在「ID 1」的行上推「sell」,那麼我想將「1」作爲值動態添加到表單中。
如果我推行「賣」爲「ID 2」的話,我想「2」動態地添加值到表格..等

<html> 
<body> 

<form id="sellAndBuy" method="POST"> 
<input type="hidden" name="qty" value="1"> 
<input type="hidden" name="id" value="3"> 

<?php 

echo "<table style='border: solid 2px black; text-align:left;'>"; 
echo "<tr><th>Product</th><th>Stock</th><th>ID</th></tr>"; 

$servername = "localhost"; 
$username = "root"; 
$password = ""; 
$dbname = "name"; 

echo "<td>"; 
try { 
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); 
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
    $stmt = $conn->prepare("SELECT product_name, product_quantity, product_id FROM product "); 
    $stmt->execute(); 

    // set the resulting array to associative 
    $result = $stmt->fetchAll(PDO::FETCH_OBJ); 

    foreach ($result as $v) { 
     echo "<td style='width:150px;border:1px solid black;'>"; 
     echo "</td>"; 
     echo '<tr>'; 
     echo '<td>' .$v->product_name. "</td>"; 
     echo '<td>' . $v->product_quantity. "</td>"; 
     echo '<td>' . $v->product_id. "</td>"; 
     echo '<td> <button type="submit" onclick="askForSell()"> Sell </button> </td> 
      <td> <button type="submit" onclick="askForBuy()"> Buy </button> </td>'; 
    echo '</tr>'; 

    } 
     echo "</td>"; 
} 

catch(PDOException $e) { 
    echo "Error: " . $e->getMessage(); 
} 
$conn = null; 
echo "</table>"; 

?> 

<br> 
<br> 
<br> 

</form> 
<script> 
form=document.getElementById("sellAndBuy"); 
function askForSell() { 
    form.action="sellAndBuy.php"; 
    form.submit(); 
} 
function askForBuy() { 
    form.action="buyProducts.php"; 
    form.submit(); 
} 

</script> 


</body> 
</html> 

回答

0

你可以通過在產品與函數,然後ID填充它到輸入字段,如:

... 

    echo '<td> <button type="submit" onclick="askForSell('.$v->product_id.')"> Sell </button> </td> 
       <td> <button type="submit" onclick="askForBuy('.$v->product_id.')"> Buy </button> </td>'; 

... 

function askForSell(id) { 
    form.action="sellAndBuy.php"; 
    form['id'].value = id; 
    form.submit(); 
} 
function askForBuy(id) { 
    form.action="buyProducts.php"; 
    form['id'].value = id; 
    form.submit(); 
} 
+0

我按照你的建議嘗試過,但生成的值是空的。 – Swift123

+0

我知道它的工作。之前爲空值的原因是我錯過了askForSell(id)中的「id」。非常感謝您的幫助! – Swift123

0

您可以提交根據無JS按下按鈕變量:

<button type="submit" name="id" value="1">Sell</button> 

此外,按鈕可以包含formaction屬性。