Hi, I need help here.
I have a for with multiple text inputs. input1 is link, input2 is description.
This is repeated a number of time.

Each link and description is one record, but I cant igure out how to add them to mysql as such.
If I fill in 2 link/desription it adds 4 records to mysql so I have 2 of each!

Can anyone help me out her?

Here is my code.

<form class="form1" action="linksaddform.php" method="post" enctype="multipart/form-data" name="links_upload_form" id="links_upload_form" style="margin-bottom:0px;">
                     <p><span class='text'><b>Link</b></span> <input type=text name="alink[0]">
                     <span class='text'><b>Description</b></span> <input type=text name="aname[0]"><br />
                     <span class='text'><b>Link</b></span> <input type=text name="alink[1]">
                     <span class='text'><b>Description</b></span> <input type=text name="aname[1]"><br />
                     <span class='text'><b>Link</b></span> <input type=text name="alink[2]">
                     <span class='text'><b>Description</b></span> <input type=text name="aname[2]"><br />
                     <span class='text'><b>Link</b></span> <input type=text name="alink[3]">
                     <span class='text'><b>Description</b></span> <input type=text name="aname[3]"><br />
                     <span class='text'><b>Link</b></span> <input type=text name="alink[4]">
                     <span class='text'><b>Description</b></span> <input type=text name="aname[4]"><br />
                     <span class='text'><b>Link</b></span> <input type=text name="alink[5]">
                     <span class='text'><b>Description</b></span> <input type=text name="aname[5]"><br />
                     <span class='text'><b>Link</b></span> <input type=text name="alink[6]">
                     <span class='text'><b>Description</b></span> <input type=text name="aname[6]"><br />
                     <span class='text'><b>Link</b></span> <input type=text name="alink[7]">
                     <span class='text'><b>Description</b></span> <input type=text name="aname[7]"><br />
                     <span class='text'><b>Link</b></span> <input type=text name="alink[8]">
                     <span class='text'><b>Description</b></span> <input type=text name="aname[8]"></p>
                     <input type="submit" name="submit" value="Upload Links" />       
                     <input name="submitted_form" type="hidden" id="submitted_form" value="links_upload_form" />
                  </form>
                  <?php
                  include '../inc/connect.php';

                       if (isset($_POST['submit'])){  
                          foreach($_REQUEST['alink'] as $alink){
                             if (($alink != ''){
                                foreach($_REQUEST['aname'] as $aname ){
                                   if ($aname != ''){
                                      mysql_query("INSERT INTO links  VALUES ('', '$alink', '$aname')");
                                   }
                                 }
                             }
                           }
                        }
                    ?>

Thanks for looking.................

You can do multiple insertion with one query:

if (isset($_POST['submit'])){

    // start the query
    $query = 'INSERT INTO links  VALUES ';

    // get number of elements in the array containing links
    $linksCount = count($_POST['alink']);

    // step through the array containing links
    for($i = 0; $i < $linksCount; $i++) {

        // add to the query if value exists
        if (($_POST['alink'] != '') {

            // escape the values (do not omit this!!)
            $alink = mysql_real_escape_string($_POST['alink']);
            $aname = mysql_real_escape_string($_POST['aname']);

            $query = "('', '$alink', '$aname'), ";
        }
    }

    // remove the trailing comma from the end of query
    $query = rtrim($query, ',');

    // run the query
    mysql_query($query);
}

And switch to newer mysqli as soon as you can :-)

Member Avatar for diafol

This is where you can use a non-indexed array for name in the controls:

Multiples of:

<p><span class='text'><b>Link</b></span> <input type=text name="alink[]">
   <span class='text'><b>Description</b></span> <input type=text name="aname[]"><br />

The indexes will be added automatically. You can then strip out empty entries:

Here's some untested stuff ( I was bored :) )

//hard coded vars - instead of post vars
$r[0] = '';
$r[1] = '';
$r[2] = 'http://foo2.com';
$r[3] = '';
$r[4] = 'http://boo4.com';

$s[0] = '';
$s[1] = 'foobar1';
$s[2] = 'foobar2';
$s[3] = '';
$s[4] = '';


function clean($data){
    return mysql_real_escape_string($data); 
}

function getSQLValuesClause($link, $desc){
    $output=array();
    foreach($link as $k=>$v){
        if(filter_var($v, FILTER_VALIDATE_URL)){
            $d = (!empty($desc[$k])) ? $desc[$k] : ''; //OR NULL instead of ''
            $url = clean($v);
            $description = clean($description);
            $output[] = "(NULL, '$url', '$description')";
        }
    }
    if(!empty($output)){
        return implode(", ", $output);  
    }else{
        return false;
    }
}

if($svc = getSQLValuesClause($r,$s)){
    if(mysql_query("INSERT INTO links VALUES $svc")){
        echo "success"; 
    }else{
        echo "fail";    
    }
}

NB. This is not a solution. Just one approach.

<form class="form1" action="linksaddform.php" method="post" enctype="multipart/form-data" name="links_upload_form" id="links_upload_form" style="margin-bottom:0px;">
    <p><?php for($i=0; $i<9; $i++): ?>
    <b>Link</b> <input type=text name="alink[]">
    <b>Description</b> <input type=text name="aname[]"><br />
    <?php endfor; ?></p>
    <input type="submit" name="submit" value="Upload Links" />
    <input name="submitted_form" type="hidden" id="submitted_form" value="links_upload_form" />
 </form>
 <?php

// include '../inc/connect.php';
      if (isset($_POST['submit'])) {
         foreach($_POST['alink'] as $key => $notused) {
             $test = trim($_POST['alink'][$key].$_POST['aname'][$key]);
             if(!empty($test)) {
                echo "mysql_query(INSERT INTO links VALUES ('', '{$_POST['alink'][$key]}', '{$_POST['aname'][$key]}')".'<br>';
             }
         }
      }

?>

Just to confirm that this will echo the sql to the screen

Member Avatar for diafol

Won't that run multiple sql queries?

Thanks for the replys guy. I have tried the methods suggested bu paulkd and broj1, but nothing is getting added to my table now. any advice?

Thanks

I got paulkd's method to work, but i tested it by adding 2 records, 2 link and 2 names

so it should be

www.something.com, something
www.someone.com, somone

but it adds 4 records to my table.

www.something.com, something
www.something.com, someone
www.someone.com, something
www.someone.com, someone

Can anyone help?

Cheers.....................

to check for mysql errors:
mysql_query("the query to test")OR die(mysql_error());

I now have this

if (isset($_POST['submit'])){  
                          foreach($_REQUEST['alink'] as $alink){
                             if ($alink != ''){
                                $aname = ($_REQUEST['aname']);
                                   if ($aname != ''){

                                       mysql_query("INSERT INTO links  VALUES ('', '$alink', '$aname')");
                                   }
                                 }

                             }
                          }

But this adds 'Array' instead of name to my table

It should be
www.something.com, something
but is
www.somethinng.com, Array

Any ideas?

Now I have this

if (isset($_POST['submit'])){  
                          foreach($_REQUEST['alink'] as $alink){
                             if ($alink != ''){
                             $link = $alink;
                                foreach($_REQUEST['aname'] as $aname){
                                   if ($aname != ''){
                                   $name = $aname;


                                   }
                                 }

                             }
                           }
                           mysql_query("INSERT INTO links  VALUES ('', '$link', '$name')");
                        }

But this only add the last entry to the database!

Member Avatar for diafol

Did you give my code a bash? It'll just run the one query and only insert those pairs where the url is not just not empty but also only proper urls. It also sanitizes the input. No problem, but you seem to be struggling with sanitizing, placing your query in a loop or not and no filtering of valid data.

But this only add the last entry to the database!

In your last version the query is outside both foreach loops so it gets run only once with the last assigned values. Put the query inside the inner loop and also apply the sanitizing (mysql_real_escape_string function), like suggested in above posts (take security seriously).

It is a good practice to assign a query to a string before running it - this is how you can echo it and test it in phpmyadmin:

$query = "INSERT INTO links  VALUES (...)";
...

// temporary debug code will display the query and stop the script
// you can now examine the query and copy it into phpmyadmin for testing
die($query);

// run the query
mysql_query($query);

Hi Al

I'm having trouble with your code. I used it as is. Its adding to thhe table, but only the link field, no description/name.

Also I'm getting this error on the page
'Notice: Undefined variable: description in C:\wamp\www\tattoocarnival\admin\linksaddform.php on line 58'

Its on this line

$description = clean($description);

Its probably something I'm overlooking, but can you tell what?

Ah figured it out!

$description = clean($description);

should be

$description = clean($d);

Just one more thing though. Were you have hardcoded the indexes, how would I get it so they are posted from my form?

I figured it out!

Thanks for all the help and advice guys, I appreciate it!.................

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.