For some reason, this code always returns “Connected to Database” even when I try to test the, try catch block and break the connection. When I change the name of the database to test the exception, it just creates a new database.
Any ideas?
<?php
try{
$db = new PDO ("sqlite:".__DIR__."/database.db");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage();
exit;
}
echo "Connected to Database";
?>
I believe this is expected behavior with pdo_sqlite: if you provide a path to a database that doesn't exist, and PHP is able to write to files in the directory of that path, it will simply create the database under the filename you've provided.
If you want to test the case where the file isn't writable, you can change file permissions such that the user that PHP runs as doesn't have write access.
Because echo "Connected to Database"; is not within the try brackets, it will always echo that.
Try this.
<?php
try{
$db = new PDO ("sqlite:".__DIR__."/database.db");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo "Connected to Database";
} catch (Exception $e){
echo 'Caught exception: ', $e->getMessage();
exit;
}
?>
Related
I have a download script which get id of file and search in database and find it's name. But when I include my db connection the files get corrupted on download.
when I comment my db connection and give file name manually file downloading work fine.
I test my db connection and there wasn't any excpetion or any html output , what do you think my problem is?
<?php
session_start();
try{
$db= new PDO("mysql:host=localhost;dbname=dbname","user","pass");
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
$db->exec("SET NAMES 'utf8'");
}catch (Exception $e){
//echo "something wrong in db.php";
echo $e->getMessage();
exit;
}
?>
I run my code on windows server IIS, if it does matter
Just try with this code..
error_reporting(E_ALL);
ini_set('display_errors','1');
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
It will return your error.
after few days struggling and headache finaly problem resolved by deleting try catch block
I have a mac with OSX 10.8.4. I have installed my localhost and it works just fine. I have made a php script, from where I would like to connect MySQL workbench database to. My apache tomcat server runs, and also mysql on the computer, and I use XAMPP. This is my code:
<?php
// Establish connection to DB using PDO
try {
$pdo = new PDO('127.0.0.1:3306', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
echo "Connected!";
} catch (PDOException $e) {
$error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
echo "Connection failed";
exit();
}
I have tried this script to connect to a remote mysql server, where it works fine, but I cannot use it for my localhost. I also tried just to put in localhost in new PDO, but still the same. Does anybody have a clue to what is wrong?
Best Regards
Mads
You'll have an easier time knowing what's not working if you echo the exception being thrown.
Your code
} catch (PDOException $e) {
$error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
echo "Connection failed";
}
doesn't actually print the exception! Try this instead:
} catch (PDOException $e) {
$error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
echo $error;
}
That will at least give you some helpful debugging info.
I'm new to php I have created a php form that will insert data into the database my database name is Emp and the table name is info. I'm inserting using PDO. I have written a code to do this and it is getting executed without catching any errors, but the database is still empty. I have posted my code below please tell me what I'm doing wrong.
<?php
try{
echo $_POST['name'].", ".$_POST['age'].", ".$_POST['email'].", ".$_POST['name'].", ".$_POST['country'].", ". $_POST['city'] ;
$user="root";
$pass="root123";
$con=new PDO('mysql:host=localhost;dbname=Emp', $user, $pass);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->beginTransaction();
//echo "INSERT INTO info(Empid,Ename,Age,Email,Country,City,Salary) VALUES('".$_POST['eid']."','".$_POST['name']."','".$_POST['age']."','".$_POST['email']."','".$_POST['country']."','".$_POST['city']."','".$_POST['salary']."')";
$num=$con->exec("INSERT INTO info(Empid,Ename,Age,Email,Country,City,Salary) VALUES('".$_POST['eid']."','".$_POST['name']."','".$_POST['age']."','".$_POST['email']."','".$_POST['country']."','".$_POST['city']."','".$_POST['salary']."')");
echo "<br>".$num." row added succesfully"; // this is displayed when I execute this but database is empty.
}
catch(Exception $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
}
?>
Since you have used beginTransaction(), you have to commit the changes. Add
$con->commit();
Reference: PHP Manual
Note: Even though you are using PDO, you are still interpolating HTTP Request values without sanitization, that could be bad
you either have to commit or rollback the transaction ..
changes made to the database via the PDO transactions are not committed until you end the transaction by calling PDO::commit() or Calling PDO::rollBack()
<?php
try{
echo $_POST['name'].", ".$_POST['age'].", ".$_POST['email'].", ".$_POST['name'].", ".$_POST['country'].", ". $_POST['city'] ;
...
$con->beginTransaction();
....
$con->commit();
}
catch(Exception $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
$con->rollBack();
}
?>
All you need to do is to commit and/or rollBack your code
<?php
try{
.
. code
.
$con->beginTransaction();
.
. code
.
$num=$con->exec("INSERT INTO info (Empid,Ename,Age,Email,Country,City,Salary) VALUES('".$_POST['eid']."','".$_POST['name']."','".$_POST['age']."','".$_POST['email']."','".$_POST['country']."','".$_POST['city']."','".$_POST['salary']."')");
$con->commit(); // This is missing
}
catch(Exception $e)
{
var_dump($e->getMessage());
$con->rollBack(); // And this is missing
}
?>
I am starting to use PDO and I successfully connected to MySQL using PDO. However, when I try to SELECT stuff from my DB, nothing happens. Nothing is echoed. (even though I have records in that table, and the column username exists) No error in my PHP log.
I am using MAMP and all PDO components seem to be working in phpinfo() (since I was able to connect to db in the first place)
Please let me know what could have gone wrong. Thanks a lot
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
$stmt=$connection->prepare("SELECT * FROM users");
$stmt->execute();
while ($row=$stmt->fetch(PDO::FETCH_OBJ)){
echo $row->username;
}
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
You need to tell PDO that you want it to throw exceptions:
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Following your comment below, it is apparent that your DSN is incorrect. It should be:
$connection = new PDO('mysql:host=localhost;dbname=my_db','my_username','xxxxxxx');
Note that the syntax is dbname= rather than dbname: (which you had originally).
First, get your query out of your PDO connection segment...
<?php
try
{
$connection = new PDO('mysql:host=localhost;dbname:my_db','my_username',
'xxxxxxx');
}
catch(Exception $e)
{
echo "There was an error connecting to the database";
}
?>
Then, do it.
<?php
$SQL = 'SELECT * FROM users';
foreach($connection->query($SQL) as $row){
print $row['username'] . "\n".'<br />';
}
?>
Why not ask PHP?
catch(Exception $e)
{
die($e);
}
Looks like your either don't have data in that table or have an error:
Try to add this code after $stmt->execute();:
$arr = $sth->errorInfo();
print_r($arr);
I have a problem with my database! Here is my code:
<?php
$host = "/homes/49/jc192699/public_html/dbase";
$database = "EduPro.db";
$dbhandle = new PDO("sqlite:".$host.$database);
if (!$dbhandle){
echo "Error connecting to database.\n";
}
else{
echo "<br>";
echo "<br>";
echo "Database connection successful!";
}
mysql_select_db($database);
?>
The problem is that it's saying "Database connection successful!" No matter what I do, if I type the address in wrong, it still says successful, when I renamed the database to a database that doesn't exist, it still says successful. I can't see what the problem is here?
If anybody could help me out it would be GREATLY appreciated!
Thank you!
For starters, the PDO constructor throws an exception if there is an error. It does not return false. Check for errors using
try {
$dbhandle = new PDO("sqlite:".$host.$database);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Secondly, as you are using SQLite, provided your dbase directory is writeable by the script, your connection attempt will create an empty database.
Try this:
<?php
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:/path/to/database.sdb");
}
catch(PDOException $e)
{
/*** real error message prints here ***/
echo $e->getMessage();
}
?>
This is directly taken from here:
http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#4.2