I'm working on a website that has a data base (phpmyadmin) with several articles, what i want to do now is to put all off that on a remote server. I never did this with a website that has mysql, i tried this now and it seens it can't connect with the database ('Database error.'). So i have this code to do the connection:
<?php
try {
$pdo = new PDO ('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
}
catch (PDOException $e) {
exit('Database error.');
}
?>
It all works at 100% on localhost so i guess what it's missing is just the connection. Do I have to do something on this piece of code? if yes, What is it? and do I have to do anything else? plz explain like i'm a child. Thanks very much
Related
I need some guidance on PDO error handling.
I got this code:
<?php
$config = include('config.php');
try{
$handler = new PDO('mysql:host-127.0.0.1;dbname=not_a_valid_dbname', $config->username, $config->password);
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo 'Yup!';
}catch(PDOException $e){
echo 'Caught! '.$e->getMessage();
}
As you can see I provided an unvalid db name. This page outputs 'Yup!' instead of letting me know that there is no such database. Same goes when changing 'mysql:not_valid_host'. Only when I change driver name it throws an error letting me know that there is no driver by that name.
I tried:
Checking php.ini for settigs (I have hard time getting around with this)
Adding
error_reporting(E_ALL);
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
Adding
ini_set('display_errors',true);
Also tried adding a backslash in catch param:
catch(\PDOException $e)
Still the same result. Help me break my code :D
The documentation is very unclear, but I've made some tests and drawn some conclusions. This is pure speculation. I'll try to back some of these claims up if I find further information.
If host is not present, localhost is then assumed.
Database name is not mandatory. This is, I imagine, so you can connect to a server and create a new database through PDO.
If you have a syntax error, the string will stop being considered thereafter.
With those suppositions, we can assume why your code is working the way it is. Your DSN is:
mysql:host-127.0.0.1;dbname=not_a_valid_dbname
Since there's a syntax error (- after host), neither of the parameters are considered, and there's no DB selected, with the host being localhost. This is why you get no errors. If you delete the host parameter, however:
mysql:dbname=not_a_valid_dbname
localhost is used as host (selected by default), but not_a_valid_dbname is tried as the database, which results in
Caught! SQLSTATE[HY000] [1049] Unknown database '1234'
mysql:not_valid_host would be the same case as the first example. The DSN is invalid so localhost is assumed with no database selected.
Further, you get no error because no actual DB is selected but you didn't try to run a query. As soon as you do,
try {
$handler = new PDO('mysql:', "root", "root");
$handler->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$handler->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$handler->query("SELECT * FROM test");
echo 'Yup!';
} catch(PDOException $e) {
echo 'Caught! '.$e->getMessage();
}
You'll get an PDOException, as expected:
Caught! SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
Like I said, all of this is speculation as I couldn't really find concrete evidence on most of this. I hope this guides you in the right direction. I'll keep looking for more information and edit if I find anything.
I'm on it since 2 days and can't figure it out this case.
I'm working with PHP 5.5 ans MSSQL, and it seems I can't insert in some table whereas an update works on this table and the same insert works on another table.
Of course I've check my user have the correct rights on this table.
Here's the code maybe I'm dumb...
// Establish connection
try {
$pdo = new PDO(DSN, UID, PWD);
} catch (PDOException $e) {
die("Error! ".$e->getMessage());
}
$pdo->beginTransaction();
// Merge-like event
try {
$updateStmt->execute();
$rows = $updateStmt->rowCount();
if($rows == 0) {
$insertStmt->execute();
}
} catch (Exception $e) {
$pdo->rollBack();
die("Error! ".$e->getMessage());
} finally {
$insertHistoryStmt->execute();
$pdo->commit();
}
All my PDO Statements objects are corrects with suitable values.
I've got no error on the INSERT seems it seems to never been executed on the DB.
Please ask if you need more code to understand I don't want to put my whole code here and say "please do my work".
Thanks I'm really stuck :/
Maybe my question's title isn't suitable now that I found the error source. But I write this answer down because it's a great tutorial which explains to debug different errors from ourselves.
If you go throw any PDO errors follow this link and you will find the way.
Thank to #Your Common Sense for providing a method to learn solving errors rather than a ready to use solution.
I have a website that has forms, images, text, etc. I want extract data from the forms and keep a record of them in mySQL. In order to do this do I need to change the file extension from '.html' to '.php'? And if so then will this effect any inline css?
Also, when I need to connect to the server via the php, how to I know the database username, database password, and the database host?
I have go daddy as the web host, and use the CPanel they provide to access the phpmyadmin
Thanks - any help is highly appreciated!
This is the PHP code I have so far, and I keep getting error alerts when I run the test through XAMPP:
mysql_connect() is already deprecated please consider using mysqli or PDO.
PDO . database connection example :-
You should create a separate class containing the functions for basic operation in database and keep that file separate from your other code , just inherit the class and use the connection and function .
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
foreach($dbh->query('SELECT * from FOO') as $row) {
print_r($row);
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
As the other answer stated, use pdo or mysqli instead of 'mysql`.
A good way to use PDO is to put the connection code within a file, and include this file anywhere you need to make use of the database.
Let's call this file dbconnector.php.
try
{
$conn = new PDO($connectionString, 'root', '');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
Now, wherever you want to use database, just use :-
include 'dbconnector.php'
Now, you can access the connection variable via $conn.
Read more on PDO.
http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
I'm having an issue yesterday and today with my host (godaddy) who apparently is having trouble with a particular mysql server... in that it's completely out of commission for a few hours at a time.
Right now this causes my site to not load at all - showing this error:
[phpBB Debug] PHP Warning: in file /home/content/index.php on line 53: mysqli::mysqli() [mysqli.mysqli]: (HY000/2003): Can't connect to MySQL server on 'dbserver.com' (110)
Connect failed: Can't connect to MySQL server on 'dbserver.com' (110)
I'm guessing it's showing that because of this code I have:
// PREPARE DB CONNECTION
$mysqli = new mysqli("dbserver.com", "username", "password", "dbname");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
Which tells the php to stop altogether if mysql is down. So I suppose all I need to do is remove the "exit" function and I'm good to go?
I guess theoretically speaking, why is exit there by default in so many tutorials of how to connect to mysql? It kills the web site if the database is unavailable.
Just looking for thoughts from those who know much more than I please, thank you!
Just bin this:
printf("Connect failed: %s\n", mysqli_connect_error());
And replace it with a placeholder page instead to inform people that s**t happened and you'll be back later.
header('Location: error_db.php');
Displaying good and pretty error-messages to the user is often neglected by most programmers. This is because it can be a real pain in the ass to do the right way.
As Jassica commented, if your entire site function without the database-connection, you can just remove the exit() in your function and the site is good to go.
However, I guess the chances for a 100 % functional site without the database-connection are very small. What most sites to is to redirect the user to a 500-errorpage where they inform the user that something went wrong. Often provided contact-information so the right people can be notified too. Twitter does this, so does Facebook, Reddit and many more.
You can just do:
$mysqli = new mysqli("dbserver.com", "username", "password", "table");
if (mysqli_connect_errno()) {
header("Location: error500.html");
exit();
}
Or something like that.
This should do the trick.
function connect($u,$p,$db,$host) {
try {
$mysqli = new mysqli($host,$u,$p,$db);
$connected = true;
} catch (mysqli_sql_exception $e) {
throw $e;
}
}
try {
connect('username','password','database','host');
} catch (Exception $e) {
echo $e->errorMessage();
}
I am facing database connection problem while trying to connect a .php file through wamp server
the error message is something like- "Access denied for the user " # ' localhost' " for database 'aschool'. 'aschool' is my database name.
Mentioning that I've changed my port number of wamp server, I am worried that is it really
for changing port number or anything else.Here is my code.
$con = mysql_connect();
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("aschool", $con);
After this line the error message comes. I've tried parameters "localhost" inside the mysql_connect()
function or more parameters but the result is same.
Thanks in advance anyone gives me any solution
That's because you are using mysql_connectwrong for your use case.
If you check the documentation page it says that you can also a server-path,
something like mysql_connect('localhost:1234', 'username', 'password').
But you shouldn't use mysql_connect.
Use PDO so that you can use parameterized queries.
In code it would go like this:
try
{
$pdo = new \PDO('mysql:dbname=aschool;host=127.0.0.1', 'myUser', 'myPassword');
} catch (PDOException $exception)
{
// Do something with your exception.
// Echo it, dump it, log it, die it.
// Just don't ignore the exceptions!
}