jose
jose

Reputation: 83

How to get result from query and insert the results in other table?

I did query to the database where I need the results from it and then store it in a variable. Then I will pass the variable to the INSERT INTO statement but for some reason my code does not work. This is my code/

$query = "SELECT * from animals where old= 1 AND user_id=".$_SESSION['user_id'];
$result = mysqli_query(mysqli_connect("","","", ""), $query);


while ($row = mysqli_fetch_array($result))
{
    $variable[] = $row['number'];
}

//now I will pass the $variable to the INSERT INTO statement

if(isset($_POST['submit_d']))
{    
    foreach($variable as $var)
    {
        $query="INSERT INTO selectedanimals(number) VALUES ({$var},2)";
        mysqli_query($con, $query) or die (mysql_error());
    }
?>
<script>
    alert("Animal added.");
    self.location="chooseAnimals.php";
</script>
<?php
    }
?>

Upvotes: 2

Views: 42

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520968

You can use INSERT INTO ... SELECT for this purpose in a single query:

INSERT INTO selectedanimals (number)
SELECT number
FROM animals
WHERE old = 1 AND user_id = some_id

PHP code:

$query = "INSERT INTO selectedanimals (number) ";
$query.= "SELECT number FROM animals WHERE old = 1 AND user_id = ".$_SESSION['user_id'];
mysqli_query($con, $query) or die (mysql_error());

Upvotes: 1

Related Questions