使用循环执行查询4次

时间:2016-06-02 07:06:34

标签: php mysql loops

我想执行4次查询以将数据插入表中。变量$answerformat$feedbackformat具有固定值,但$answer$format的值将发生变化。

这是我迄今取得的成就:

 $answer=array('<p>ali<p>','<p>ali<p>','<p>ali<p>','<p>ali<p>');  
 $answerformat=1;
 $fraction=array('1.0000000','0.0000000','0.0000000','0.0000000');
 $feedbackformat=1;

 for($i=0;$i<=sizeof($answer);$i++){

 }

1 个答案:

答案 0 :(得分:0)

您只需将查询放入循环中即可。您是否尝试过阅读mysqli_*PDO

mysqli_*扩展名为例。我们必须首先建立与数据库的连接,假设您还建立了用户权限,创建了数据库等等:

$con = new mysqli("Host", "User", "Password", "Database"); /* REPLACE NECESSARY PARAMETERS INSIDE */

/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

然后,让我们继续你的循环并插入查询:

$answer = array('<p>ali<p>', '<p>ali<p>', '<p>ali<p>', '<p>ali<p>');  
$answerformat = 1;
$fraction = array('1.0000000', '0.0000000', '0.0000000', '0.0000000');
$feedbackformat = 1;

for($i = 0; $i < sizeof($answer); $i++){

    /* PREPARE YOUR INSERT QUERY BELOW; REPLACE NECESSARY TABLE NAME AND COLUMN NAME; */
    $stmt = $con->prepare("INSERT INTO yourTable (Column1, Column2, Column3, Column4) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("ssss", $answer[$i], $answerformat, $fraction[$i], $feedbackformat); /* QUESTION MARKS IN YOUR INSERT QUERY WILL BE REPLACED WITH THESE FOUR VARIABLES; REPLACE OR REARRANGE PROPERLY THESE VARIABLES; s STANDS FOR STRINGS */
    $stmt->execute(); /* EXECUTE QUERY */
    $stmt->close(); /* CLOSE PREPARED STATEMENT */

}

必须删除循环中的=,因为它将循环五(5)次而不是四(4)次。数组的索引始终以零(0)开始。