mysql_real_escape_string not showing error - php

I am moving my application from Mysql extension to PHP PDO.
I am facing a strange problem.
In my development environment, I have both db server [MySQL] and web server are in single system where as in testing environment web and db servers are in different system.
The following test code runs perfectly in dev environment and fails in test environment.
require "class.DB.php" ;
class DbMaster extends DB
{
public function __construct()
{
$this->Host = "192.168.1.00";
$this->Database = 'test_database';
$this->User = "root";
$this->Password = "12345";
}
}
// Creates the instance
$db = new DbMaster();
$table = mysql_real_escape_string('persons');
$result_array = $db->query("SELECT Id, Age FROM $table WHERE Id >= :Id", array("Id" => 1));
foreach ($result_array as $rec)
{
echo '<br>'.$rec["Id"].' -> '.$rec['Age'];
}
In dev, mysql_real_escape_string should fail, because there is no mysql_connect().
But, mysql_real_escape_string works when there is a mysql server running locally. To test this in dev environment I stopped the local mysql and connected to remote database. Then I got the following error:
Warning: mysql_real_escape_string(): A link to the server could not be established
So with my existing development setup [both web and db server together], I am not able to see the PDO related errors.
Any way to resolve this problem.

mysql_real_escape_string() tries to open a connection to a server with mysql_connect() if no connection exist. The default values for mysql_connect() are "localhost" and "root" without a password.
If you have the root account without a password in your development environment (which is a pretty common setup) this will work without problem, since a connection can be esteblished.
On the live environment on the other hand, the root user hopefully has a password set, so this call will fail.
In this case mysql_real_escape_string() will return false instead of your escaped value.
The solution: Use the mysqli or PDO equivalent of the function. Or open an additional connection using mysql_connect() with valid credentials for the time being so mysql_real_escape_string() can use it.

Related

Constructor failed on creating a new PDO connection

I'm trying to access a remote MySQL server. I created a user in the remote server and granted all the remote privileges to all hosts.
This is my code for connecting to database:
<?php
try{
$dsn = "mysql:host=MY_REMOTE_SERVER_IP;dbname=DB_NAME;port=3306";
$db = new PDO($dsn, 'USER_NAME','PASSWORD');
}catch(Exception $e){
echo $e->getMessage();
}
The code is working fine on my localhost. I even tried the code on some Playgrounds and it's working fine. But on my website, it's not working. The website does not connect to the database and always returns Constructor failed error.
The PHP version is 7.4 on my website and it supports PDO. But I don't know why it does not make the connection?
This is a picture of the error:
Just guessing: you maybe should not use the remote ip address, but localhost or 127.0.0.1 for your database host.
According to the pdo source code, this error message means the connection failed, which is not really helpful, but could mean one of these things (but not limited to):
hostname is wrong
database name is wrong
credentials are wrong
some networking issue
you name it :)
My prime suspect is the hostname, but just make sure all parameters are correct.

Setting up a PHP and SQL Website

so I've recently finished a course on web development, and completed a final project that functioned on my personal Apache Web Server and MySQL Database (MariaDB) through XAMPP. I should note that the site works perfectly as expected on the Apache. I'm interested in having this site hosted so that others can access it as well. (I've never had any sites hosted before, even static ones, and I'd like to do this to experiment). I've tried searching the web for hosting sites with PHP connected to SQL databases and could not find a solution. What I'd like to do is set up a site where the PHP is able to communicate with the SQL db and update realtime so that all visitors can see the changes.
From what I've gathered, I believe that I'll have to host the SQL db from a site that hosts them and separately have another site host my php site. I'm assuming that in my Database Adaptor function, I'll have to change the value of "host" in $db to connect to the SQL db being hosted rather than direct it "home". Is this correct? or am I going about this completely wrong?
This is the database adaptor function I used:
class DatabaseAdaptor {
private $DB;
public function __construct() {
$db = 'mysql:dbname=planner;host=127.0.0.1;charset=utf8';
$user = 'root';
$password = '';
try {
$this->DB = new PDO ( $db, $user, $password );
$this->DB->setAttribute ( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo ('Error establishing Connection');
exit ();
}
}
If I'm going about this completely wrong, could you please lead me in the right direction. I've read a little about WordPress and it seems like they have some compatibility with php and databases, are they what I'm looking for?
In addition, what sites would you recommend for hosting php sites or sql databases?
You are right, you have to change this:
$db = 'mysql:dbname=planner;host=127.0.0.1;charset=utf8';
$user = 'root';
$password = '';
to the one given by your hosting company. There are various hosting companies that provide PHP and MySql hosting.
When you subscribe to a Hosting Provider, they usually have a knowledge base or guidelines on how you would setup your website through the Control Panel. From there, you will be able to setup database(s), (S)FTP to upload your PHP files to your (public) directory, and even setup email(s). There are a lot of (PHP) hosting providers it's up to you which to choose. Here are a few:
DreamHost
SiteGround
HostGator
Linode
GoDaddy
Or you might want to try a free (sandbox) from Heroku?
Happy hunting!

Fatal error: Call to undefined function pg_connect() in C:\wamp\www\php\function.php on line 18

can anyone help me in step by step thank you so much.
function wampserver (){
$host = "localhost";
$port = "5432";
$name = "IMSDB";
$user = "postgres";
$pass = "magahin";
$pg = pg_connect("host=$host port=$port dbname=$name user=$user password=$pass")
or die("Can't connect to database.");
}
You do not have the Postgres extension installed in your PHP setup. Refer to your platforms documentation on how to install it.
you should include file with class pg_connect in order get access to the function and connect your Db
Consider the first rule in the pg_hba.conf:
local all all peer
It means that for all local connections, the Unix user should be the same as the db user. Obviously this is not the case for you php code, hence the failure Peer authentication failed for user....
The second rule would let your script connect, but it's ignored because the first rule takes precedence:
local all all trust
This rule means that all local connections are allowed without requiring password and without checking any identity.
If that's OK with you, just delete the first rule, and reload the postgresql service for the change to take effect.
The other rules should not be relevant to the problem since they're related to TCP connections, and according to the error message, that's not that the method used by your script, it's trying to connect through the default Unix domain socket.

How can I access PDO in MAMP?

I'm setting up a PDO connection in a test script:
use app\SomeDAO;
class SomeTest extends \PHPUnit_Framework_TestCase
{
protected $db;
public function setUp()
{
$dsn = "mysql:host=localhost;dbname=baseball;user=root;password=root";
$this->db = new PDO($dsn);
}
I'm getting an error:
PDOException: SQLSTATE[HY000] [2002] No such file or directory.
How can I use PDO here?
In Unix based (like linux, bsd, or OS X) systems, with MySQL localhost is secret code for try-to-use-a-socket, unless a you force it via a protocol flag to not do this (and no one ever does this). Just remember localhost usually equals socket file.
If Mysql in your MAMP is running in non-socket mode, you can try replacing the host value with 127.0.0.1 which connects via TCP on via port to the local machine--you'll need to figure out which port it's running on if it's not the default port.
If you look at the MAMP start script
less /Applications/MAMP/bin/startMysql.sh
You can see if it's starting in socket mode, and what file it's using if it has a config param like:
--socket=/Applications/MAMP/tmp/mysql/mysql.sock
You can also investigate what open socket mysql might be using by following the answer in this question: error: 'Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)'
If you're running in socket mode, you need to make sure PDO knows the path to the socket file. One way to do this is specify the unix_socket instead of host in the dsn:
$dsn = "mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;dbname=baseball;user=root;password=root";
I had problem like that at MAMP. My decided it, when I connected with PDO I used next line code:
$this->pdo = new \PDO("mysql:unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock;port=8889;dbname=mydatabase;charset=utf8", 'root', 'root');

Trouble with PHP $connection command and MySQL

Probably just because I'm not experienced with this sort of thing, but I downloaded MySQL with Apache running, and I'm working with the following code in a PHP file:
public static $connection = NULL;
private static $host = MYSQL_HOST;
private static $username = MYSQL_USER;
private static $passwd = MYSQL_PASS;
private static $db = MYSQL_DBNAME;
public static function init() {
if(!self::$connection) {
self::$connection = new mysqli(self::$host, self::$username, self::$passwd, self::$db);
}
}
It comes up with this when I open it in Firefox:
trying to connect via unix:///var/mysql/mysql.sock (says this doesn't exist—which, it doesn't)
I replaced MYSQL_HOST with 'localhost', MYSQL_USER with both 'mysql' and 'root' (stupid, yes), MYSQL_PASS with both my system password and NULL, and MYSQL_DBNAME with a few more things (I am having trouble finding out what my database name is called, even with MySQLWorkbench...I started learning this entire field of computing two days ago). It does say that a MySQL server is running on my machine, just not sure how to put the legos together here. Most of the settings are default (port 3306 and such). A test database migration over MySQLWorkBench failed (something to do with not reading the number of rows correctly), but otherwise it was fine and dandy, from what I saw.
Any help would be very welcome!
When you specify localhost as the host name, your computer will try to access the MySQL server using sockets in /var/mysql/mysql.sock. Since that file does not exist, this won't work. However, when you specify 127.0.0.1 as host name, the MySQL connection is set up over TCP/IP.
See also this question.
So the answer is to either find where MYSQL_HOST is defined and change it to be 127.0.0.1, or forget about MYSQL_HOST and just enter 127.0.0.1 instead. The latter is harder to maintain in case you would want to move your site to some other location (server).
Try restarting SQL server. This may recreate the missing .sock file. See here for info on restarting: http://theos.in/desktop-linux/tip-that-matters/how-do-i-restart-mysql-server/

Categories