PHP - Multi DB Connection suddenly not working - php

I have 2 databases:
news_db. having table : t_news
branding. having table : t_branding
I have db connection:
$con1 = mysql_connect('127.1.0.0', 'root', 'root');
mysql_select_db('news_db', $con1);
$con2 = mysql_connect('127.1.0.0', 'root', 'root');
mysql_select_db('branding', $con2);
My codes:
$dataNews = mysql_fetch_assoc(mysql_query("SELECT * FROM t_news",$con1));
echo $dataNews['title']; /* it is working, showing "Test Title" */
$dataBrand = mysql_fetch_assoc(mysql_query("SELECT * FROM t_branding",$con2));
echo $dataBrand['title']; /* it is not working, nothing to show */
But if i reverse the query like :
$dataBrand = mysql_fetch_assoc(mysql_query("SELECT * FROM t_branding",$con2));
echo $dataBrand['title']; /* it is working, showing "Test Brand Title */
$dataNews = mysql_fetch_assoc(mysql_query("SELECT * FROM t_news",$con1));
echo $dataNews['title']; /* it is not working, nothing to show" */
Can anybody help me, why the sudden php and mysql as though I can only run one connection, but yesterday all of connections can walk and coding nothing has changed. Thanks

The issue is that you're reusing the connection:
Taken from the manual for mysql_connect():
If a second call is made to mysql_connect() with the same arguments,
no new link will be established, but instead, the link identifier of
the already opened link will be returned. The new_link parameter
modifies this behavior and makes mysql_connect() always open a new
link, even if mysql_connect() was called before with the same
parameters. In SQL safe mode, this parameter is ignored.
You should parse the fourth (true which is $new_link) parameter to the second connect like below:
$con1 = mysql_connect('127.1.0.0', 'root', 'root');
mysql_select_db('news_db', $con1);
$con2 = mysql_connect('127.1.0.0', 'root', 'root', true);
mysql_select_db('branding', $con2);
As stated, you should avoid using mysql_* functions as the api IS depreciated.
Alternatively you should be looking into PDO or Mysqli Prepared Statements.
Some More Notes
You should turn on error reporting when developing to ensure you don't run into any issues:
ini_set('display_errors', 1);
error_reporting(E_ALL);
And since you're using mysql, you should look at mysql_error() which probably would've thrown a message something like:
The table TABLENAME doesn't exist in DATABASE

With the code-
$con1 = mysql_connect('127.1.0.0', 'root', 'root');
mysql_select_db('news_db', $con1);
$con2 = mysql_connect('127.1.0.0', 'root', 'root');
mysql_select_db('branding', $con2);
Or,
$con1 = mysql_connect('127.1.0.0', 'root', 'root');
$con2 = mysql_connect('127.1.0.0', 'root', 'root'); // this line is redundant, both lines are same
mysql_select_db('news_db', $con1);
mysql_select_db('branding', $con2); // this will be selected
the effect will be that- the database branding will be selected, news_db wont be selected, coz its written after news_db!
So, your bnoth the queries will look for the database branding and will throw error "Table ...... not found" if you check with mysql_error()

$con1 = mysql_connect('127.1.0.0', 'root', 'root');
mysql_select_db('news_db', $con1);
$dataNews = mysql_fetch_assoc(mysql_query("SELECT * FROM t_news",$con1));
echo $dataNews['name'];
$con2 = mysql_connect('127.1.0.0', 'root', 'root');
mysql_select_db('branding', $con2);
$dataBrand = mysql_fetch_assoc(mysql_query("SELECT * FROM t_branding",$con2));
echo $dataBrand['title'];
You can use this code.I think it will be helpful for you.

Related

How to connect to mysql using pdo

I am working on my php as I want to connect to the mysql database using PDO. I have stored the username, password and database in the config file, but I have got a problem with connecting to the mysql database because I keep getting an error.
When I try this:
<?php
//Connect to the database
include('config.php');
$smtps = $link->query('SELECT * FROM sent');
$smtps->execute();
$db = $smtps->get_result();
print($db);
?>
I am getting an error:
Fatal error: Uncaught Error: Call to undefined method
PDOStatement::get_result() in
/home/username/public_html/test_pdo.php:17 Stack trace: #0 {main}
thrown in /home/username/public_html/test_pdo.php on line 17
Here is the line 17:
$db = $smtps->get_result();
Here is the config:
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'dbtablename');
//$errflag = false;
$link = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME.'', DB_USER, DB_PASS);
?>
Can you please show me an example how do you connect to mysql database using PDO when you stored the username, password and database name in config.php?
Thank you.
This is happening because get_result() is not a PDO method.
In this situation you should just use fetch() (link) if you just want the first result or fetchAll() (link) if you want an array of the results
Try this:
$smtps = $link->query('SELECT * FROM sent');
$result = $smtps->fetchAll();
print($result);
You only need to use the excute() when using parameters in your select:
SELECT * FROM sent where id = ?
would be
$smtps = $link->prepare('SELECT * FROM sent where id = ?');
$smtps->execute([$id]);
$result = $smtps->fetch();
print($result);
If u use query method u can without execute method get result as as below cod
include('config.php');
$result = $link->query('SELECT * FROM sent')->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
get_results is not a method of the PDO class. If you want to fetch data from the database in this case, use fetchAll() method of the query object.
<?php
//Connect to the database
include('config.php');
$smtps = $link->query('SELECT * FROM sent');
$smtps->execute();
$db = $smtps->fetchAll();
print($db);
?>
Hope that helps.

Unknown database 'database_name' in MySQL with WAMPServer

I already have my database named als and I still got the error.
<?php
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con = #mysql_connect($mysql_host,$mysql_user,$mysql_password) or die(mysql_error());
#mysql_select_db($mysql_db) or die(mysql_error());
?>
Not exactly an answer to your question but too long for a comment:
After establishing the database connection you could just query the existing databases via SHOW DATABASES
<?php
$mysqli = new mysqli('localhost', 'root', '');
if ($mysqli->connect_errno) {
trigger_error('query failed: '.$mysqli->connect_error, E_USER_ERROR);
}
$result = $mysqli->query('SHOW databases')
or trigger_error('connect failed: '.join(',', $mysqli->error_list), E_USER_ERROR);
foreach( $result as $row ) {
echo join(', ', $row), "<br />\r\n";
}
Does your database als show up?
Since you're using the default root account (with an empty password; you might want to look into that as well) there shouldn't be any permission related problems. So, if the database doesn't show up, it's just not there...
(almost) same script using PDO (my weapon of choice) instead of mysqli:
<?php
$pdo = new PDO('mysql:host=localhost;charset=utf8', 'root', '', array(
PDO::MYSQL_ATTR_DIRECT_QUERY => false,
PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION
));
foreach( $pdo->query('SHOW DATABASES', PDO::FETCH_NUM) as $row ) {
echo $row[0], "<br />\r\n";
}
There you go. The mysql_ family has been deprecated for some time. Please change to the mysqli_ library. Another machine may work because it's using an older version of PHP in which it hasn't been deprecated OR where deprecated warnings have been globally supressed.
MySQLI Connect
In the wild
$mysql_host='localhost';
$mysql_user='root';
$mysql_password='';
$mysql_db='als';
$con= mysqli_connect($mysql_host,$mysql_user,$mysql_password, $mysql_db) or die("Error " . mysqli_error($con));
There's no need to arbitrarily select the database anymore. Now you can use $con as an argument to the mysqli_ family of procedural functions.
Last, but not least, never debug with the # symbol. This suppresses the error warnings from the function it precedes.

I got 3 Days of PhP please Forgive me but Echo is killing me... What is Wrong?

I tried and read for hours...
I just cant get the last Echo to show a total id count.
I tried insert conditions in Select... Nope...
Please help...
As i said in the title i am new at this.
Doing just for 'fun'
If you could help a newbie out i would appreciate that.
<?php
$dt = new DateTime('');
$dt->setTimeZone(new DateTimeZone('Europe/Lisbon'));
echo $dt->format('d-m-Y | G:i:s');
// START CONECTION TO BD -->
if (isset($_POST['submitted'])) {
DEFINE ('DB_USER', 'YES_I_DID_THIS');
DEFINE ('DB_PSWD', 'THIS_TOO');
DEFINE ('DB_HOST', 'YEAP..I CAN USE THE TABLE FINE.. ITS NOT CONNECTION');
DEFINE ('DB_NAME', 'MYUSER');
$dbcon = mysql_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
$pnome = $_POST['pnome'];
$unome = $_POST['unome'];
$contacto = $_POST['contacto'];
$morada = $_POST['morada'];
$stamp = $_POST['stamp'];
$sqlinsert = "INSERT INTO Contactos (pnome, unome, contacto, morada, stamp) VALUES ('$pnome','$unome','$contacto','$morada','DATE: Auto CURDATE($stamp)')";
if (!mysql_query($dbcon, $sqlinsert)) {
die('');
}
$newrecord = "1 Record added to the Database";
// END INSERT DATA SCRIPT -->
}
// START COUNT TOTAL TABLE ID's
// As i said i am Noob... So i repeat this because i copied it... :)
DEFINE ('DB_USER', '-----------');
DEFINE ('DB_PSWD', '-----------');
DEFINE ('DB_HOST', '---------------');
DEFINE ('DB_NAME', '-----------');
$con = mysql_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
if (!$con) {
die("cant connect: " . mysql_error());
}
mysql_select_db("$con");
$sql = "SELECT id FROM Contactos";
count($t);
//help here please i can't show this '$t' to show at page. Thanks
echo $t ;
?>
You aren't instantiating the $t variable. You kind of need to to be able to get the value and use it.
You would've seen an error about that if you turn on error reporting:
ini_set('display_errors', 1);
error_reporting(E_ALL);
Now your issue. You aren't even running the query.. You need to mysql_query() that $sql. I'd suggest you actually use sql's COUNT() function.
$sql = "SELECT COUNT(id) AS count FROM Contactos";
$query = mysql_query($sql);
if(!$query) {
die(mysql_error());
} else {
$count = mysql_fetch_assoc($query);
echo $count['count']; // should have your count in there.
}
You should stop using mysql_* functions. The library is deprecated.
I do understand that you've just started learning PHP and all, but it's best to start with the right libraries as mysql_* will be removed soon as it's an insecure library.
You should look into using PDO or MySQLi as they are more modern libraries and while you might have to overcome a hurdle to learn it, being competent in those libraries will do you the world of good!
Resources:
PDO
MySQLi

PHP - Selecting database from MySQL doesn't work

I have read a lot about this but it still doesn't work.
I'm just trying to select a database to create a new table in, I try:
$db = mysqli_select_db("test");
if(!$db) {
echo "error: " . mysqli_error($db);
}
But I still get an error (and mysqli_error($db) doesn't seem to work).
Of course I have already connected to it:
$con=mysqli_connect("localhost", "administrator", "****");
On phpMyAdmin I have these databases:
Why can't I select "test" ?
And creating a database doesn't work because I don't have the rights, as you can see.
The procedular signature of this function is:
bool mysqli_select_db ( mysqli $link , string $dbname )
So you will have to provide the resource you got back from the mysqli_connect() to make it work. Something like this:
$con = mysqli_connect("localhost", "administrator", "****");
$success = mysqli_select_db($con, "test");
Alternatively you could specify the database on the connect call with a 4th argument:
$con = mysqli_connect("localhost", "administrator", "***", "test");
See the examples on mysqli_connect().
mysqli_select_db function requires two parameters link and dbname. Please refer to the documentation:
http://php.net/manual/en/mysqli.select-db.php
You are only passing link and no database name in your call:
$db = mysqli_select_db("test");

What is corret way to connect to MySQL? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result
what is the correct way to connect to MySQL database without the mysql_fetch_assoc() error?
Getting [Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource] with
mysql_connect('localhost', 'name', 'pass'); mysql_select_db('dbname');
getting mysql_fetch_assoc() error without mysql_select_db any suggest?
CODE are:
var somethings= ;
Typo? Your question has msyql_select_db instead of mysql_select_db - note the swap of the s and y in mysql.
Try:
$result= mysql_query('SELECT DISTINCT username FROM users');
$somethings= array();
while ($row= mysql_fetch_assoc($result)) {
$somethings[]= $row['something'];
}
Basically changing $results to $result.
$connect = mysql_connect('host', 'user', 'pass);
mysql_select_db('database', $connect);
That's how you connect to a database.
You also spelled mysql wrong.
Getting Fatal error: Call to undefined function msyql_select_db() with mysql_connect('localhost', 'name', 'pass'); <<msyql>>_select_db('dbname');
Arrows around the error.
you spelled your function incorrectly mysql not msyql
I do not understand your question, but maybe this will help.
$session = mysql_connect('host','username','password');
mysql_select_db('database', $session);
$resultset = mysql_query('SELECT * FROM TABLE', $session);
$result = mysql_fetch_assoc($resultset);
Good luck...
May want to change localhost to '127.0.0.1' as well...I've had issues with that before.
<?php
$result= mysql_query('SELECT DISTINCT username FROM users');
while ($row= mysql_fetch_assoc($results)) {
$somethings[] .= $row['something'];
}
?>
Try this
<?php
DEFINE ('DB_USER', ''); //specify the DB username like root.
DEFINE ('DB_PASSWORD', ''); //specify the DB password.
DEFINE ('DB_HOST', ''); //specify the DB hostname(localhost of IP address).
DEFINE ('DB_NAME', ''); //specify the DB Name on which your doing operations.
$dbc = #mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die ('Could not connect to MySQL: ' .mysqli_connect_error() );
$query="Specify your operation in a query format";
#mysqli_query($dbc,$query);
#mysqli_close($dbc);
?>

Categories