2014-01-21 185 views
0

我正在嘗試處理一個大表單,並且遇到了一個絆腳石。我試過谷歌的答案,但我不太確定我的措詞是什麼,我需要的權利。我的代碼看起來像這樣。更改變量的變量

<?PHP 

$exchange = $_POST['exchange']; 
$estimate = $_POST['estimate']; 
$wp = $_POST['wp']; 
$label1 = $_POST['name3']; 
$result1 = $_POST['fb1']; 
$result2 = $_POST['fb2']; 

$username = "-----"; 
$password = "-----"; 
$hostname = "-----"; 

$con = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL"); 
$selected = mysql_select_db("-----", $con) or die("Could not select examples"); 



$query = "UPDATE btsec SET Status='$result1', TM='result2' WHERE Exchange='$exchange' AND Estimate='$estimate' AND WP='$label1' AND SectionID='$label1'"; 

if (!mysql_query($query,$con)) 
    { 
    die('Error: ' . mysql_error($con)); 
    } 
} 

echo "Sections updated for WP's $wp on $estimate on the $exchange Exchange!"; 

mysql_close($con); 

?> 

我需要做的是循環查詢,但每次更改變量的內容。

$label1 = $_POST['name3']; needs to become $label1 = $_POST['name6']; 
$result1 = $_POST['fb1']; needs to become $result1 = $_POST['fb10']; 
$result1 = $_POST['fb2']; needs to become $result1 = $_POST['fb11']; 

正如我所說的谷歌是無法彌補我的不好的措辭。

+3

是否有任何規則選擇這些索引,或者你只是隨機挑選它們? –

+0

@YUNOWORK窗體標籤name3在表單的每個部分增加3,fb1增加9.它貫穿整個 –

+1

您可能會發現將輸入字段用作數組更容易:name =「name [ 3]「','name =」name [6]「','name =」fb [1]「','name =」fb [10]「'等等 - 然後你可以做foreach $ _POST ['name'] as $ index => $ name)'... – MichaelRushton

回答

0

最好的解決辦法是改變形式的投入,使他們爲數組工作:

<input type="text" name="name[3]"> 
<input type="text" name="name[6]"> 
<input type="text" name="name[9]"> 


<input type="text" name="fb[1]"> 
<input type="text" name="fb[10]"> 
<input type="text" name="fb[19]"> 

然後當你提交你可以遍歷數據形式:

foreach ($_POST['name'] as $index => $name) 
{ 

} 

foreach ($_POST['fb'] as $index => $fb) 
{ 

} 

作爲注意,你也應該考慮使用prepared statements或至少escaping的數據 - 你有SQL injection的風險。

+0

SQL是我嘗試使用的代碼,我使用了許多年前做過的類似任務,但規模要小得多。我將圍繞更新SQL,我保證 –

+0

您的解決方案非常完美! –