0

I made a form which takes the attendance of around 11 people and what i need is to insert the daily attendance in a database. i want to use one single query to insert the attendance of all employees at once instead of writing 11 different queries for each of them. my table structure is ike this : attendance(date,eid,ename,attendance) I tried the following code for my bulk insert but it didnt work. any suggestions??

<?php
    $dbhost = "localhost";
    $dbuser = "root";
    $dbname = "gail";

    $conn = mysql_connect($dbhost, $dbuser,"") or die ('Error connecting to mysql');
    mysql_select_db($dbname);
    $dbh->beginTransaction();

    $stmt = $dbh->prepare("INSERT INTO attendance VALUES (curdate(),'$_POST[eid]','$_POST[ename]','$_POST[pora]')");

    foreach($valuesToInsert as $insertRow)
    {   

        // now loop through each inner array to match binded values
        foreach($insertRow as $column => value)
        {
            $stmt->bindParam(":{$column}", value);
            $stmt->execute();
        }
    }


    $dbh->commit();
?>

I also tried this:

<?php

    $dbhost = "localhost";
    $dbuser = "root";
    $dbname = "gail";

    $conn = mysql_connect($dbhost, $dbuser,"") or die ('Error connecting to mysql');
    mysql_select_db($dbname);

    $employees=array();

    while($row=mysql_fetch_assoc($result))
    {
        $employees[$row["eid"]]=array("ename"=>$row["ename"]);
        $employees[$row["eid"]][$row["dated"]]=array();
        $employees[$row["eid"]][$row["dated"]][$row["ename"]]=$row["pora"];
        $inserts = array();
        foreach($employees as $v)
        {
            $inserts[] = "(curdate(),'$_POST[eid]','$POST[ename]','$POST[pora]')";

            $query = "INSERT INTO attendance VALUES ". implode(", ", $inserts);

            echo "query = $query"; // for debugging purposes, remove this once it is working
            mysql_query($query) or die(mysql_error());
        }
    }


?>

but all this does is insert current date in the table a large number of times. please help. thnks in advance :)

i did this one more thing. it inserts multiple rows in the db exactly the no of rows u want but all blank. any ideas on how to deal with that?

html file:

Beamline ID Flow

Beamline ID
Flow

Beamline ID Flow

Beamline ID Flow

Beamline ID Flow

php:

 <?php
    $dbhost = "localhost";
    $dbuser = "root";
    $dbname = "gail";

    $conn = mysql_connect($dbhost, $dbuser,"") or die ('Error connecting to mysql');
    mysql_select_db($dbname);

    $cnt = count($_POST['bline_id']);
    $cnt2 = count($_POST['flow']);

    if ($cnt > 0 && $cnt == $cnt2) {
        $insertArr = array();
        for ($i=0; $i<$cnt; $i++) {
            $insertArr[] = "('" . mysql_real_escape_string($_POST['bline_id'][$i]) . "', '" .        mysql_real_escape_string($_POST['flow'][$i]) . "')";
        }

        $query = "INSERT INTO bltest (bline_id, flow) VALUES " . implode(", ", $insertArr);
        mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
    }

    echo("<pre>\n");  
    print_r($_POST);
    echo("</pre>\n");
    mysql_close($conn); 
?> 
Jaak Kütt
  • 2,566
  • 4
  • 31
  • 39
  • please show us what `$query` looks like just before you make the request. – lollercoaster Jul 10 '13 at 15:25
  • Your sql statement should look like "INSERT INTO attendance VALUES(?,?,?,?),(?,?,?,?),(?,?,?,?)" Where you repeat the ,() for each row to insert. Hope this helps. – Boundless Jul 10 '13 at 15:26
  • @lollercoaster $query = "INSERT INTO attendance VALUES ". implode(", ", $inserts); i read somewhere that implode statements are stored in a variable like this and nothing comes even after the cho statement. all tht comes is a large number of dates inserted in the date column – Veronika Marvolo Jul 10 '13 at 15:29
  • @Boundless that solves only the current scenario..but everytime an employee joins the company and i add his name in the database i will have to update the code. i want something that automatically reads the values from the table employee details and then inserts them into another table for attendance – Veronika Marvolo Jul 10 '13 at 15:31
  • @VeronikaMarvolo: no, it returns a string: http://php.net/manual/en/function.implode.php – lollercoaster Jul 10 '13 at 15:54

3 Answers3

0

Got it finally! if anyone needs to insert multiple values from a form with only one block of cide, follow should help! cheers: :)

<?php

$dbhost = "localhost";
$dbuser = "root";
$dbname = "gail";

$conn = mysql_connect($dbhost, $dbuser,"") or die ('Error connecting to mysql');
mysql_select_db($dbname);

$cnt = count($_POST['eid']);
$cnt2 = count($_POST['ename']);
$cnt3 = count($_POST['pora']);

if ($cnt2 > 0 ) {
$insertArr = array();
for ($i=0; $i<$cnt2; $i++) {
    $insertArr[] = "(curdate(),'" . mysql_real_escape_string($_POST['eid'][$i]) . " ','" . mysql_real_escape_string($_POST['ename'][$i]) . " ','" .   mysql_real_escape_string($_POST['pora'][$i]) . "')";
      }

 $query = "INSERT INTO attendance (dated,eid,ename,pora) VALUES " . implode(", ",     $insertArr);
 mysql_query($query) or trigger_error("Insert failed: " . mysql_error());
 }

echo("<pre>\n");
print_r($_POST);
echo("</pre>\n");

mysql_close($conn);
?>
-1

You are on the right track with your foreach() loop. There are two main things to change. Since we want to build a single query (rather than a query for each employee, start the query before the loop:

$query = "INSERT INTO `attendance` (`field1`, `field2`, `field3`) VALUES ";
foreach ($employees as $v)

Next, add the employee-specific fields to the query within each iteration of the loop. Notice that you need to escape your inputs to avoid MySQL inject. mysql_real_escape_string() is one way to do this, but you should consider implementing a more robust solution, perhaps via PDO parameterized queries.

foreach($employees as $v)
{
    $inserts[] = "(curdate(), '"
        . mysql_real_escape_string($_POST['eid'])
        . "', '" . mysql_real_escape_string($_POST['ename'])
        . "', '" . mysql_real_escape_string($_POST['pora']) . "')";
}

Then add the individual inserts to the query:

$query .= implode(",", $inserts);

This will produce a query in the following format:

INSERT INTO `attendance` (`field1`, `field2`, `field3`) VALUES 
    (curdate(), 'id1', 'ename1', 'pora1'),
    (curdate(), 'id2', 'ename2', 'pora2'),
    (curdate(), 'id3', 'ename3', 'pora3')

Finally, there is a bit of confusion in your code regarding whether you are pulling the data from $_POST or from a database query. If the data comes from the query, replace the references to $_POST data with the correct location of the data.

George Cummins
  • 28,485
  • 8
  • 71
  • 90
  • wow..that is the most understandable solution i have seen. thank you george..i guess this shoul do. but one quick question, my dates are coming from a table called dates which updates the date daily and eid and ename come from a table called employees. pora (which is for marking attendance) comes from the form. however i hv put the values of date eid an ename in d form as well in for all 3. so i am using $_POST for all. is that correct? – Veronika Marvolo Jul 10 '13 at 16:05
  • @VeronikaMarvolo If the values for all employees have been inserted into the form, it will work to pull data from `$_POST`. However, if you are pulling some values from the database and some from the form, you will need to modify the code slightly to find the values wherever they exist. – George Cummins Jul 10 '13 at 16:56
  • no i m pulling evrythng from the form..thnks fr the tip though :) – Veronika Marvolo Jul 10 '13 at 17:17
  • hey o implemented ur code, it inserting the date and pora column, but its not inserting eid and ename.. – Veronika Marvolo Jul 10 '13 at 17:44
  • Undefined index: eid in C:\wamp\www\gail\att.php on line 217 it gives this error – Veronika Marvolo Jul 10 '13 at 17:45
  • line 217 : $query = "INSERT INTO attendance (dated,eid,ename,pora) VALUES (curdate(),'$_POST[eid]','$_POST[ename]','$_POST[pora]')"; – Veronika Marvolo Jul 10 '13 at 17:46
  • That means you have no field named 'eid' in your form. – George Cummins Jul 10 '13 at 17:46
  • i do..i double checked it.. echo "".$row['eid'].""; – Veronika Marvolo Jul 10 '13 at 17:49
-2

Recently I managed to create a checklist for everyone who starting to learn dynamical SQL queries with PHP. You need to complete every item before turning to the text one:

  1. First of all, a database have to be designed to store your data.
  2. Once you've done with it, you need to make your mind on what query would serve the purpose of insert.
  3. then write this query by hand and make sure it works in console
  4. next step would be to determine what data you need for this query
  5. then you have to verify the data you have and determine if it fits for the (4)
  6. if not - you need to format your existing data to make it meet requirements from (4)
  7. As soon as you have it, you may start writing a PHP program that does create your query dynamically, using string concatenation, and echo the result out.
  8. then you have to test this dynamically built query in the console as if in (3)
  9. if it works - replace variables in the query with placeholders and proceed with running this query using mysqli prepared statements, with one single set of data. Note that when using native prepared statements, a placeholder can represent only a single data literal alone.
  10. having done with it, you may finally start your research on a problem of feeding a prepared statement with multiple values.
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 1
    thank you very much for these tips..i try using that approach only, however if you could have a luk at my code and tell me what is possibly wrong with it and how can i correct it to acheive my purpose..i wud be very grateful – Veronika Marvolo Jul 10 '13 at 15:34
  • One have to **run** the code, not look at it. I have no your $_POST, no your server, no your data, no your environment. Its only you who have it. Why don't you check your query, your variables if they contain the data you need? You have them but I am not. – Your Common Sense Jul 10 '13 at 15:37