I need to write a script which will take the values from two columns and use them to update the column in a view that I created in another database. In the first database I have sku and qty as well as in the view.
here is my code:
$server = 'localhost';
$user = 'invodata';
$pass = 'Abcd1234!1';
$dbname = 'tboinvodata';
$con = mysql_connect($server, $user, $pass) or die("Can't connect");
mysql_select_db("tboinvodata") or die(mysql_error());
$result = mysql_query("SELECT item, onhand FROM immaster"); <- this is getting the values from the columns in the first data base
$server = 'localhost';<-setting up my second connection to other database
$user = 'tbo';
$pass = 'Abcd1234!1';
$dbname = 'i187358_mage1';
$con = mysql_connect($server, $user, $pass) or die("Can't connect");
mysql_select_db("i187358_mage1") or die(mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {<-this gets the array from other database
UPDATE qtyview SET qty = $row["onhand"] WHERE sku = item;<- this should update the necessary columns "sku" is used in my view and "item" is used in the first data base I use this so the proper rows in the other columns get updated.
}
?>
really not sure what I am doing wrong I am pretty new to this though.
You can make multiple calls to mysql_connect() and use them like this.
First connect to two your MYSQL USER
$con1 = mysql_connect($server, $user, $pass);
$con2 = mysql_connect($server, $user, $pass, true);
Then establish a connect with different DATABASE
mysql_select_db('firstdatabase', $con1);
mysql_select_db('seconddatabase', $con2);
Then query from firstdatabase like this
mysql_query('select * from views', $con1);
And query from seconddatabase
mysql_query('select * from views', $con2);
This code is not tested by me...but i think it will work good for you.. :)
Related
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.
I am new in PHP. I use session first time. I have two tables in db. First table with name pacra_teams with column id and title. Second table is og_users with multiple column but i use team_title as foreign key as store id against team title.
Now i want to create a session and want to display team name from table pacra_teams and user name from table og_users.
I try following code but i failed.
<?php
// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
// setting variable values during session
$_SESSION['og_users.username']=$username;
$_SESSION['pacra_teams.title']=$title;
?>
call these variables
<?php
session_start();
?>
<?php
print_r($_SESSION);
?>
Please help me how i can do this?
One Thing More. if i run seesion.php page it display undefine variable "title"
and if i run print code. It display username "root" but i dont have any user name root in my db
You already defined a query but didn't execute it.
// starts session
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql="SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
LIMIT 1
";
$result = $conn->query($sql);
$row = $result->fetch_object();
// setting variable values during session
$_SESSION['og_users.username'] = $row->USER_NAME; // Change to correct column name in table og_users
$_SESSION['pacra_teams.title'] = $row->TITLE_COLUMN_NAME; // Change to correct column name in table pacra_teams
The result will be the same every time without a WHERE clause in your sql statement. It's only going to return the first row it finds. It looks like you're trying to set user information in a session variable so you can call the data throughout your application so here's a possible solution assuming you grab an ID for the user somewhere (IE web form).
This is a simple answer to explain a concept, not a tutorial.
<?php
//Setup your connection stuff here
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pacra1";
//Get a user's name from a form
$userName = $_POST['username'];
// Perform your query
$db= new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT *
FROM og_users
LEFT JOIN pacra_teams
ON og_users.id = pacra_teams.id
WHERE og_users.username = {$userName} LIMIT 1";
if(!$result = $db->query($sql)){
die('Error [' . $db->error . ']');
}
// Setting variable values during session
while($row = $result->fetch_assoc()) {
$_SESSION['ogUsername'] = $row['USERNAME']; // USERNAME is a placeholder for the example
$_SESSION['pacraTeamsTitle'] = $row['TITLE']; // Same here
}
It's not perfect, but hopefully it helps explain the concept and helps you complete your task.
I am trying to update for some products their category in database. I want to find products that have in their name a specific word and after that I want to update the category for this products.
I want to select IDs from sho_posts where sho_posts.post_title contain this part of word '%Audio CD%' and after that to update the sho_term_relationships.term_taxonomy_id with value 2 where sho_term_relationships.object_id=sho_posts.id.
I wrote a little PHP code but it make only selection part. What is wrong?
<?php
$username = "user_name";
$password = "password";
$hostname = "host";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("1812233_shoping",$dbhandle)
or die("Could not select examples");
echo "Connected to MySQL<br>";
$result = mysql_query ("SELECT `id` FROM `sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%' ");
while ($row = mysql_fetch_array($result)) {
echo "ID:".$row{'id'}."<br>";
}
$sql = "UPDATE 'sho_term_relationships'
SET 'term_taxonomy_id' = '123'
WHERE 'object_id' = $row";
//close the connection
mysql_close($dbhandle);
My new cod for script now is:
$username = "_shoping";
$password = "password";
$hostname = "localhost";
//connection to the database
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
$selected = mysql_select_db("_shoping",$dbhandle)
or die("Could not select examples");
echo "Connected to MySQL<br>";
$result = mysql_query ("SELECT `id` FROM `sho_posts` WHERE CONVERT(`post_title` USING utf8) LIKE '%Audio CD%' ");
while ($row = mysql_fetch_array($result)) {
$id[] = $row['id'];
/*echo "ID2:".$id."<br>";*/
}
foreach ($id as $value) {
echo "value:".$value."<br>";
}
/*$id = $row['id'];*/
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = '123'
WHERE object_id =".$value;
mysql_query($sql);
//close the connection
mysql_close($dbhandle);
now it make an update but only for one row, how to make for all rows? From select query I get 4 result
Try this:
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = '123'
WHERE object_id = ".$row{'id'};
And make sure to run the query mysql_query($sql)
Also, I think you might want to add this query inside the while loop
You are using single quotes instead of backticks (which are in this case not necessary). Change your update query to this:
$sql = "UPDATE sho_term_relationships
SET term_taxonomy_id = 123
WHERE object_id = $row";
Also, you are missing some pieces of your code; nothing will be called on that query. It's not being executed at all.
Also you have some other problems here, mainly due to the high risk of sql injection. First of all stop using mysql_ functions, they are deprecated. You should prepare your variables. Here's a demonstration of the key parts of your script in mysqli_ format.
This should also solve most of your issues (there may be a few more if I don't full understand your original question).
You would call your database like this (and check for errors)
$dbhandle = new mysqli($hostname, $username, $password);
if ($dhandle->connect_error) {
die("Connection failed: " . $dbhandle->connect_error);
}
Then you would select your data like this (assuming that term might not be the same every time, and might be coming from a post variable named search).
Edit: For example, if you have an HTML form that is getting this variable like so:
<input type="select" name="search_term" />
you name the variable like this:
$search = $_POST['search_term'];
and then you set it up for your query for the like operator
$search_term = '%'.$search.'%';
$result = $dbhandle->prepare("SELECT `id`
FROM `sho_posts`
WHERE CONVERT(`post_title` USING utf8)
LIKE ? ");
$result->bind_param("s",$search_term);
$result->execute();
$result->bind_result($id);
And then you can get your data through the while loop like so
while ($result->fetch()) {
... stuff you want to do here...
}
$result->close();
Then you would use this in your update query (which would take a similar syntax), and you can just get the information from $id which was created with the bind_result above:
$sql = $dbhandle->("UPDATE sho_term_relationships
SET term_taxonomy_id = 123
WHERE object_id = ?");
$sql->bind_param("s",$id);
$sql->execute();
$sql->close();
It may take a little bit to get used to this, but I find it easier to parse, and also is much more secure
I've got two different sites. What I'd like to do is to automatically run a script that sends some of the data inserted into the database in site 1 when a user registers and updates a table in the database for site 2 so that an account is automatically created in site 2 using the same details.
I'm at the stage of trying to create a query that will update the database. I'm the self-made type so don't know that well what I'm doing. Got this query from somewhere but can't make it work. Can anyone tell what's wrong with it? It's not executing the query.
Thanks!
Eugenie
<?php
$host = "localhost"; // Host name
$username = "----"; // Mysql username
$password = "----"; // Mysql password
$db_name1 = "------"; // Database name
$db_name2 = "-----"; // Database name
$tbl_name1 = "-----"; // Table name
$tbl_name2 = "---"; // Table name
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name1")or die("cannot select DB");
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name2")or die("cannot select DB");
$query = "USE $db_name2
UPDATE $db_name2.dbo.$tbl_name2
SET email=d2.email FROM $db_name1.dbo.$tbl_name1 d2
WHERE d2.uid = $tbl_name1.uid";
$result = mysql_query($query) or die ("could't execute query.");
?>
<?php
$host = "localhost"; // Host name
$username = "----"; // Mysql username
$password = "----"; // Mysql password
$db_name1 = "------"; // Database name
$db_name2 = "-----"; // Database name
$tbl_name1 = "-----"; // Table name
$tbl_name2 = "---"; // Table name
$conn = mysql_connect($host, $username, $password);
mysql_select_db($db_name1, $conn) or die("cannot select DB");
mysql_select_db($db_name2, $conn) or die("cannot select DB");;
$query1 = "SELECT * FROM `" . $db_name1.$tb1_name1 . "` ";
$query2 = "SELECT * FROM `" . $db_name2.$tb1_name2 . "` ";
You can fetch data of above query from both database as below
$result1 = mysql_query($query1);
while($row = mysql_fetch_assoc($result1)) {
$data1[] = $row;
}
$result2 = mysql_query($query2);
while($row = mysql_fetch_assoc($result2)) {
$data2[] = $row;
}
print_r($data1);
print_r($data2);
?>
Suggestion: Try shifting to mysqli or PDO since mysql is depreciated now.
Recall the documentation for mysql_connect:
Returns a MySQL link identifier on success or FALSE on failure.
... and the documentation for the second parameter for mysql_query:
The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed. If no such link is found, it will try to create one as if mysql_connect() was called with no arguments. If no connection is found or established, an E_WARNING level error is generated.
... should solve your problem. Example:
$link1 = mysql_connect( ... ); // For db 1.
$link2 = mysql_connect( ... ); // For db 2.
$result1 = mysql_query( "some query for db 1", $link1 );
$result2 = mysql_query( "some query for db 2", $link2 );
Well,
first of all, you're not connecting to two different databases, but using two different schemas in the same database. So only a mysql_connect should be used.
Also, if you're using full qualified names to access your tables you don't need to call mysql_select_db, nor the 'use db_name' mysql command.
Your query string is wrong. After USE $db_name2 you should have a semi-colon, and the update sentence is not correct.
Code could be somthing like that:
mysql_connect(...)
$query = "update $db2.$table2, $db1.$table1
im having problems in PHP with selecting Infomation from a database where username is equal to $myusername
I can get it to echo the username using sessions from the login page to the logged in page.
But I want to be able to select things like 'bio' and 'email' from that database and put them into variables called $bio and $email so i can echo them.
This is what the database looks like:
Any ideas?:/
You should connect to your database and then fetch the row like this:
// DATABASE INFORMATION
$server = 'localhost';
$database = 'DATABASE';
$dbuser = 'DATABASE_USERNAME';
$dbpassword = 'DATABASE_PASSWORD';
//CONNECT TO DATABASE
$connect = mysql_connect("$server", "$dbuser", "$dbpassword")
OR die(mysql_error());
mysql_select_db("$database", $connect);
//ALWAYS ESCAPE STRINGS IF YOU HAVE RECEIVED THEM FROM USERS
$safe_username = mysql_real_escape_string($X);
//FIND AND GET THE ROW
$getit = mysql_query("SELECT * FROM table_name WHERE username='$safe_username'", $connect);
$row = mysql_fetch_array($getit);
//YOUR NEEDED VALUES
$bio = $row['bio'];
$email = $row['email'];
Note 1:
Dont Use Plain Text for Passwords, Always hash the passwords with a salt
Note 2:
I used MYSQL_QUERY for your code because i don't know PDO or Mysqli, Escaping in MYSQL is good enought but Consider Using PDO or Mysqli , as i don't know them i can't write the code with them for you
Simplistic PDO examples.
Create a connection to the database.
$link = new PDO("mysql:host=$db_server;dbname=$db_name", $db_user, $db_pw, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Use the $link variable when creating (preparing) and executing your SQL scripts.
$stmt = $link->prepare('insert into `history` (`user_id`) values(:userId)');
$stmt->execute(array(':userId' => $userId));
Code below will read data. Note that this code is only expecting one record (with 2 data elements) to be returned, so I'm storing whatever is returned into a single variable (per data element), $webId and $deviceId.
$stmt = $link->prepare('select `web_id`, `device_id` from `history` where `user_id` = :userId');
$stmt->execute(array(':userId' => $userId));
while($row = $stmt->fetch()) {
$webId = $row["web_id"];
$deviceId = $row["device_id"];
}
From the picture I can see you are using phpMyAdmin - a tool used to handle MySQL databases. You first must make a connection to the MySql server and then select a database to work with. This is shown how below:
<?php
$username = "your_name"; //Change to your server's username
$password = "your_password"; //Change to your server's password
$database = "your_database" //Change to your database name
$hostname = "localhost"; // Change to the location of your server (this will prolly be the same for you I believe tho
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$selected = mysql_select_db($database, $dbhandle)
or die("Could not select examples");
?>
Then you can write something like this:
<?php
$bio = mysql_query("SELECT bio FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
and
<?php
$email = mysql_query("SELECT email FROM *your_database_table_name* WHERE username='bob' AND id=1");
?>
Where *your_database_table_name* is the table in the database you selected which you are trying to query.
When I was answering your question, I was referencing this site: http://webcheatsheet.com/PHP/connect_mysql_database.php. So it might help to check it out as well.