user9
user9

Reputation: 145

PHP: populate MySQL table with result of anagram creation

I am trying to populate a MySQL table with the result of a function to create anagrams from a given word. There is simply no result at all. I even do not get an error message.

 <?php

//connect to your database
$conn = mysqli_connect("localhost","dbuser","3423423sfdfsdf","mydb");

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

  $input = $trimmed;

function string_getpermutations($prefix, $characters, &$permutations)
{
    if (count($characters) == 1)
        $permutations[] = $prefix . array_pop($characters);
    else
    {
        for ($i = 0; $i < count($characters); $i++)
        {
            $tmp = $characters;
            unset($tmp[$i]);

            string_getpermutations($prefix . $characters[$i], array_values($tmp), $permutations);
        }
    }
}
$characters = array();
for ($i = 0; $i < strlen($input); $i++)
    $characters[] = $input[$i];

$permutations = array();

string_getpermutations("", $characters, $permutations);

foreach($permutations  as $result) {echo $result,'<br>';}

foreach($permutations  as $result) {mysqli_query($conn,"INSERT INTO tempanagram (anagram) VALUES ('$result')");}

    ?>

Upvotes: 0

Views: 63

Answers (2)

user9
user9

Reputation: 145

I got the solution:

Instead of foreach($permutations as $result) {mysqli_query("INSERT INTO tempanagram (anagram) VALUES ('$result')");}

I had to write:

foreach($permutations  as $result) {mysqli_query($conn,"INSERT INTO tempanagram (anagram) VALUES ('$result')");}

Otherwise it is apparently not clear that I am referring to that connection.

All the other hints are very valuable. Thanks very much to everybody.

Upvotes: 0

bato3
bato3

Reputation: 2815

You can also use mysqli, but best solution is using some query builders.

Add to your code error reporting for PHP and MYSQL

<?php
error_reporting(E_ALL);
ini_set('display_errors', true)
mysql_query($sql, $conn) or die('ERROR: '.mysqli_error($conn));

More info in http://php.net/manual/en/mysqli.error.php

You can optimize your code to make 1 insert query by using bulk insert, something like this:

<?php
$sql = 'INSERT INTO tempanagram (anagram) VALUES ("'.join('"),("', $permutations).'")';

Upvotes: 1

Related Questions