-2

I am trying to insert data into 2 tables which are in different database. But I'm not able to connect to the second database.

$con1 = mysqli_connect("localhost","root","","db1");

$sql_1 = "insert into enquiry(name,email,phone,subject,message,service_category) values('aa','aa@gg.com','12344','xxx','ddd','ddd')";

$res_1 = mysqli_query($con1,$sql_1);

$con = mysqli_connect("localhost","root","","db2");

$sql = "insert into customers(cname,cphone,cemail) values('$name','$phone','$email')";

$res = mysqli_query($con,$sql);
Zhorov
  • 28,486
  • 6
  • 27
  • 52
  • Check the result from `mysqli_connect()` and if the function fails, post the error message with `mysqli_connect_errno()`. – Zhorov Apr 22 '19 at 07:31
  • Please refer this url https://stackoverflow.com/questions/17788659/how-to-insert-data-in-two-different-tables-of-two-different-database-in-php – VinoCoder Apr 22 '19 at 07:32
  • im using mysqli – Ajay Viswanath Apr 22 '19 at 07:35
  • 1
    As long as the databases are on the same instance (they both connect to `localhost`) and the correct permissions - you can just and the database name as a prefix `insert into db1.enquiry` and `insert into db2.customers` – Nigel Ren Apr 22 '19 at 07:36

1 Answers1

2

You can do this with a single connection

$db = new mysqli($host,$user,$pass);

When selecting the DB use this

mysqli_select_db('DB_NAME', $db);

You Code

$con1 = mysqli_connect("localhost","username","password");
/* For the DB1 */
mysqli_select_db('DB_NAME1', $con1);
$sql_1 = "insert into 
enquiry(name,email,phone,subject,message,service_category) 
values('aa','aa@gg.com','12344','xxx','ddd','ddd')";
$res_1 = mysqli_query($con1,$sql_1);

/* For the DB2 */
mysqli_select_db('DB_NAME2', $con1);
$sql = "insert into customers(cname,cphone,cemail) 
values('$name','$phone','$email')";
$res = mysqli_query($con1,$sql);
Rakesh Jakhar
  • 6,380
  • 2
  • 11
  • 20