2

I am fresh learner.

I found a difficulty for "Insert combination data made PHP to MySQL"

Example: for 1,2,3,4, combination is:

123
124
134
234

I want to insert that into a MySQL database.

Result:

123
124
134
234
234 <= duplicate

I couldn't locate where is the problem is. Thank you so much. :-)

$lista = array($a,$b,$c,$d);
$b=1;

for ($i=0; $i<=3; $i++) {
  for ($j=$b; $j<=4;$j++) {
    for ($k=$j+1; $j<count($lista); $j++) {

       printf($lista[$i].','.$lista[$j].'<br>');

       $sql="INSERT INTO table10(id)
            VALUES($lista[$i]$lista[$j])";
        mysql_query( $sql, $con );

        }           
    }
    $b++;
}

2 Answers 2

3

You can create array to avoid duplicate data

$dupList=array();
//declare this array before loop

//Hold  $lista[$i] and $lista[$j] jointly in a variable
$newVal=$lista[$i].$lista[$j];
if (!in_array($newVal, $dupList)) {

      $sql="INSERT INTO table10(id) VALUES ($newVal)";
      mysql_query( $sql, $con );
      array_push($dupList,$newVal);
}
Sign up to request clarification or add additional context in comments.

4 Comments

My array logic isn't very good, after I added this to my code. It appear an error. "syntax error, unexpected T_VARIABLE< start from IF..... Is it something wrong to me? The code I added as another, please comment. Thank you so much
Hi, I upadted the codes, it seems work, but the record is still duplicated. I felt a sense of shame, is it something wrong on me. I took almost 2 hrs try to fix it. It doesn't work. Can I send my control panel to let u check. T^T.
what in $lista = array($a,$b,$c,$d); $a,$b,$c and $d ?
$a=$_POST[no1]; $b=$_POST[no2]; $c=$_POST[no3]; $d=$_POST[no4]; All are number inputted by user what number they want from a simple form website.
1

My array logic isn't very good, after I added this to my code. It appear an error.

syntax error, unexpected T_VARIABLE< start from IF..... Is it something wrong to me? The code I added as below.

$lista = array($a,$b,$c,$d);
$dupList=array();
//declare this array before loop
$b=1;


for ($i=0; $i<=3; $i++) {
    for ($j=$b; $j<=4;$j++) {
        for ($k=$j+1; $j<count($lista); $j++) {
            if (!in_array($lista[$i]$lista[$j], $dupList)) {
                $sql="INSERT INTO table10(id) VALUES ($lista[$i]$lista[$j])";
                mysql_query( $sql, $con );
                array_push($dupList,$lista[$i]$lista[$j]);
                }
            }
        }
    $b++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.