How select from one MYSQL DB and insert it into another? - php

I'm running some small Updates via CRON and execute them with PHP.
Now I want to select something from DB1 and insert it into DB2
My Problem is, that these 2 DBs are on the same Server but with 2 different Users and its not possible to give 1 User permission to both DB's.
So I know this works with one user and dbconnect:
insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)
How can I do it with 2 db connects in one Loop?
Thanks

you can create two files of connection like this
<?PHP
function connect(){
$servername = "localhost";
$username = "user";
$password = "psw";
$database = "database";
$conn = new mysqli($servername, $username, $password, $database);
if(mysqli_connect_errno()){
echo "Error conectando a la base de datos: " . mysqli_connect_error();
exit();
}
else{
$conn->query("SET NAMES 'utf8'");
return $conn;
}
}
function disconnect($connection){
$disconnect = mysqli_close($connection);
}
?>
and in your php file and like this
require("connection.php");
$connection=connect();
require("connection2.php");
$connection2=connect2();
obviously in your connection2.php your funtion named connect2(); and in your loop you can use the two connection
$query="insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)";
$messageResult = "Good";
$band = true;
if(!($connection -> query($query))){
$messageResult = "Error";
$band = false;
}
or..
$query="insert into db1.tbl1(data1,data2) values (select data2, data1 from db2.tbl2)";
$messageResult = "Good";
$band = true;
if(!($connection2 -> query($query))){
$messageResult = "Error";
$band = false;
}

If u r using pdo. U declare 2 different connection.
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass)
$dbh2 = new PDO('mysql:host=localhost;dbname=test', $user2, $pass)
Then u do this
$query = $dbh->prepare(select statement);
$query->execute();
$data = $query->fetchAll(); // you get array of data
$query = $dbh2->prepare(insert statement);
$query->execute()

Create 2 dB connection in two different variable and make that work .... Take value of first db in one variable and simply dump that variable into second db .... Or you can use another dB or caching dB like redis to store one time temporary base.

Related

how to make a query with database as a variable

I have two databases - lorem and nts.lorem - and need to operate with both of them
$user = 'root';
$pass = '';
$db1 = new PDO('mysql:host=localhost; dbname=nts.lorem', $user, $pass);
$db2 = new PDO('mysql:host=localhost; dbname=lorem', $user, $pass);
everything works fine until db is a variable in an ajax request - for example:
js
var db;
if(something is true){db = 'db1';};
else{db = 'db2';}
//... ajax post code
php
function something($db){
global $db1, $db2;
// how to say the next line
$sq = "select id from " . $db . ".tableName order by title asc";
// error - table db1.tableName doesn't exist
}
any help?
Choose connection according to $db value:
function something($db){
global $db1, $db2;
$sq = "select id from tableName order by title asc";
if ($db === 'db1') {
$db1->execute($sq);
} else {
$db2->execute($sq);
}
// rest of the code
}
Add the line that executes the query to your code sample. Without it, it's hard to be sure what's wrong, but I can guess: you don't need the name of the database in the query text, you need to execute the query with the proper database connection, based on the parmeter received from the client.
Something like:
function something($db){
global $db1, $db2;
$sq = "select id from tableName order by title asc";
$stmt = $db === 'db1' ? $db1->query($sq) : $db2->query($sq);
$result = $stmt->fetch();
}
Comment: this assumes you have a table called tableName in both databases.

PHP PDO always give only one result

I wrote a SQL query with PDO. DB table has 3 results with match the query. But the PDO shows only one result.
my code is this
conn.php
function connect() {
$servername = "localhost";
$dbname = "guiding_db";
$username = "user";
$password = "pass";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
_admin.php
include_once './conn.php';
function getStudentsRequests(){
$sql = "SELECT * FROM `user` WHERE signas = 'student' AND accept='0'";
$result = connect()->query($sql);
$out = $result->fetch(PDO::FETCH_ASSOC);
print_r($out);
return $out;
}
getStudentsRequests();
PDOStatement::fetch() loads a single row only. Use PDOStatement::fetchAll() to load all rows (or use a while loop):
$out = $result->fetchAll(PDO::FETCH_ASSOC);
fetch method return only one row from query. If you want all you need to use while loop or fetchAll method
fetch method return next result (one). If you wish get all results - use methods like fetchAll

Connect to Multiple Databases using MySQLi

I need to connect to two databases using PHP and use the results from the first query to get the rest of the data I need out of a second database.
So for the second connection, I need to connect to the second database and Select state and zipcode where the results from connection 1 (client) is equal to the firstname in database 2. How would I do this?
<?php
// check if the 'id' variable is set in URL, and check that it is valid
if (isset($_GET['cd']) && is_numeric($_GET['cd'])) {
// get id value
$id = intval($_GET['cd']);
}
$results = $id;
//Open a new connection to the MySQL server
require "calendarconnect.php";
//chained PHP functions
$client = $mysqli->query("SELECT client FROM appointments WHERE ID = $results")->fetch_object()->client;
print $client; //output value
$mysqli->close();
Connection To Database Code is similar to the below
<?php
//Open a new connection to the MySQL server
$mysqli = new mysqli('localhost','some database','some password','some username');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
This isn't tested, but I think it would go something like this.
<?php
$dbc1 = new MySQLi()or die('error connecting to database');
$dbc2 = new MySQLi()or die('error connecting to database');
//build query 1
$query1 = "SELECT * FROM Table";
$result1 = $dbc1->query($query) or die("Error in query");
$thing1 = '';
// check result
if($result1->num_rows){
//fetch result as object
$row = $result1->fetch_object();
//set attributes
$thing1 = $row->Name;
}
//build query 2
$query2 = "SELECT * FROM AnotherTable WHERE Id = '$thing1'";
$result2 = $dbc2->query($query) or die("Error in query");
$thing2 = '';
// check result
if($result2->num_rows){
//fetch result as object
$row = $result2->fetch_object();
//set attributes
$thing2 = $row->Name;
}
?>
You would need to make 2 different connections
<?php
$mysqliDB1 = new mysqli('localhost', 'DB1UserId', 'pwd', 'db1');
$mysqliDB2 = new mysqli('localhost', 'DB2UserId', 'pwd', 'db2');
Now when you use the $mysqliDB1->.... you are talking to the DB1 database and when you use the $mysqliDB2->.... you are talking to the DB2 database
So
$client = $mysqliDB1->query("SELECT client FROM appointments WHERE ID = $results")
->fetch_object();
$locn = $mysqliDB2->query("SELECT state,zipcode
FROM location
WHERE ClientID = {$client->FirstName}")
->fetch_object();
echo $locn->state;
echo $locn->zipcode;
I am guessing the table name and so on, but I am not clarevoyant so you will have to fill that in for yourself.
If you want to perform queries in two databases at the same time you need to have two separate mysqli objects. To open the connection you can use the following code:
// Don't forget to enable error reporting!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$db1 = new mysqli('localhost', 'user', 'pass', 'dbName');
$db1->set_charset('utf8mb4'); // always set the charset
$db2 = new mysqli('localhost', 'user', 'pass', 'dbName2');
$db2->set_charset('utf8mb4'); // always set the charset
Then you can perform your two statements in each database separately.
// get id value
$id = intval($_GET['cd']);
// Get client name from DB1
$stmt = $db1->prepare('SELECT client FROM appointments WHERE ID = ?');
$stmt->bind_param('s', $id);
$stmt->execute();
$client = $stmt->get_result()->fetch_object();
// Get state and zipcode from DB2
$stmt = $db2->prepare('SELECT state,zipcode FROM location WHERE ClientName = ?');
$stmt->bind_param('s', $client->client);
$stmt->execute();
$location = $stmt->get_result()->fetch_object();
echo $location->state;
echo $location->zipcode;

Can'nt add data to MySQL with PHP

I was trying to add a new user to the database with the next user id of last user's ID but its not happening.
function addNewUser($addUserName, $addUserEmail, $addUserPassword, $addUserAuthLevel){
$dbHost = "localhost";
$dbUser = "admin";
$dbPassword = "d4shb5w";
$dbName = "masterDatabase";
$connection = mysqli_connect($dbHost,$dbUser,$dbPassword, $dbName);
//test if connection occurred
if(mysqli_connect_errno()){
die("Database connection failed: " . mysqli_connect_error() . "(" . mysqli_connect_errno() . ")");
};
//adding new userInformation into database
$queryLastUserId = "SELECT * FROM userlogindetails ORDER BY userId DESC ";
$LastUserId = mysqli_query($connection, $queryLastUserId);
if($id=mysqli_fetch_assoc($LastUserId)){
$userId=$id["userId"]+1;
}
$userName = mysqli_real_escape_string($connection,$addUserName);
$userEmailId = mysqli_real_escape_string($connection,$addUserEmail);
$userPassword = $addUserPassword;
$passwordHash = password_hash($userPassword, PASSWORD_DEFAULT);
$userAuthLevel= $addUserAuthLevel;
$queryNewUser = "INSERT INTO userlogindetails(userId, userName, userEmailId, userPassword, userLoginTime, userAuthLevel) VALUE ($userId,'$userName', '$userEmailId', '$passwordHash', Now(),'$userAuthLevel')";
$result = mysqli_query($connection, $queryNewUser);
if($result){
mysqli_close($connection);
return "Success "/*.$userId*/;
}else{
mysqli_close($connection);
return "Failed "/*.$userId*/;
}
}
But when I assign usedId statically then it works fine.
What is the problem in the code?
Use the MAX function in a PHP function to get the value. This is a better practice.
function getMaxID($db){
$result = mysqli_query($db, "SELECT MAX(userId) FROM userlogindetails;");
return mysqli_fetch_assoc($result)["MAX(userId)"];
}
Note: I agree with the comments thus far: You should set the primary key to be auto-incrementing. That is an even better practice. MySQL workbench is a great (free) place to start, if you're not yet familiar with data structures.
All this can be done with simply making the id auto_increment in the database. Edit your table.
You need to assign a default value to your $userId variable (e.g. $userId = 1; at the beginning of the function).
If you don't initialize it and in your table there is no users your code will crash.

wrong value from MYSQL using PHP

when running this query in phpMyAdmin, I get the correct values,
but when using the same line in a PHP script,
It always gives x=0 y=0.
All other values are correct only x and y
for some reason return 0.
EDITED not getting the right values
code:
$sql = "select a.image_id as id,
i.image_url as url,
i.image_x as x,
i.image_y as y
from album a
join images i
where a.album_id = 1
and
i.image_id = a.image_id";
echo getFunc($sql);
function getFunc($sql) {
try {
$db = getConnection();
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$db = null;
return json_encode($result);
} catch(PDOException $e) {
echo $e->getMessage();
}
};
function getConnection() {
$dbhost="127.0.0.1";
$dbuser="root";
$dbpass="";
$dbname="efrattest";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec("set names utf8");
return $dbh;
}
mySQL table:
image_id int(11)
image_url varchar(250)
image_x int(9)
image_y int(9)
Thanks everybody,
the problem lays at
$dbhost="127.0.0.1";
I changed that from 'localhost' to '127.0.0.1'
as it was supposed to be better with PDO (A tip I heard online)
changed it back to 'localhost' now everything works as it should.

Categories