Connect to MySQL table using PHP (XAMPP) - php

I am trying to make a CRUD in PHP. Apache and MySQL is still running.
class DB
{
static private $connection;
const DB_TYPE = "mysql";
const DB_HOST = "localhost";
const DB_NAME = "crud";
const USER_NAME = "root";
const USER_PASSWORD = "";
static public function getConnection()
{
if (static::$connection == null) {
try {
static::$connection = new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);
} catch (Exception $exception) {
throw new Exception("connection failed");
}
}
return static::$connection;
}
}
I am running on localhost:3306
phpMyAdmin is up and running
The output is in the picture
output:

Your PDO invocation looks weird.
static::$connection = new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);
The construct for this is new PDO($dsn, $user, $password);
The dsn has this format:
mysql:dbname=testdb;host=127.0.0.1;port=3333 then , user then , password
Your dsn section seems wrong, it should be more like this:
$dsn = 'mysql:dbname='. self::DB_NAME .';host=' . self::DB_HOST ;
$user = self::USER_NAME;
$password = self::USER_PASSWORD;
$dbh = new PDO($dsn, $user, $password);

I think you forgot spaces and signs in your connection arguments
That is your syntax :
new PDO(self::DB_TYPE . "host" . self::DB_HOST . "dbname" . self::DB_NAME . self::USER_NAME . self::USER_PASSWORD);
Which give :
"mysqlhostlocalhostdbnamecrudroot"
This is the syntax from the doc :
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

Related

error 1045: access denied for user 'root'#'localhost' using password NO... when connecting through extended classes,others

I have a class that was connecting to the database without issue. Upon extending that class the same connection fails. The credentials work in phpMyAdmin and command line.
The error I get when attempting to connect to the server:
1045: Access denied for user 'phpClasses'#'Jesse-Server' (using password: NO)
I have also tried alternate credentials with the same result.
The following is the constructor and property definitions of the parent class and then the child class, then the caller model:
//Database.php
private $dbhost;
private $dbname;
private $dbusername;
private $dbuserpassword;
private $dbtableprefix;
private $dbport;
protected $dbC;
public function __construct($ndbhost = "localhost", $ndbname = "", $ndbusername = "", $ndbuserpassword = "", $ndbtableprefix = " ", $ndbport = 3600)
{
$this->dbhost = $ndbhost; // Default = localhost
$this->dbname = $ndbname; // Default = None
$this->dbusername = $ndbusername; //Default = None
$this->dbuserpassword = $ndbuserpassword; // Default = None
$this->dbtableprefix = $ndbtableprefix; //Default = None sets the prefix before the table name so that it can be used with the same db with different tables.
$this->dbport = $ndbport; // Default = 3600
// starting the connection
# $this->dbC = new mysqli($this->dbhost, $this->dbusername, $this->dbuserpassword, $this->dbname);//, $this->dbport);
if ($this->dbC->connect_error) {
//catch error connecting.
die("There was a connection error while attempting to connect to the database " . $this->dbname . " on " . $this->dbhost . ":" . $this->dbport . ". The following is the error that we received back: <strong>" . $this->dbC->connect_errno . ": " . $this->dbC->connect_error . "</strong>\n Please correct this issue, if you need assistance see your database or IT administrator.");
}else{
//echo "Connected to " . $this->dbname . " on " . $this->dbhost . ":" . $this->dbport;
}
}
Now the child
//QueryBuilder.php
protected $dbC;
private $host;
private $dbName;
private $dbUser;
private $dbPassword;
private $tablePrefix;
private $dbport;
function __construct($ndbhost = "localhost", $ndbname = "", $ndbusername = "", $ndbuserpassword = "", $ndbtableprefix = " ", $ndbport = 3600){
//default Constructor
$this->host = $ndbhost;
$this->dbName = $ndbname;
$this->dbUser = $ndbusername;
$this->dbPassword = $ndbuserpassword;
$this->tablePrefix = $ndbtableprefix;
$this->dbport = $ndbport;
echo $this->host . ',';
echo $this->dbName . ',';
echo $this->dbUser . ',';
echo $this->dbPassword . ',';
echo $this->tablePrefix . ',';
echo $this->dbport;
parent::__construct($this->host, $this->dbName, $this->dbUser, $this->dbpassword, $this->tableprefix, $this->dbport);
$this->dbC = parent::getdbconnection();
}
The model
//model.php
require("./Class/Database.php");
require("./Class/QueryBuilder.php");
$result=false;
$host = '192.168.1.2'; //or localhost , same thing, also tried 127.0.0.1
$database = 'phpclasses';
$dbuser = 'phpClasses';
$dbuserpw = 'test1234';
//now I want to see that the connection has been made.
//$db = new DatabaseClass($host, $database, $dbuser, $dbuserpw);
$qb = new QueryBuilderClass($host, $database, $dbuser, $dbuserpw);
I thank you all for your time and your help;
Jesse Fender
In the child. You've got mixed case typos for $this->dbpassword vs $this->dbPassword. Same with $tablePrefix vs $tableprefix

Pending PDO connection - medoo php

When I change the IP of my MySQL connection and run this:
$this->pdo = new PDO($dsn, $this->username, $this->password, $this->option);
The try and catch does not work. Its does not catch that error, PDOException or general exception.
The problem is that I did not get any error or a response from PDO. It is pending for a long time.
How can I get the response immediately if there are no connections?
Full code:
case 'mysql':
if ($this->socket) {
$dsn = $type . ':unix_socket=' . $this->socket . ';dbname=' . $this->database_name;
} else {
$dsn = $type . ':host=' . $this->server . ($is_port ? ';port=' . $port : '') . ';dbname=' . $this->database_name;
}
$commands[] = 'SET SQL_MODE=ANSI_QUOTES';
if (in_array($type, explode(' ', 'mariadb mysql pgsql sybase mssql')) && $this->charset) {
$commands[] = "SET NAMES '" . $this->charset . "'";
}
//**here is the problem //
$this->pdo = new PDO($dsn, $this->username, $this->password, $this->option);
foreach ($commands as $value) {
$this->pdo->exec($value);
}
} catch (PDOException $e) {
echo "Connection to database lost";
}
catch (Exception $e) {
echo "Connection to database lost";
return;
}
even if I try from php manual
$dsn = 'mysql:host=127.0.0.2;port=3306;dbname=dbname';
$username = 'user';
$password = 'pass';
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
$dbh = new PDO($dsn, $username, $password, $options);

Getting error as " SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected "

I am trying to select records from database using php PDO, but getting error as "SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected".
I found some similar available solutions, but unfortunately these are not resolved my problem.
Here is my code
class Database {
private $servername = "127.0.0.1";
private $username = "root";
private $password = "";
private $dbname = 'demo';
protected static $con = null;
function __construct() {
try {
self::$con = new PDO( "mysql:host = $this->servername;dbname = $this->dbname", $this->username, $this->password );
self::$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = self::$con->prepare("select * from test");
$stmt->execute();
while($row = $stmt->fetch()){
print_r($row);
}
} catch( PDOException $e ) {
echo "Connection failed: " . $e->getMessage();
die;
}
}
}
when I am executing the above code I am getting the mentioned error.
Can anyone please let me know, what exactly i missed out here?
In your connection string do this:
self::$con = new PDO( "mysql:host={$this->servername};dbname={$this->dbname}", $this->username, $this->password );
It will help php to parse your variables correctly.
Or use concatenation:
self::$con = new PDO( "mysql:host=" . $this->servername . ";dbname=" . $this->dbname, $this->username, $this->password );
And as shown in the manual - I removed all spaces in dsn.

PHP $_POST encoding

i've got an problem.
I try to connect to my MySQL-Database with this password:
Test12&#_#+.:-;}][{$%!/()?,*'"`<>
public function __construct() {
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['dbName'])) {
$this->dbName = $_POST['dbName'];
}
if (isset($_POST['dbUser'])) {
$this->dbUser = $_POST['dbUser'];
}
if (isset($_POST['dbPass'])) {
$this->dbPass = $_POST['dbPass'];
}
}
}
public function connectToDatabase() {
try {
$dsn = 'mysql:dbname=' . $this->dbName . ';host=' . $this->dbHost . ';charset=utf8';
$options = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);
$dbh = new PDO($dsn, $this->dbUser, $this->dbPass, $options);
$this->isConnected = TRUE;
} catch (PDOException $e) {
echo $e->getMessage();
$this->isConnected = FALSE;
}
}
i always get the message:
SQLSTATE[HY000] [1045] Access denied for user 'web3_10'#'localhost' (using password: YES)
I think it's because of my overkill password.
How can i get this to work?
Next i have to import a Dump with this:
public function importDatabase($dbTarget) {
$stmt = 'mysql --host=' . $this->dbHost . ' --user=' . $this->dbUser . ' --password=' . $this->dbPass . ' ' . $this->dbName . ' ' . '<' . ' ' . $dbTarget;
var_dump($stmt);
exec($stmt, $output, $return);
if (!$return) {
$this->dbImported = TRUE;
}
}
same problem here. no import with this password.
How ca i fix this?
There could be a couple of problems here, so make sure:
You escaped your password string correctly (specifically characters like ' -> \')
Its actually the correct password (log in via console and see if it works)
Your user actually has the correct permissions for the tables.
Further, try to print your password string before connecting, and verify it is indeed correct.

PDO and classses getting the 'PDOException' error

I am getting an error: Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [2002] Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.sock' (2)' in /home/content/........
Althought if I do it in one file, it works fine!
My php file:
<?php
require 'includes/dbc.php';
$dbc = new dbc();
$db = $dbc->openDb();
$stmt = $dbc->getAllUsers($db);
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['iduser'];
}
?>
my database class:
<?php
class dbc {
public $dbserver = '';
public $dbusername = '';
public $dbpassword = '';
public $dbname = '';
function openDb() {
$db = new PDO('mysql:host=' . $dbserver . ';dbname=' . $dbname . ';charset=utf8', '' . $dbusername . '', '' . $dbpassword . '');
return $db;
}
function getAllUsers($db) {
$stmt = $db->query("SELECT * FROM user");
return $stmt;
}
}
?>
In the sample-code you provided, you're not specifying a database, user, password or host to the database connection string:
function openDb() {
$db = new PDO('mysql:host=' . $dbserver . ';dbname=' . $dbname . ';charset=utf8', '' . $dbusername . '', '' . $dbpassword . '');
return $db;
}
With invalid data, your code cannot connect and therefore you're receiving the connection-error.
As they're global to the dbc class, you'll need to use $this when accessing them (such as $this->dbserver). Try updating your code to:
function openDb() {
$db = new PDO('mysql:host=' . $this->dbserver . ';dbname=' . $this->dbname . ';charset=utf8', '' . $this->dbusername . '', '' . $this->dbpassword . '');
return $db;
}
* Also, though you may have removed it to post the question, you don't have any of those variables set to actual values either.
You forgot to define the database settings? I always use the following to connect using the PDO class.
/** Define database propperties **/
define('DB_HOST', 'localhost', true);
define('DB_USER', 'user_db', true);
define('DB_PASS', 'yoursuperpass', true);
define('DB_DATA', 'data_www', true);
$dbInstance = new PDO('mysql:dbname='.DB_DATA.';host='.DB_HOST, DB_USER, DB_PASS);
$dbInstance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbInstance->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

Categories