I'm trying to validate my php form using exception, but somehow it doesn't work. The exception is supposed to be thrown if the user enters in "nameg" any character which is not string and in the "amountg" anything which is not integer. Should Exceptions even be used in this case:
if(!empty($_POST['nameg']) && !empty($_POST['amountg']))
{
$user="rootdummy";
$pass="password";
$db="practice";
$nameg=$_POST['nameg'];
$amountg=$_POST['amountg'];
try{
if(!is_int($amountg) || !is_string($nameg)){
throw new Exception("This is the exception message!");
}
}
catch (Exception $e){
$e->getMessage();
}
mysql_connect('localhost',$user,$pass) or die("Connection Failed!, " . mysql_error());
$query="INSERT INTO practable (name,given) VALUES('$nameg',$amountg) ON DUPLICATE KEY UPDATE name='$nameg', given=IFNULL(given + $amountg,$amountg)";
mysql_select_db($db) or die("Couldn't connect to Database, " . mysql_error());
mysql_query($query) or die("Couldn't execute query! ". mysql_error());
mysql_close() or die("Couldn't disconnect!");
include("dbclient.php");
echo "<p style='font-weight:bold;text-align:center;'>Information Added!</p>";
}
Presumably you want to output the exception? Do:
echo $e->getMessage();
Edit: In response to your later comment regarding script ending, put the MySQL queries in the try block.
Edit 2: Changed validation in response to your comments.
if(!empty($_POST['nameg']) && !empty($_POST['amountg']))
{
$user="rootdummy";
$pass="password";
$db="practice";
$nameg=$_POST['nameg'];
$amountg=$_POST['amountg'];
try{
if(!ctype_numeric($amountg) || !ctype_alpha($nameg)){
throw new Exception("This is the exception message!");
}
mysql_connect('localhost',$user,$pass) or die("Connection Failed!, " . mysql_error());
$query="INSERT INTO practable (name,given) VALUES('$nameg',$amountg) ON DUPLICATE KEY UPDATE name='$nameg', given=IFNULL(given + $amountg,$amountg)";
mysql_select_db($db) or die("Couldn't connect to Database, " . mysql_error());
mysql_query($query) or die("Couldn't execute query! ". mysql_error());
mysql_close() or die("Couldn't disconnect!");
include("dbclient.php");
echo "<p style='font-weight:bold;text-align:center;'>Information Added!</p>";
}
catch (Exception $e){
echo $e->getMessage();
}
}
It does, but you're doing nothing with your exception, except catching it.
Try
echo $e->getMessage()
You are catching it and performing a statement that does virtually nothing.
$e->getMessage(); just gets it as a string and throws it away without echoing it.
Either echo it or rethrow or, if you just wanted to exit at that point, don't catch the exception at all (you can remove both the try and catch blocks).
Related
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'm doing this (yes, I'm using wrong connection data, it's to force a connection error )
try {
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
} catch (Exception $e ) {
echo "Service unavailable";
exit (3);
}
But PHP is doing this php_warning:
mysqli::mysqli(): (28000/1045): Access denied for user 'my_user'#'localhost' (using password: YES)
In the example I'm using wrong connection data to force a connection error, but in the real world the database could be down, or the network could be down... etc..
Question: Is there a way, without suppressing warnings, to intercept a problem with the database connection ?
You need to tell mysqli to throw exceptions:
mysqli_report(MYSQLI_REPORT_STRICT);
try {
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
} catch (Exception $e ) {
echo "Service unavailable";
echo "message: " . $e->message; // not in live code obviously...
exit;
}
Now you will catch the exception and you can take it from there.
For PHP 5.2.9+
if ($mysqli->connect_error) {
die('Connect Error, '. $mysqli->connect_errno . ': ' . $mysqli->connect_error);
}
You'll want to set the Report Mode to a strict level as well, just as jeroen suggests, but the code above is still useful for specifically detecting a connection error. The combination of those two approaches is what's recommended in the PHP manual.
Check $connection->connect_error value.
See the example here: http://www.php.net/manual/en/mysqli.construct.php
mysqli_report(MYSQLI_REPORT_STRICT);, as described elsewhere, gives me an error and stops the script immediately. But this below seems to provide the desired output for me...
error_reporting(E_ERROR);
$connection = new mysqli('localhost', 'my_user', 'my_password', 'my_db') ;
error_reporting(E_ERROR | E_WARNING | E_PARSE);
if($connection->connect_errno)
{
// Database does not exist, you lack permissions, or some other possible error.
if(preg_match($connection->connect_error, "Access denied for user"))
{
print("Access denied, or database does not exist.");
}
else
{
print("Error: " . $connection->connect_error);
}
}
Attempting to catch this error with try..catch() will fail.
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
I have an error.php file which can be grossly simplified to:
<?
if (!isset($error))
$error = "Unspecified Error";
echo "Error: $error";
?>
It is not "normal usage" to just navigate to error.php. Rather, I would do something like:
$dbh = mysql_connect($host, $user, $pass);
if (!$dbh)
{
$error = "Can't connect to MySQL: " . mysql_error();
include('error.php');
exit();
}
That said, if the user does navigate to error.php then they will just get "Error: Unspecified Error" as expected.
All my code is working, and the error page shows up and works exactly as expected, however Zend is complaining that $error is undefined on the line: if (!isset($error)).
I realise my design pattern is awful, but I'm just throwing together something quick-and-dirty in this case.
Better idea, create a function instead:
function output_error( $error = NULL )
{
if( !$error ) $error = "Unspecified Error";
echo "Error: $error";
}
It has the benefit of both removing the Zend issue, and you have a MUCH better design. Then:
if (!$dbh)
{
include('error.php');
output_error( "Can't connect to MySQL: " . mysql_error() );
exit();
}
$dbh = mysql_connect($host, $user, $pass);
if (!$dbh){
$error = "Can't connect to MySQL: " . mysql_error();
if(!include('error.php'){
echo $error;
exit();
}
}
Try this:
if (!isset(#$error)).