Usman Qadeer Usman Qadeer - 6 months ago 9
MySQL Question

Execute a query 4 times with a loop

I want to execute a query 4 times to insert data into a table. The variables

$answerformat
and
$feedbackformat
have a fixed value but the value for
$answer
and
$format
will change.

Here is what I have achieved so far:

$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++){

}

Answer

You just have to put your query inside the loop. Have you tried reading about mysqli_* or PDO?

Lets use mysqli_* extension as an example. We have to establish first a connection to your database, assuming that you have also established your user privileges, created a database, etc.:

$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();
}

Then, lets proceed with your loop and insert query:

$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 */

}

Have to remove = in your loop as it will loop five (5) times instead of four (4). Index of an array always starts with zero (0).