error in PDO connection - php

Hye, kindly need your help to assist me finding the error of this connection. The reason is that i didn't get submitting the data in a form to the database.
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=;charset=utf8', 'root', '');
}
catch(Exception $e)
{
die('Erreur : '.$e->getMessage());
}

You are missing the database name.
dbname=You Forgot The Name Here;
P.S. if you don't want to include the database, you should leave the entire part.

Related

Where does my PHP code make connection to the database?

So I am very new to MongoDB and PHP and I am trying to make a connection to the database and perform an insert query on it. I have managed to make it work, but know I do not really understand my own code.
My code:
<?php
// PHP version 7.4 used here
try {
require 'mongophp/vendor/autoload.php';
//$mongo = new MongoDB\Driver\Manager('mongodb://localhost:27017');
echo "Connection to database successfully\n";
$collection = (new MongoDB\Client)->shinto->users;
$insertOneResult = $collection->insertOne([
"name" => "testuser",
"password" => "1234",
]);
printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
var_dump($insertOneResult->getInsertedId());
echo "so far so good";
}
catch (Throwable $e) {
// catch throwables when the connection is not a success
echo "Captured Throwable for connection : " . $e->getMessage() . PHP_EOL;
print("\ndoes not work\n");
}
?>
The thing that I do not understand is how the code knows where my database is since I do not have to use the connection string.
My guess is that the mongophp/vendor/autoload.php takes care of this part, but I have looked through those files and can't seem to find the answer to my question in there as well.
Can someone help me understand how my code knows where my database is without a connection string or provide me with a link that will explain this to me?
Thank you very much in advance!

how to connect to remote database in php pdo

This is view of my phpmyadmin web server
I need to connect to my university webserver on PHPmyadmin which is "phpmyadmin.newnumyspace.co.uk"
what changes are required to achieve this. I mean i know localhost would be changed and port and something needs to be put here but help me out as i don't understand the syntax
<?php
$db_host="localhost";
$db_user="root";
$db_password="";
$db_name="nbl";
try{
$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
$e->getMessage();
}
?>
Your sql DB is local to the web host as they are both run on a linux XAMPP server. Obviously include the correct username and password.
function getConnection() {
try {
/* connects to the SQL DB */
$connection = new
PDO("mysql:host=localhost;dbname=unn_w19038752",
"unn_w19038752", "Password");
$connection->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
return $connection;
} catch (Exception $e) {
/* displays an error if unable to connect */
throw new Exception("Connection error ". $e->getMessage(), 0, $e);
}
}
Then you can just call this function everytime you need to make a connection
($dbConn = getConnection();)
Although for a clearer answer you're better speaking to your KF4009 Module tutor for assistance (That's what you're paying Uni fees for :-) )
Regards, former NU Student :-)
P.S. nbl is a table not a db, and you don't have root access(username), check your email from newnumyspace for your correct server login details.

PHP Try Catch in Exception Handling

I have a database class dbconnect.php, and processform.php. Inside dbconnect.php there is a method for connecting to the database.
If there's an error, how do I throw an exception? Where do I put the try catch block, in the processform.php? People say I shouldn't echo an error directly from inside the class. Here's an example:
<?php
// dbconnect.php
class DbConnect
{
public function open_connection()
{
/* Should I do it like this? */
$this->conn = PDO($dsn, $this->username, $this->password);
if (!$this->conn) {
throw new Exception('Error connecting to the database.');
}
/* Or like this */
try {
$this->conn = PDO($dsn, $this->username, $this->password);
} catch (PDOException $e) {
echo 'Error: ', $e->getMessage(), '<br>';
}
}
?>
// processform.php
<?php
require_once 'dbconnect.php';
$pdo = new DbConnect($host, $username, $password);
try {
$pdo->open_connection();
} catch (PDOException $e) {
echo 'Error connecting to the database.');
}
?>
I really want to learn the correct way of implementing the try catch in my code.
You don't have to throw an exception manually, especially on a successful connect :-)
Instead you need to tell PDO that it needs to throw exceptions when something goes wrong and you can do that when you open your database connection:
$options = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$this->conn = new PDO($dsn, $this->username, $this->password, $options);
Now you can put everything in try / catch blocks but that is not even necessary; if you don't do that, php will show you unhandled exceptions complete with a stack trace when you don't catch them manually.
And when you decide you want to fine-tune your error handling for your visitors, you can set your own exception handler using set_exception_handler(). That way you can handle everything at one place instead of wrapping different sections in try / catch blocks. Should you prefer that of course.
In my practice, I prefer to catch exception in bottom. I mean, second way in your DbConnect.
You can output error message to error log. And return an error code to front-end. So the front-end knows how to tell users an error occours in a friendly way.
What's more, you can use global error handler such as set_error_handler/set_exception_handler to do this. Redirect to an error page when error occours.

How do I handle error message in my case

I am trying to catch an error with php when I connect to DB
I have something like
try{
//connect to DB
}catch(exception $e){
echo $e
}
//other php codes...
//My html elements...
<div>....
My problem is that I want to skip //other phpo codes if we have error connecting to DB and straight to show my html elements. Is that possible to do it? Thanks a lot.
Just out that code in your try/catch. Once the exception is thrown execution is handed off to the catch portion of the control structure and that portion of code is never reached:
try{
//connect to DB
// If an exception is throw above we never get here
//other php codes...
}catch(exception $e){
echo $e
}
//My html elements...
<div>....
If you don't want to move the // other php code
And you don't want/can't edit the try/catch block, surely the try/catch returns some variable you can test, even if only that $e.
try {
// something like $connected_db should be available
}
catch (exception $e)
{
}
if (!empty($connected_db) AND empty($e)) // one or the other depending on the code above
{
// other php code
}
// my html elements

Error with transfering MySQL database (connected via PDO) from localhost to hosted server

Okay, so this is my code:
try {
$pdo = new PDO ('mysql:host=127.0.0.1;dbname=db_name','user','password');
} catch (PDOException $e) {
exit ('Database error.');
}
I tried so many different combinations with host name, username and password, and every time I get 'Database error'.
My question is:
What should I do to succesfully transfer MySQL database from localhost to my hosted server using this part of code (which is my connection.php file)?
Thank you, in advance.
Get rid of this try catch stuff. Leave it as
$pdo = new PDO ('mysql:host=127.0.0.1;dbname=db_name','user','password');
And see what it says (on-screen or logs)
Use this try and catch block for error trace
try {
$this->conn = new PDO('mysql:host=127.0.0.1;dbname=db_name','user','password');
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}

Categories