2015-10-14 171 views
0

我有這個PHP代碼。一切都很順利,直到$插入。我想要得到的是循環過程中的不同變量。PHP雖然循環增量變量

例如,第一循環應該得到

$ A1

下一個循環是獲得$ A2等。我這樣做是因爲在完成所有這些後,變量將超過一百。

我想會的工作就是讓像

$b='$A'; 

但顯然它不工作。

<?php 
include 'connect.php'; 

$A1=$_POST['a1']; 
$A2=$_POST['a2']; 
$A3=$_POST['a3']; 
$examinee=$_POST['examinee']; 
$Q1=$_POST['q1']; 
echo $A1 . '<BR>' 
    . $A2 . '<BR>' 
    . $A3 . '<BR>' 
    . $examinee . '<BR>' 
    . $Q1; 

$query = "SHOW TABLES LIKE '$examinee'"; 
$result = $conn->query($query); 

if(mysqli_num_rows($result)==1) { 
    echo "Table exists"; 
} 
else { 
    $create="CREATE TABLE $examinee (ano int NOT NULL AUTO_INCREMENT, answer varchar(255), PRIMARY KEY (ano))"; 
    $conn->query($create); 


    $a=1; 
    $b='$A'; 

    while ($a<4) { 
     $insert="INSERT INTO $examinee (ano, answer) VALUES ('', '$b.$a')"; 
     $conn->query($insert); 
     $a++; 
    } 
} 
?> 

我希望發生的是變量$ A1,A2 $,$ A3在使用while循環數據庫中插入的值。

+0

你的問題還不清楚。另外,你可以[** SQL注入**](https://www.owasp.org/index.php/SQL_Injection)。 –

+0

爲什麼你不只是使用數據庫自​​動遞增ID? – 2015-10-15 00:04:36

+0

我不知道這是如何不清楚,但再次,如大家可以看到,在第3行有一個$ A1 = $ _ POST ['a1'] ;.因此,在包含$ insert的while循環中,我希望將$ A1,$ A2等值插入到每個循環的數據庫中。簡而言之,我想將$ A1放入VALUES中,但是如何在每個循環中增加它。 – Selim

回答

1

再一次,我同意Ed Cottrell在這裏,你已經開放SQL注入,但考慮到目前的實現,我認爲你可以使用一個數組來做你想要的更快。請參閱下面的代碼部分。

<?php 
$post_array = array(
    $_POST['a1'], 
    $_POST['a2'], 
    $_POST['a3'] 
); 

// printout statements and database connection here as above 

for ($i = 0; $i < count($post_array); $i++) { 
    $insert = "INSERT INTO $examinee (ano, answer) VALUES ('', " . $post_array[$i] . ")"; 
    $conn->query($insert); 
} 

一個更好的實現將使用prepared statements

+0

雖然我們沒有使用預處理語句,但您也可以在循環中使用$ _POST數組,而不是創建另一個數組。至少在變量的周圍拋出[mysqli_real_escape_string](http://php.net/manual/en/mysqli.real-escape-string.php)。 '$ conn-> real_esacape_string($ _ POST ['a'。$ i])' – Terminus

+0

我會盡量在以後解決SQL注入事件。我相信在這裏搜索解決方案非常容易。 – Selim

1

如果你想存儲在$ A1,$ A2,$ A3,$ A4值插入到一個字符串,做這樣的事情:

<?php 

$A1 = 'some'; 
$A2 = 'set'; 
$A3 = 'of'; 
$A4 = 'inputs'; 

for ($a = 1; $a <= 4 ; $a++) { 
    echo ${"A".$a}; 
} 
?> 

所以你的情況,這會是這樣的:

$insert="INSERT INTO $examinee (ano, answer) VALUES ('', '" . ${"A" . $a} . "')"; 

這不是我會去,雖然路線......因爲我不喜歡variable variables