What does 'NO_DSN' option mean in creating DB server connection? - php

In TestLink, I found a NO_DSN option in Database connection in installNewDB.php script. I never heard of NO_DSN and would like to know if someone can explain it to me:
see Lines 163 - 180 (https://github.com/viglesiasce/testlink/blob/master/install/installNewDB.php):
// Connect to DB Server without choosing an specific database
$db = new database($db_type);
define('NO_DSN',FALSE);
#$conn_result = $db->connect(NO_DSN,$db_server, $db_admin_name, $db_admin_pass);
if( $conn_result['status'] == 0 )
{
echo '<span class="notok">Failed!</span><p />Please check
the database login details and try again.';
echo '<br>Database Error Message: ' . $db->error_msg() . "<br>";
close_html_and_exit();
}
else
{
echo "<span class='ok'>OK!</span><p />";
}
$db->close();
$db=null;
What does it mean here?: define('NO_DSN',FALSE);
and here: $db->connect(NO_DSN,$db_server, $db_admin_name, $db_admin_pass);

In this case DSN refers to 'Data source name'.
It can be an optional connection string that you pass to the database to set additional options like db driver, host, db name, charset, port, etc..
An example of a DSN string using PDO would be like this:
mysql:host=localhost;dbname=test;port=3306;charset=utf8mb4
So in your case it looks like the 'NO_DSN' option is defaulting to false unless you specify the connection string.

DNS is a server that translates websites' addresses so that your browser can connect to them. If the addresses become out-of-date or theserver has issues, you'll encounter aDNS error and won't be able to connect to a specific site or group of sites even with Internet access.

Related

Check if connected to MySQL and Database

I'm having a problem with a PHP-Script, where I want to check, if the MySQL-Logindata are valid. I found somewhere the mysql_ping() function, but it doesn't work as it should, because it returns in every case true, even if the inserted data are totally wrong. How do I solve it?
$verbindung = mysql_connect($_POST["mysql_host"], $_POST["mysql_user"],
$_POST["mysql_pwd"]);
if (!mysql_ping($verbindung)) {
$break = true;
}
else {
// Check here also via SQL, if database $_POST["mysql_db"] exists
}
This already is more complex than it needs to be and should do the correct thing. The reason why all usernames work quite likely is that MySQL by default has an anonymous user ''#'localhost' which accepts any username. Probably you want to remove that user. (DROP USER ''#'localhost', be sure you can login as other user before doing that, use SHOW GRANTS to see which user you are using)
For simplification mind that the connect cal will fail if there is something wrong, so you wont need that ping call. ping can be used if you have a longer living connection and you want to check whether the connection is still working.
A simple form for the check might look like this:
$verbindung = new mysqli($_POST["mysql_host"], $_POST["mysql_user"], $_POST["mysql_pwd"]);
if (!$verbindung) {
echo "Wrong settings";
}
Mind that I changed to the mysqli insterface. the old mysql extension in PHP providing the mysql_* functions is deprecated and shouldn't be used anymore.
I actually found out a nicer solution with the mysqli_connect_errno() function and a requirement of inputs from the database name and the user name.
$verbindung = #mysqli_connect((!empty($_POST["mysql_host"]) ? $_POST["mysql_host"] : 'localhost'),
$_POST["mysql_user"], $_POST["mysql_pwd"], $_POST["mysql_db"]);
if (mysqli_connect_errno() || empty($_POST["mysql_user"]) || empty($_POST["mysql_db"])) {
$break = true;
}

Mysql fails in php but works in phpmyadmin

I've made this a lot of times but now I can't :(
The insert allways return false but if I execute the same SQL script (taked from the output) it inserts in the database without any problem. I'm connected to the database because some values are fetched from another table.
This is my code:
$query = "INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx,equipo_compania,paciente,sexo,edad,id_compania,otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('$fecha','$macropera','$pozo','$equipo_pmx','$equipo_compania','$paciente','$sexo',$edad,$id_compania,'$otra_compania','$puesto','$ta','$tum','$ove','$coordinador')";
if (mysql_query($query,$connection)){
//OK
} else {
$errno = mysql_errno();
$error = mysql_error();
mysql_close($connection);
die("<br />$errno - $error<br /><br />$query");
exit;
}
The output is:
0 -
INSERT INTO normotensiones(fecha,macropera,pozo,equipo_pmx, equipo_compania,paciente,sexo,edad,id_compania, otra_compania,puesto,ta,tum,ove,coordinador)
VALUES('20111001','P. ALEMAN 1739','P. ALEMAN 1715','726', 'WDI 838','SERGIO AYALA','M',33,21, '','','110/70','ROBERTO ELIEL CAMARILLO','VICTOR HUGO RAMIREZ','LIC. PABLO GARCES')
Looks like there are no error, but allways execute the code in the else part of the if instruction. Any idea? Thanks in advance.
I think the issue might be you are missing the mysql_select_db line after the connection.
After the connection with the database is established you need to select a DB. Please make sure you have selected the Database that your desired table resides in.
And you can even use the following snippets to get some useful informated through mysql_errors.
$connection = mysql_connect('localhost', 'root', 'password');
if (!$connection) {
die('<br>Could not connect: ' . mysql_error());
}
if (!mysql_select_db('db_name')) {
die('Could not select database: ' . mysql_error());
}
And try you insert query after these lines of code. All the best.
I agree with the others concerning the column types. INT is one of the only data types that do not require single quotes.
There are two blank strings. There is a possibility that the variables are not defined, and therefore giving you a PHP exception (not even in the MySql yet) but that requires stricter-than-normal exception settings. I would personally look into the $connection variable. Before the SQL query statement, put this and send us the cleaned results:
echo '<pre>'.var_dump($connection, true).'</pre>';
Additionally, on your mysql_connect function call, put
OR die('No connection')
afterwords. Do the same thing with the mysql_select_db function, changing it to 'No DB Select' obviously.
Ultimately, we will need more information. But changing to mysqli is very desirable.
Oh! And make sure the permissions for the user you are connecting as are not changed. Sometimes I find people who connect to PhpMyAdmin using one user account but a different account in their PHP code. This is problematic, and will lead to problems eventually, as you forget the different accounts, at times.

PHP MySQL external database connection timed out

I'm getting a connection timed out when I try to connect to an external (not on the same server as this code is on) database through the following code. I know the settings of the database is set up right, and the login info is good, 'cause I can login fine from my computer with HeidiSQL. If anyone can see a problem with this code, thanks.
function database_connect(){
$link = #mysql_connect("xx.xxx.xxx.xx:3306","root","pass");
$sql_error = mysql_error();
if (!$link) {
echo "Connection with the database couldn't be made.<br>";
echo "$sql_error";
exit;
}
if (!#mysql_select_db("databasename")) {
echo "The database couldn't be selected.";
exit;
}
return $link;
}
database_connect();
have you tried adding the IP address of where that script is hosted to "Remote Database Access Hosts"?
If you're on cPanel, you need to allow the IP address who can remotely access the datase(mysql).
If you're not, then this is just an idea of what to do.
Problem known now.
My webhost does not allow connections to an external database.

mysql_connect - Access Denied to DB or DB doesn't exist?

So I connect to my MySQL database using the following code:
function dbConnect($h,$u,$p,$n) {
if (!$con = #mysql_connect($h,$u,$p)) {$err = err("There is a problem connecting to the database. ".mysql_error());}
else if (!#mysql_select_db($n,$con)) {$err = err("The database \"{$n}\" could not be found. Check your spelling, make sure the database exists, and that your database credentials allows you access to this database.");}
return (isset($err)) ? $err : "";
}
The problem is, if they put in a wrong username, mysql_connect will not see anything wrong with it and try to connect to the database, which outputs an error for the mysql_select_db().
So I found this link. Now normally removing the "any" user would be doable but I'm creating a phpMyAdmin-like tool and will be connecting to different databases with all types of configurations. How can I tell which username can actually connect? And how can I differentiate between the database name not existing and the username not having access to it?
use mysql_errno()
see error codes here

The mysqli_connect not working

I installed apache, php and mysql. Now when I execute the php code, the mysqli_connect() is not working, neither it's showing the message in die.
$dbc=mysqli_connect(' ', ' ', ' ', ' ') or die('not connecting');
Now someone tell me what database username shall I pass to mysqli_connect and what password. I don't remember I was asked for any username or password
and why isn't the message in die() showing up?
My var_dump(function_exists('mysqli_connect')); outputs bool(false).. if it has anything to do with it, how do I correct it.?
Looks like MySQLi extension is not installed. What does var_dump(function_exists('mysqli_connect')); output?
Do you have error_reporting(E_ALL); And ini_set('display_errors',1); ?
The problem could be somewhere else.
Also how do you know it's failing if it is not priting the message in Die()?
for the host, if you are using "localhost:8889",
try using "localhost", and in the mysqli_connect() put in '8889' (or whatever port you are using) as an argument after the other arguements.
worked for me.
eg:
mysqli_connect('localhost','root','root','dbname','8889');
If you pass no values, I think MySQL is using defaults from the settings ini. So maybe this happens too if you pass empty values. In that case the connection could actually be established, and the result won't 'die'. Best thing is to use var_dump to check what $dbc contains after the call and continue from there.
But anyway, there is no way, PHP is going to tell you which settings to use if you don't remember them. :)
If you just installed mysql, then there exists only the root user, without a password (or blank one if you prefer). You are strongly encouraged to change that password AND create a new user and password for your application, who has only access to just one database, the one your application uses.
To change the root password, you may do this:
$ mysql -u root -p
Enter password: [press enter]
mysql> use mysql;
mysql> UPDATE user SET `password`=PASSWORD('your_desired_password') WHERE username='root';
# this next bit is to create a database and a username for your web application
mysql> CREATE DATABASE your_application_name;
mysql> GRANT ALL ON your_application_name.* TO 'your_username'#'localhost' IDENTIFIED BY 'yourpassword';
Obviously change all your_* values with correct ones.
For the reason why the die() gets not executed, do what #yes123 and #binaryLV had said (I think both are right, the mysqli is not installed, so it throws a E_FATAL_ERROR upon calling mysqli_connect(...) and as error_reporting is disabled (or maybe display_errors, or maybe both), you don't see that error.
//1 create a data base connection
$con = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if (!$con) {
die('mysqli connection failed: ' . mysql_error() );
}
//2 connect with a data base
$db_select = mysqli_select_db($con , DB_NAME);
if (!$db_select) {
die('data base selection failed: ' . mysql_error() );
}
//3 create query
$result = mysqli_query($con, "select * from subjects");
if (!$result) {
die('query not successed: ' . mysql_error() );
}
//4 use the returned data
while ($row = mysqli_fetch_array($result)) {
echo $row['menu_name'] . " " . $row['position'] . "<br>" ;
}
//5 close connection...
if (isset($con)) {
mysqli_close($con);
}
Run this code if you have any query then feel free to ask me.
First check your php version
echo 'Current PHP version: ' . phpversion();exit;
if it is above 5.5 and even not working
then write script in your php file phpinfo(INFO_MODULES);exit;
it show all about php and check Mysqli listed or not. if not then inform to our server admministrator or if you have access then go to phpini file and enable mysqli (remove semicolon from it)
Try this:
$dbc = # mysql_connect('localhost', 'root', '') or exit('Not connecting.');

Categories