SitePoint Sponsor

User Tag List

Results 1 to 8 of 8
  1. #1
    SitePoint Wizard tgavin's Avatar
    Join Date
    Feb 2003
    Location
    FL
    Posts
    1,051
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    INSERTing unknown number of items

    I have a simple form - a text field and a textarea - for news articles. The number of articles depends upon the user. The form starts with 1 article and, if the user wants to add more, will click on a button (for now it's text) to add another article to the form. If you try using the code below, you'll see more clearly what I mean.

    My problem is now getting that info and inserting it into the articles table. I'm not sure how to go about splitting, or exploding or whatever needs to be done to assign each posted article (the text field and textarea combo constitutes an article) an ID number and insert it in the appropriate manner.

    Code:
    CREATE TABLE `articles` (
    `art_id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    `newsletter_id` INT UNSIGNED NOT NULL ,
    `art_headline` VARCHAR( 255 ) NOT NULL ,
    `art_txt` TEXT NOT NULL ,
    ) ENGINE = MYISAM ;
    PHP Code:
    <?php
    if(isset($_POST['submit'])) {
      
    $conn mysql_connect('localhost''username''password') or trigger_error(mysql_error(),E_USER_ERROR);
      
    mysql_select_db('database'$conn) or die(mysql_error());
      
      foreach(
    $_POST as $key=>$value) {
        
    // just testing here
        
    echo "Key: $key; Value: $value<br />\n";
        
    //$query = mysql_query("INSERT INTO articles (newsletter_id,art_headline,art_txt) VALUES ('".$_POST['newsletter_id']."','".$_POST[$key]."','".$_POST[$value]."')") or die(mysql_error());
      
    }
    }
    ?>

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script type="text/javascript">
    var elCount = 2;
    function add() {
      var parent = document.getElementById('parent');
      var article = document.createElement('DIV');
        article.id = 'article_' + elCount;
        article.name = 'article_' + elCount;
      var article_title_label = document.createElement('LABEL');
        article_title_label.appendChild(document.createTextNode('Title ' + elCount + ': '));
      var article_title_text = document.createElement('INPUT');
        article_title_text.id = 'article_' + elCount + '_title';
        article_title_text.name = 'article_' + elCount + '_title';
      var article_textarea = document.createElement('TEXTAREA');
        article_textarea.id = 'article_' + elCount + '_content';
        article_textarea.name = 'article_' + elCount + '_content';
      var article_remove_a = document.createElement('A');
        article_remove_a.appendChild(document.createTextNode('Remove'));
        article_remove_a.href = 'javascript:remove(\'article_' + elCount + '\');';
        article.appendChild(article_title_label);
        article.appendChild(article_title_text);
        article.appendChild(document.createElement('BR'));
        article.appendChild(article_textarea);
        article.appendChild(document.createElement('BR'));
        article.appendChild(article_remove_a);
        parent.appendChild(article);
        elCount++;
    }

    function remove(el) {
      if(typeof(el) == 'string')
        el = document.getElementById(el);
      var parent = el.parentNode;
      parent.removeChild(el);
    }
    </script>
    </head>
    <body>
    <form action="add.php" method="post">
        <div id="parent">
            <div id="article_1">
                <label for="article_1_title" style="float:left; width:80px">Headline 1: </label><input type="text" name="article_1_title" id="article_1_title" /><br />
                <label for="article_1_content" style="float:left; width:80px">Article 1: </label><textarea name="article_1_content" id="article_1_content"></textarea><br />
                <a href="javascript:remove('article_1');">Remove this article</a>
            </div>
        </div>
        <a href="javascript:add();">Add another article</a><br />
        <input type="hidden" name="newsletter_id" value="32" />
        <input type="submit" name="submit" value="submit">
    </form>
    </body>
    </html>

  2. #2
    reads the ********* Crier silver trophybronze trophy longneck's Avatar
    Join Date
    Feb 2004
    Location
    Tampa, FL (US)
    Posts
    9,854
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    instead of article_1_title, use article[1][title]. this will turn $_POST['article'] in to an array that that you can foreach through.

    and don't forget to account for SQL injection.

  3. #3
    SitePoint Evangelist mad-onion's Avatar
    Join Date
    Aug 2000
    Location
    Land of the long white cloud
    Posts
    556
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I am not entirely sure if there is a better way of doing this but the below code works:

    PHP Code:
        foreach($_POST as $n => $v){        
            if ( 
    substr($n,0,8) == "article_" && substr($n,-6) == "_title" ){
                list(,
    $id) = explode("_",$n);
                
    $title $_POST['article_'.$id.'_title'];
                
    $content $_POST['article_'.$id.'_content'];        
                
    $sql "INSERT INTO articles (newsletter_id,art_headline,art_txt) VALUES ('".$_POST['newsletter_id']."','".$title."','".$content."')";
                
    mysql_query($sql);
            }        
        } 
    SiteOptions >> Services :: Products :: Contact
    Developers of PHP, C++, Visual Basic, MySQL, and more!

  4. #4
    SitePoint Evangelist mad-onion's Avatar
    Join Date
    Aug 2000
    Location
    Land of the long white cloud
    Posts
    556
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by longneck View Post
    instead of article_1_title, use article[1][title]. this will turn $_POST['article'] in to an array that that you can foreach through.

    and don't forget to account for SQL injection.
    will that work with js?
    SiteOptions >> Services :: Products :: Contact
    Developers of PHP, C++, Visual Basic, MySQL, and more!

  5. #5
    reads the ********* Crier silver trophybronze trophy longneck's Avatar
    Join Date
    Feb 2004
    Location
    Tampa, FL (US)
    Posts
    9,854
    Mentioned
    1 Post(s)
    Tagged
    0 Thread(s)
    sure. why wouldn't it?

  6. #6
    SitePoint Evangelist mad-onion's Avatar
    Join Date
    Aug 2000
    Location
    Land of the long white cloud
    Posts
    556
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    No reason really have just had some teething problems with javascript and inputs named as arrays, not doing this exactly, but that is why I asked.
    SiteOptions >> Services :: Products :: Contact
    Developers of PHP, C++, Visual Basic, MySQL, and more!

  7. #7
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    So how about like this then:
    Code javascript:
    var elCount = 2;
    function add() {
    	var parent = document.getElementById('parent');
     
    	/* Creating new article div */
    	var article = document.createElement('DIV');
    	var inntertext = "";
     
    	/* Setting new div id and name attributes */
    	article.id = 'article_' + elCount;
    	article.name = 'article_' + elCount;
     
    	/* Preparing new article form */
    	inntertext += 'Headline ' + elCount + ': </label><input type="text" name="atitle[]" id="aatitle[]" /><br />\n';
        inntertext += 'Article ' + elCount + ': </label><textarea name="acontent[]" id="acontent[]"></textarea><br />\n';
    	inntertext += '<a href="javascript:remove(article_' + elCount + ');">Remove this article</a>\n';
     
    	/* Setting innerHTML of new div */
    	article.innerHTML = inntertext;
     
    	/* Appending the new div to parent */
    	parent.appendChild(article);
    	elCount++;
    }
    function remove(el){
      if(typeof(el) == 'string')
        el = document.getElementById(el);
      var parent = el.parentNode;
      parent.removeChild(el);
    }
    Code html:
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    </head>
    <body>
    <form action="" method="post">
        <div id="parent">
            <div id="article_1">
                Headline 1: </label><input type="text" name="atitle[]" id="aatitle[]" /><br />
                Article 1: </label><textarea name="acontent[]" id="acontent[]"></textarea><br />
                <a href="javascript:remove('article_1');">Remove this article</a>
            </div>
        </div>
        <a href="javascript:add();">Add another article</a><br />
        <input type="hidden" name="newsletter_id" value="32" />
        <input type="submit" name="submit" value="submit">
    </form>
    </body>
    </html>
    Code php:
    if(isset($_POST['submit'])) {
    	for($i = 0; $i < count($_POST['atitle']); $i++){
    		$sql = "INSERT INTO articles SET newsletter_id='{$_POST['newsletter_id']}',
    				art_headline='{$_POST['atitle'][$i]}',
    				art_txt='{$_POST['acontent'][$i]}'";
    		echo $sql . "<br>";
    	}
    	/*print '<pre>';print_r($_POST['atitle']);print_r($_POST['acontent']);print '</pre>';*/
    }
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  8. #8
    SitePoint Wizard tgavin's Avatar
    Join Date
    Feb 2003
    Location
    FL
    Posts
    1,051
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you all for your replies. Longneck, you were right as usual. I always forget to add braces!

    rajug: That works like a charm. Thank you very, very much!


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
  •