PHP虽然循环增量变量

问题描述:

我有这个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

再一次,我同意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])' – *

+0

我会尽量在以后解决SQL注入事件。我相信在这里搜索解决方案非常容易。 – Selim

如果你想存储在$ 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