iCodeCrew
iCodeCrew

Reputation: 115

PHP inserting data from one table to another

<?php
$con=mysqli_connect("localhost","usr","pwd","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT id, Name, email FROM users WHERE status='ACTIVE'");
while($row = mysqli_fetch_array($result)){
//  echo $row['Name']. " - ". $row['email'];
//  echo "<br />";
$userid = $row['id'];
$username = $row['Name'];
$email = $row['email'];
mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
VALUES ($userid, $username, $email)");
}
mysqli_close($con);
?>

i have the above code i am trying to insert data from one table to another The above code do not returning any error but it do not puts any data to second table "other_user"

Upvotes: 0

Views: 81

Answers (4)

phuk
phuk

Reputation: 1118

There is an error in INSERT query - you have to enclose strings in quotes, like this:

"INSERT INTO other_user (user_id, username, email) VALUES ($userid, '$username', '$email')"

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111889

You should use mysqli prepared statement to insert data to table. Now you don't use quotes in your query (probably that's why data is not inserted into second table) and even if you were, it would be still vulnerable to SQL Injection

Upvotes: 1

Pieter21
Pieter21

Reputation: 1845

I think you should carefully check the table design of your new table. Check if the column names and types are what you expect. Also user_id in your new table may be an autoincrement index and than if doesn't have to be inserted.

Upvotes: 0

VMai
VMai

Reputation: 10346

A single query would be enough:

$result = mysqli_query($con, "INSERT INTO other_user (user_id, username, email) 
    SELECT id, Name, email FROM users WHERE status='ACTIVE'");

No need for an agonizing slow row by row insert.

PS: The original error was leaving out quotes around your values.

Upvotes: 1

Related Questions