How to insert data into 2 database? - php

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);

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);

Related

Connect Multiple Database with PHP and MySQL

We have this multiple database and we need to connect all of them together. We are using relationship table to talk back and forth. Multiple database will help us to backup the project or version separately.
Registration database: User Log In
Project database: Number of projects under the Logged in user.
Version database: Number of versions under the selected Project
THE ISSUE
Because we are using 0 and 1, only one user can able to connect to the database at a time. What we need is like the one in the flowchart below. Multiple user can able to connect to the database and working on a different project > different versions.
Thanks!
Sidenote: We are open to try different approach
<?php
//database error message
$connect_error='We could not able to connect. Please try later';
// Registration table
$main = mysql_connect('localhost','root','',true) or die($connect_error);
mysql_select_db('registration-table', $main) ;
// Obtaining session id
if(isset($_SESSION['id'])===true){
$session = $_SESSION['id'];
// Filtering projects based on 0 and 1
$sql = mysql_query("SELECT * FROM project1_table where user_id = '$session' and database_active = '0'",$main);
$row = mysql_fetch_array($sql);
// Each Project has Versions
$project_id = $row['id'];
$sqli = mysql_query("SELECT * FROM version_table where project_id = '$project_id' and database_active ='0'",$main);
$emp = mysql_fetch_array($sqli);
// Fetching the database name
$db_name = $emp['database_name'];
$sub = mysql_connect('localhost','root','',true) or die($connect_error);
mysql_select_db("$db_name", $sub) ;
}
?>
First of all I would suggest you to use mysqli or PDO other then mysql , Because after PHP 5.5 version mysql function deprecated and therefore mysql function will not be available in future
Multiple DB connection in Mysql
$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);
mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);
mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);
Multiple connection using Mysqli
$link1 = new mysqli($hostname, $username, $password,$database1);
$link2 = new mysqli($hostname, $username, $password,$database2);
mysqli_query($link1,"SELECT * FROM table");
mysqli_query($link2,"SELECT * FROM table");
Multiple DB connection in PDO
$conn1 = new PDO("mysql:host=$hostname;dbname=database1", $username, $password);
$conn2 = new PDO("mysql:host=$hostname;dbname=database1", $username, $password);
$conn1->query("SELECT * FROM table");
$conn1->query("SELECT * FROM table");
$conn1 = mysqli_connect( $db_host, $db_user, $db_pass, $db_name );
$conn2 = mysqli_connect( $db_host2, $db_user2, $db_pass2, $db_name2 );
Let's say you have a database named chat1 and chat2, and a table named tbl_chat1 and tbl_chat2.
$sql1 = "SELECT `id`, `msgs` FROM `chat1` . `tbl_chat1`";
$sql2 = "SELECT `id`, `msgs` FROM `chat2` . `tbl_chat2`";
$result1 = mysqli_query($conn1, $sql1);
$result2 = mysqli_query($conn2, $sql2);
However you can achieve the backup of your database without having to connect to multiple databases OK.

Double or more value inserted when insert query written inside another query result object

I have the code below which was written in php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * from table name";
$result = $conn->query($sql);
//the result count is 95142
while($row = $result->fetch_assoc()) {
$sql = "insert into table1 (column) values ('test')";
$result = $conn->query($sql);
}
$conn->close();
?>
Which inserting more than 100 000 data in table1 but if I try to limit the source query up to 30 000 it inserts correct count of data into table1.
i.e
$sql = "SELECT * from table name limit 10000";
Both the table are in same Database.
Even tried with mysql_connect & mysql_query() method also getting the same error. Also tried with another connection for insert query but issue exists.
If I try the code like this
$flag = 1;
while($row = $result->fetch_assoc()) {
$flag = $flag + 1;
}
echo $flag;
I am getting the result of 95142.
you must really use different variable names in the second query !!!
while($row = $result->fetch_assoc()) {
$sql2 = "insert into table1 (column) values ('test')";
$result2 = $conn->query($sql2);
}
and secondly, delete the previous rows before running script, and then check the count, it must work fine.
Change your variable name $result inside the while.
Ex:
while($row = $result->fetch_assoc()) {
$insertSQL = "insert into table1 (column) values ('test')";
$insertRow = $conn->query($insertSQL);
}
The value of $result has been changed when insert query is executed. Maybe this is main problem.

PHP MySQL inserting information from one form into multiple tables

So I have form1 that contains information from multiple tables in a database. I've got listboxes and textboxes within this form that have that information. So all I'm trying to do is insert whatever information the user submits back into the database and have it outputted on form2. I've got my INSERT INTOs on my output page. I know you can't use one INSERT INTO query, so I was wondering how to use multiple INSERTS and submit that information back into the database.
The variables created below come from the previous page and all of the values are there.
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
echo "New record created successfully";
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query = "select status_id from ostatus where status_type = '$ostatus'";
$result = mysqli_query($db, $query) or die("Error in SQL statement:" .mysqli_error());
$row = mysqli_fetch_array($result);
$statusid = $row[0];
$query1 = "insert into cust ('c_fname', 'c_lname') values ('$cfname', $clname)";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed ('e_fname', e_lname) values ('$efname', '$elname')";
$result2 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('{$oid}', '{$odate}', '{$statusid}')";
$result3 = mysqli_query($db, $query3);
}
First of all your query is vulnerable to SQL injection. I am not going to fix that.
Second, you should Google how to handle forms properly. And you should consider starting SQL transaction if you really care about the data to go into all the tables for sure.
Third, you should be able to use multiple inserts like you are doing in your code. but you need to correct your syntax errors.
Try this code (I also removed the select code are based on your question it is not needed)
if (isset($_POST['n_submit'])){
$oid = $_POST['oid'];
$odate = $_POST['odate'];
$ostatus = $_POST['ostatus'];
$cfname = $_POST['cfname'];
$cname = $_POST['clname'];
$efname = $_POST['efname'];
$elname = $_POST['elname'];
$db = mysqli_connect('127.0.0.1:3307', 'mysql_user', 'mysql_password') or die ("I cannot connect to the database because: ".mysqli_connect_error());
$query1 = "insert into cust (c_fname, c_lname) values ('".$cfname."', '".$clname."')";
$result1 = mysqli_query($db, $query1) or die("Error in SQL statement:" .mysqli_error());
$query2 = "insert into employed (e_fname, e_lname) values ('".$efname."', '".$elname."')";
$result2 = mysqli_query($db, $query2) or die("Error in SQL statement:" .mysqli_error());
$query3 ="INSERT INTO sorder (o_id, o_date, s_id) VALUES ('".$oid."', '".$odate."', '".$statusid."')";
$result3 = mysqli_query($db, $query3);
if($result1 && $result2 && $result3)
echo 'New record created successfully';
else
echo 'something did not work';
}

PHP: mysqli_query is not working [duplicate]

This question already has answers here:
php/mysql with multiple queries
(3 answers)
Closed 3 years ago.
I've a doubt with mysqli_query..
this is a part of my code:
$con = db_connect();
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
$result = mysqli_query($con, $sql);
return $result;
I can't do the query...
If I try to do a query like this:
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
It works.
What's the problem?? I can't use SET with mysqli_query?
Thanks
You can not execute multiple queries at once using mysqli_query but you might want to use mysqli_multi_query as you can find out in the official documentation:
http://www.php.net/manual/en/mysqli.multi-query.php
Lets start with creating a working php script.
<?php
// replace for you own.
$host ="";
$user = "";
$password = "";
$database = "";
$con= mysqli_connect($host, $user, $password, $database);
if (!$con)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else{
// Begin SQL query
$sql = "SELECT * FROM users";
$result = mysqli_query($con,$sql) OR Die('SQL Query not possible!');
var_dump($result);
return $result;
var_dump($result);
// End SQL query
mysqli_close($con);
};
?>
INSERT query:
$sql= "INSERT INTO categorias(name) VALUES ('ssss')";
mysqli_query ($con,$sql) OR Die('SQL Query not possible!');
UPDATE and DELETE query:
$sql= "DELETE FROM users WHERE username = 'Hola';";
$sql.= "UPDATE users SET foreign_key_checks = 0 WHERE username = 'Hola'"; /* I made a guess here*/
mysqli_multi_query ($con,$sql) OR Die('SQL Query not possible!');
Check the SET query. I think something is missing. I have changed it to what I think was your aim.
The connection should be established like this:
$Hostname = "Your host name mostly it is ("localhost")";
$User = "Your Database user name default is (root)"//check this in configuration files
$Password = "Your database password default is ("")"//if you change it put the same other again check in config file
$DBName = "this your dataabse name"//that you use while making database
$con = new mysqli($Hostname, $User , $PasswordP , $DBName);
$sql= "INSERT INTO categorias(id_categoria,name) VALUES ('15','ssss');";
In this query:
put categorias in magic quotes(`) and column names also
For your next query do this:
$sql= "SET foreign_key_checks = 0; DELETE FROM users WHERE username = 'Hola';";
Change to:
$sql= "SET foreign_key_checks = 0; DELETE FROM `users` WHERE `username` = 'Hola'";

how to use php variables in postgresql query

I have two php variables, one integer and other json, which I convert into string variable and then inserting them inside a postgresql database.
Converting integer into string variable:
$string1 = (string)$integer;
Coneverting json from facebook api into string variable:
$string2 = json_encode($json);
Now, I have to insert these two string variables into postgres database:
$query = "INSERT INTO interests VALUES(". $string1 ." ," . $string2 .")";
pg_query($con, $query) or die("Cannot execute query: $query\n");
This is not working. I have tried a lot of solutions but still not working.
I changed my function to insert into database
function push_interests(){
$id = $facebook->getUser();
$int = $facebook->api('/me/interests');
$host = "hostname";
$user = "user";
$pass = "password";
$db = "database";
$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");
$id = (string)$id;
$int = json_encode($int);
$sql = "INSERT INTO interests VALUES($1,$2)";
pg_prepare($con,'my_insert', $sql) or die ("Cannot prepare statement1\n") ;
pg_execute($con,'my_insert', array($id,$int)) or die ("Cannot execute statement1\n");
pg_close($con);
}
Output is: cannot execute statement1
I have created database as below:
$query = "DROP TABLE IF EXISTS interests";
pg_query($con, $query) or die("Cannot execute query: $query\n");
$query = "CREATE TABLE interests(id VARCHAR(25) PRIMARY KEY, interests VARCHAR(500))";
pg_query($con, $query) or die("Cannot execute query: $query\n");
Because strings need to be surrounded with simple quotes. I would strongly advise you use prepared statements to ignore these kind of problems and ensure correct variable escaping to prevent your application from beeing hacked trough SQL injection.
$sql = "INSERT INTO interests VALUES ($1, $2)";
$result = pg_prepare($con, 'my_insert', $sql);
$result = pg_execute($con, 'my_insert', array($string1, $string2));
See http://php.net/manual/en/function.pg-prepare.php
Edit: Here is the actual code I've tested:
<?php
$con = pg_connect('')
or die ("Could not connect to server\n");
$id = (string) 5;
$int = json_encode(array('pika' => 'chu', 'plop' => array(1, 2, 3)));
$query = "CREATE TABLE interests(id VARCHAR(25) PRIMARY KEY, interests VARCHAR(500))";
pg_query($query) or die('creating table failed.');
$sql = "INSERT INTO interests (id, interests) VALUES ($1, $2)";
pg_prepare('my_query', $sql);
pg_execute('my_query', array($id, $int)) or die("Error while inserting.");

Categories