I want to retrieve two different fields residing in different data bases. My db connection settings are this:
define ('DB_HOST', 'ipaddress1');
define ('DB_USER', 'username1');
define ('DB_PASSWORD', 'password1');
define ('DB_DATABASE', 'ecbooks');
$db_wink = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, TRUE) or die("Connection Error: " . mysql_error());
mysql_select_db(DB_DATABASE) or die("Error connecting to Winkstore DB. " . mysql_error());
// DB configuration parameters : magonwink
define ('DB_REMOTE_HOST', 'ipaddress2');
define ('DB_REMOTE_USER', 'username2');
define ('DB_REMOTE_PASSWORD', 'password2');
define ('DB_REMOTE_DATABASE', 'magsonwink');
$db_magson = mysql_connect(DB_REMOTE_HOST, DB_REMOTE_USER, DB_REMOTE_PASSWORD, TRUE) or die("Connection Error: " . mysql_error());
mysql_select_db(DB_REMOTE_DATABASE, $db_magson) or die("Error connecting to magson wink DB. " . mysql_error());
define ('CMS_DB_HOST', 'ipaddress3');
define ('CMS_DB_USER', 'username3');
define ('CMS_DB_PASSWORD', 'password3');
define ('CMS_DB_DATABASE', 'mawinkcms');
$db_rp = mysql_connect(CMS_DB_HOST, CMS_DB_USER, CMS_DB_PASSWORD, true) or die("Connection Error: " . mysql_error());
mysql_select_db(CMS_DB_DATABASE, $db_rp) or die("Error connecting to DB. " . mysql_error());
but when I used this query
SELECT ecbooks.user.user_name AS field1, mawinkcms.purchase.USER_NAME AS field2 FROM ecbooks.user,mawinkcms.purchase
$result = mysql_query($query, $db_wink) or die("Couldn't execute query: " . mysql_error());
while($row = mysql_fetch_assoc($result)){
$users[] = $row;
}
I got an error could not execute the query. Thanks in advance.
You have to pass the correct link identifier to the mysql_query function as the second parameter: http://www.php.net/mysql_query
$ecbooks does not exist (based on the code you provided).
In your case if the table you want to access is in the ecbooks database, you have to pass $db_wink to mysql_query.
But since you are trying to access two different databases in the same query, you will have to connect to the database with a user that has access to both databases. Posting the actual error you get would also help.
ps: please stop usingng this extension to access MySQL. See here for details.
Firstly, when asking for help with an error, it's a good idea to include the error itself.
Secondly, your query doesn't appear to have a join condition, so you will get back the cartesian product if you do get it to go - that's probably not what you want.
Thirdly, when running a query, it runs against the database you connected to, regardless of whether you've connected to any others. So, in your example, you're running a query against $db_wink; the other two connections don't affect this at all.
For the query to work, the user who connected to $db_wink needs to have permissions on the databases ecbooks and mawinkcms, and mawinkcms must be running on the same server as ecbooks.
I'm guessing that either the permissions are not set up, or you're running them on different databases.
Related
I have written that seems to not be working, but MySQL does not return any error. It is supposed to get data from database1.table to update database2.table.column
<?php
$dbh1 = mysql_connect('localhost', 'tendesig_zink', 'password') or die("Unable to connect to MySQL");
$dbh2 = mysql_connect('localhost', 'tendesig_zink', 'password', true) or die("Unable to connect to MySQL");
mysql_select_db('tendesig_zink_dev', $dbh1);
mysql_select_db('tendesig_zink_production', $dbh2);
$query = " UPDATE
tendesig_zink_dev.euid0_hikashop_product,
tendeig_zink_production.euid0_hikashop_product
SET
tendesig_zink_dev.euid0_hikashop_product.product_quantity = tendesig_zink_production.euid0_hikashop_product.product_quantity
WHERE
tendesig_zink_dev.euid0_hikashop_product.product_id = tendesig_zink_production.euid0_hikashop_product.product_id";
if (mysql_query($query, $dbh1 ))
{
echo "Record inserted";
}
else
{
echo "Error inserting record: " . mysql_error();
}
?>
The manual page for mysql_error() mentions this about the optional parameter you're omitting:
link_identifier
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.
So it's reading errors from $dbh2, which is the last connection you've opened. However, you never run any query on $dbh2:
mysql_query($query, $dbh1 )
Thus you get no errors because you are reading errors from the wrong connection.
The solution is to be explicit:
mysql_error($dbh1)
As about what you're trying to accomplish, while you can open as many connections as you want, those connections won't merge as you seem to expect: they're independent sessions to all effects.
All your tables are on the same server and you connect with the same users, there's absolutely no need to even use two connections anyway.
You can't just issue a cross-database update statement from PHP like that!
You will need to execute a query to read data from the source db (execute that on the source database connection: $dbh2 in your example) and then separately write and execute a query to insert/update the target database (execute the insert/update query on the target database connection: $dbh1 in your example).
Essentially, you'll end up with a loop that reads data from the source, and executes the update query on each iteration, for each value you're reading from the source.
I appreciate everyone's help/banter, here is what finally worked for me.
<?php
$dba = mysqli_connect('localhost', 'tendesig_zink', 'pswd', 'tendesig_zink_production') or die("Unable to connect to MySQL");
$query = " UPDATE
tendesig_zink_dev.euid0_hikashop_product, tendesig_zink_production.euid0_hikashop_product
SET
tendesig_zink_dev.euid0_hikashop_product.product_quantity = tendesig_zink_production.euid0_hikashop_product.product_quantity
WHERE
tendesig_zink_dev.euid0_hikashop_product.product_id = tendesig_zink_production.euid0_hikashop_product.product_id";
if (mysqli_query($dba, $query))
{
echo "Records inserted";
}
else
{
echo "Error inserting records: " . mysqli_error($dba);
}
?>
I am trying to connect to a mysql database within a php script. So far, my code looks like
//to my knowledge, this works. I was able to echo out the correct name
$name = $_POST["name"];
$server_name = "localhost";
$user_name = //my user name
$password = //my password
$db_name = //the db name
//it passes this error check, so I am connecting properly I am assuming
$dbconn = mysql_connect($server_name, $user_name, $password)
or die ('Could not connect to database: ' . mysql_error());
mysql_select_db($db_name, $dbconn);
$query = "SELECT *
FROM brothers
WHERE name = '$name'";
//it DOES NOT make it past this one
$result = mysql_query($query)
or die('Bad Query: ' . mysql_error());
//filter through the query as a row
$row = mysql_fetch_array($result, MYSQL_ASSOC);
//echo the result back to the user
echo $row["name"];
echo $row["major"];
//close the connection
mysql_close($dbconn);
I keep getting the error "No Database Selected", even though I am sure that I spelled the database name correctly (I copy pasted). Does anyone know why my code might be throwing this error?
Could be a permissions issue(the user which logon maybe don't have read rights on the database) :
mysql_select_db() fails unless the connected user can be authenticated
as having permission to use the database.
Here's my comment in answer form:
Do the same or die ('Could not use DB: ' . mysql_error()) after the mysql_select_db() call to find out what's going on there.
Your comment ("access denied") suggests that you have permissions to connect to the database server but not to use the database. Remember that one database server can have multiple databases on it, each with their own permission scheme. Check the permissions on the database you're trying to use and make sure that $user_name can use it with $password.
How do I create a database if it doesn't exist, using PHP?
Presuming you're talking about a MySQL database - you want to use mysql_query and mysql_select_db.
Note that mysql_create_db is deprecated.
<?php
// Connect to MySQL
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
// Make my_db the current database
$db_selected = mysql_select_db('my_db', $link);
if (!$db_selected) {
// If we couldn't, then it either doesn't exist, or we can't see it.
$sql = 'CREATE DATABASE my_db';
if (mysql_query($sql, $link)) {
echo "Database my_db created successfully\n";
} else {
echo 'Error creating database: ' . mysql_error() . "\n";
}
}
mysql_close($link);
?>
Since you mention WAMP I'll assume you're talking about MySQL.
It can be tricky. Assuming that your PHP script runs with all the required credentials (which is by itself a questionable idea), you can run this query:
SHOW DATABASES
If the DB does not show up there, you can assume it doesn't exist and create it with one of these queries:
CREATE DATABASE foo ....
or:
CREATE DATABASE IF NOT EXISTS foo ...
Right after that, you need to check the return value for whatever PHP function you are using (e.g. mysql_query). The above queries will fail if your user is now allowed to see all the existing databases or it's not allowed to create new databases.
In general, I find the whole concept kind of scary. Handle it with care! ;-)
So a friend of mine and I are using both xampp on ubuntu, if that helps, to connect between each other's website, We both created the same php file to connect, so we use de IP of the other, but then it says an error
Warning: mysql_connect() [function.mysql-connect]: Host 'coke-laptop.local' is not allowed to connect to this MySQL server in /opt/lampp/htdocs/connection.php on line 2
Could not connect: Host 'coke-laptop.local' is not allowed to connect to this MySQL server
We have this code on the connection.php file:
<?php
$link = mysql_connect('10.100.161.37','root','');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//echo 'Connected successfully';
$db_selected = mysql_select_db('Prueba', $link);
if (!$db_selected) {
die ('Can\'t use Prueba : ' . mysql_error());
}
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT * FROM Agencia");
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['ID'] . " ";
echo $row['Nombre'] . "\n\r";
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
mysql_close($link);
?>
If we use the IP just like that, we can enter each others xampp normal welcome page.
Check you have enabled remote access to the MySQL server. Open the my.cnf file (probably found inside xampp/etc/), go to the [mysqld] section and add the following (using your own ip address instead of the example)
bind-address=192.168.1.100
If there is a line that says skip-networking, comment that out so it looks like this:
# skip-networking
then restart the MySQL server
It looks like your MySQL database isn't allowing you to connect remotely with the credentials you provided. You will need to configure a remote user to connect. Try looking into MySQL Grants.
For Example:
GRANT SELECT, INSERT ON database.* TO 'someuser'#'somehost';
I have a question about PHP Class. I am trying to get the result from Mysql via PHP. I would like to know if the best practice is to display the result inside the Class or store the result and handle it in html.
For example, display result inside the Class
class Schedule {
public $currentWeek;
function teamQuery($currentWeek){
$this->currentWeek=$currentWeek;
}
function getSchedule(){
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$scheduleQuery=mysql_query("SELECT guest, home, time, winner, pickEnable FROM $this->currentWeek ORDER BY time", $connection);
if (!$scheduleQuery){
die("database has errors: ".mysql_error());
}
while($row=mysql_fetch_array($scheduleQuery, MYSQL_NUMS)){
//display the result..ex: echo $row['winner'];
}
mysql_close($scheduleQuery);
//no returns
}
}
Or return the query result as a variable and handle in php
class Schedule {
public $currentWeek;
function teamQuery($currentWeek){
$this->currentWeek=$currentWeek;
}
function getSchedule(){
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
$scheduleQuery=mysql_query("SELECT guest, home, time, winner, pickEnable FROM $this->currentWeek ORDER BY time", $connection);
if (!$scheduleQuery){
die("database has errors: ".mysql_error());
// create an array }
$ret = array();
while($row=mysql_fetch_array($scheduleQuery, MYSQL_NUMS)){
$ret[]=$row;
}
mysql_close($scheduleQuery);
return $ret; // and handle the return value in php
}
}
Two things here:
I found that returned variable in php is a little bit complex to play with since it is two dimension array. I am not sure what the best practice is and would like to ask you experts opinions.
Every time I create a new method, I have to recreate the $connection variable: see below
$connection = mysql_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DB_NAME,$connection);
if (!$db_select) {
die("Database selection failed: " . mysql_error());
}
It seems like redundant to me. Can I only do it once instead of calling it anytime I need a query? I am new to php class. hope you guys can help me. thanks.
I treat classes like these as 'accessors' so they purely query the database and return the result. That way any PHP code which calls it can do whatever it likes with it. this may be displaying or it may be a check or it may be an update. This is good design as it separates the datastore from the logic from the display and means your code will be more flexible. But yes, it is a little more complex.
In regards to re-creating the connection each time. This may or may not be necessary. Depending on your setup you may be able to create a connection pool. To make it easier for you for now, you can abstract the creation of a connection to its own method. This way you only need to call this method at the start to get a connection handle. This saves you from having many copies of the same code all over the place.
If you are new to PHP classes I suggest doing a bit of research on object oriented design. This will give you an idea on why it would be beneficial to abstract some functions, and also why you would want to return the results instead of displaying them.
Its probably a bad idea to echo the result int he class nstead you should return the result or result set for echoing else where.
May the connection a mebmer of the class like:
protected $_connection = null;
Then in your constructor you can assign the database connection. Though normally your db connection would be wrapped by yet another class.
Additionally if i were you i would not use the mysql functions. Instead use the Mysqli or PDO_Mysql drivers. They encapsulate all this functionality in an object orientend manner by default. You can then extend those classes with your custom functionality instead of working from scratch.