SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Jan 2013
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question how insert values in database from froeach loop

    cart.php
    have that form
    <form action="process.php" methodd="POST">

    <input type="hidden" name="id" value='".$product_id."'>

    <input type="hidden" name="name" value='".$name."'>

    <input type="hidden" name="quantity" value='".$quantity."'>

    <input type="hidden" name="hello" value='".$price."'>

    <input type="submit" value="place order"/>

    </form>


    process.php
    <?php
    foreach($_POST as $key=>$value)

    echo '$value';

    ?>
    problem is at last i want to insert all posted 4 items in database but i don't know how to do this plz help meeee

  2. #2
    SitePoint Enthusiast
    Join Date
    Apr 2011
    Posts
    40
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    foreach($_POST as $key=>$value){
    if($key == 1){ $values = "(1, 'abc', 2, 'xyz')"; }
    else { $values .= ", (2, 'abcd', 2, 'wxyz')" }
    }

    so the $values will be (1, 'abc', 2, 'xyz'), (2, 'abcd', 2, 'wxyz'), (2, 'abcd', 2, 'wxyz') if $key count 3

    So you can query like

    INSERT INTO table (id, name, value, value2) VALUES $values;

  3. #3
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    1. Create your form properly in the first place:

    Code:
    <form action="process.php" method="POST">
    <input type="hidden" name="id" value='".$product_id."'>
    <input type="hidden" name="name" value='".$name."'>
    <input type="hidden" name="quantity" value='".$quantity."'>
    <input type="hidden" name="hello" value='".$price."'>
    <input type="submit" value="place order"/>
    </form>
    Its not "methodd" but "method".

    2. Show us how your database table is made up.

  4. #4
    SitePoint Enthusiast
    Join Date
    Jul 2012
    Posts
    69
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    It's simple to put the data into a database.

    Have your connection ready:
    PHP Code:
     $db = new mysqli("host","user","password","database"); 
    Then make variable for the post data:
    PHP Code:
    $id $_POST['id'];
    $name $_POST['name'];
    etc
    Then insert it into the database using the connection you made:
    PHP Code:
    $query "insert into tablename(id, name, etc.) values($id$name, etc.);
    $insert = $db->query($query); 
    Make sure to have some error and success messages on your process.php


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •