I am working on my first ever .php application! All I am doing is posting some data to a database: simple stuff.
Right now, everything works fine, I can send my data to the DB no problems. However, I want to return an error message to my Objective-c application. I have the try and catch statements to make sure I connect to the DB, and if there is an error I would like to communicate that back to my application.
Here is some of what I have so far:
$dsn='mysql:dbname=******;host=******;';
$user='******';
$pass='******';
try {
/* obtain a database connection handle */
$pdo = new PDO($dsn, $user, $pass);
}
catch (PDOException $exception) {
echo("Failed to connect to the database. Error: " . $exception->getMessage());
}
Also, is it possible to set a limit for how long the PDO will attempt to connect to the database?
Right now when I purposely put in something invalid, it tries to connect for a long time.
If you're trying to do what I think you are, it doesn't work like that.
If you want to pass the error message to an Objective-C application, you will need to pipe, write contents to a file, or write the error to STDERR and capture it from the Objective-C application.
What exactly are you trying to accomplish? Calling a PHP script from an Objective-C script?
According to the PDO documentation, you can pass an array of driver options to it:
PDO::__construct() ( string $dsn [, string $username [, string $password [, array $driver_options ]]] )
In this same page there is an example of some driver specific options, also i believe you can use the PDO::ATTR_TIMEOUT and/or one of these:
http://www.php.net/manual/es/pdo.constants.php
Related
We have a remote server containing a SQL MariaDB. I have to write a piece of code to be placed in that same server whose mission is to execute querys asking for data, modify that data and send it to an external api hosted in another server. When I was shown the DB, it was through ssh commands and entering sql mode inside the server rather than trough code like PHP as I have always done it before.
So, my code is to placed in the same server as the DB, brings the data, modifys some info and calls the api to upload it.
As I said, I am completely lost so my question is simple: can this be achieved? if so, how?
I've read about ssh_connect and exec, but since the code will be placed in the same server I don't think this is necessary, correct me if I am wrong. I can't place any code since I don't know how to start.
Thank you guys for all the help, I am closing the question now:
All I had to do was to use PDO as a secure way to establish a connection and to prepare and execute the querys. Remember I placed my php file in the same server that hosts the DB and note that I had to create a user and grant permissions to the DB you can find how in one of the comments above or here. Here is the code:
try {
$conn = new PDO('mysql:host=yourhostserver;dbname=dbname','user','password');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}catch(PDOException $e){
echo "ERROR: " . $e->getMessage();
}
//Example of query
$stmt = $conn->prepare('SELECT GROUP_CONCAT(DISTINCT source_external_subscriber_id) AS ids FROM cdr');
$stmt->execute();
foreach ($stmt as $row) {
$string = $row['ids'];
}
I am trying to connect to my database with the following code. And it works, but I am not sure how secure is it. Do I must have a private function too? I don't have any examples of how to apply a private function on this code.
$username = 'user';
$dsn = 'mysql:host=localhost; dbname=register';
$password = 'somepassword';
try{
$db = new PDO($dsn, $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch (PDOException $ex){
echo "Connection failed ".$ex->getMessage();
}
Better use php composer where you can put these details in a environment file .env. It will be secured as .env is hidden and is placed on Server.
Put the connection parameters into a secure place (i.e. not reachable
by HTTP requests, something like the first answer will be nice), don't leave them into PHP script or some file in the same context... if you put there, protect it with htaccess DENY directive
Never echo exceptions into script output, always deal with them (put
into a log file, translate to friendly errors hiding parameters,
etc). The script never should throw exceptions to the user, it must be handled... the user must only see friendly messages from the script, even a "Ops, something bad happen here..." is better than a "ERROR: SQLSTATE[42000] [1049] Unknown database 'users'" (that show the user a part of the database structure, witch is a security problem)
I have several stored procedures that I am calling via PDO in PHP. I was hoping to be able to handle errors by performing a ROLLBACK, but I still want to be able to use PHP to retrieve and handle the last error in the procedure. I have tryed using PDO::errorCode() and PDO::errorInfo(), but that does seem to be a legitimate solution, I think because I am already handling the errors in my stored procedures.
When I call one of the stored procedures via command line and then call SHOW ERRORS I get a nice result set with the error status, code and message, but if I call SHOW ERRORS in PDO after executing the stored procedure, I get no results. I also get no result from SHOW ERRORS in command line if I call show errors inside the stored procedure.
I would use GET DIAGNOSTICS, but the MySQL server I am developing for is on a hosted cPanel that I don't have control over updating and it is version 5.5.
Is there some other option I could use or another route I should be taking?
Like I said, I have several stored procedures I want to handle errors, but I can't even get this to work on a simple stored procedure:
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;
SELECT *
FROM bunnies;
END
Update: My PHP code was in an object, so I copied and simplified the code to post per Barmar's request and when I tried the simplified code, I found that SHOW ERRORS does indeed work with PDO when prepared and executed after the function is prepared and executed.
My object was a little complicated (I wrote it a while back before I knew much about PHP OOP), so I simplified it as well and now it works! I think the connection was being closed in between calls and now that the code is simpler, I am having no problems with calling SHOW ERRORS in it.
Here's the simplified PHP code I used to test, in case anyone has had issues getting this to work:
$host = '***';
$user = '***';
$pass = '***';
$schema = '***';
$connection = new PDO('mysql:host=' . $host . ';dbname=' . $schema . ';', $user, $pass);
$statement = $connection->prepare('CALL test()');
$statement->execute();
$statement = $connection->prepare('SHOW ERRORS');
$statement->execute();
echo var_dump($statement->fetchAll());
$statement = null;
$statement = null;
$connection = null;
Make sure you use the same PDO connection object to execute the original queries and to retrieve the errors. Each connection has its own error state.
I'm a beginner programmer, and I've installed XAMPP with the intention of learning a bit of PHP. I have a working knowledge of SQL.
I've been following the PHP tutorial at w3schools. The problem I am currently having is this: I'm using the script here to create a database and a table within it. What I'm using is almost verbatim, except I've replaced the user with "root" and I've deleted the password.
After running the script through the browser, the database my_db appears in the datafile for mysql in XAMPP.
However, there is no sign of a table, and when I try to select the table, I get
Table 'my_db.persons' doesn't exist
What is going on? Is there something wrong with the code I took verbatim, or is it something with permissions?
It's weird that the database is created but not a table...
What has happenned is that your "CREATE TABLE" will have failed.
Get into the habit of checking for errors after EVERY mySQL query (in your code): there are some times you can ignore errors, but it's rare. So program alonghte lines of:
Create query: $sql =
Set parameters: $aParams = (or bind paramters)
Execute query
If errors
If debug: Show error and query
If live: Log error and query
I'm not giving the solution is code, as one problem with the tutorial you follow is that it uses mysql_() functions that are going to be depreciated shortly. You should use PDO (PHP Database Objects) or mysqli() functions otherwise your code will not work in a few releases time.
With PDO, you can set error handling to use exceptions, and you wrap every call in try {} catch {} and this makes the habit of catching and reporting errors very easy.
$sql = 'CREATE TABLE....';
$aParams = array(
':param_name' => $param_value,
':param_name2' => $param_value2
);
try {
$stmnt = $db->prepare($sql);
$stmnt->execute($aParams);
$stmnt = null;
} catch (Exception $e) {
// Error log here; $e contins line of error and the actual error, you have $sql and $aParams
LogDBError($e, $sql, $aParams);
}
this post has been edited to reflect the findings thus far between myself and iamkrillin, as we have been the only two posters
I have the following VB.NET code connecting correctly, running from my PC
Dim strConnection As String = "Server=dev.xxxxx.vmc;Database=report1;integrated security=SSPI;" & _
"persist security info=False;Trusted_Connection=Yes;"
Dim ObjDa As SqlDataAdapter = New SqlDataAdapter(pStrQuery, strConnection)
Try
Dim dsReturn As DataSet = New DataSet
ObjDa.Fill(dsReturn)
ObjDa.Dispose()
Return dsReturn
Catch ex As Exception
Return Nothing
End Try
I have the following PHP code running from our iSeries
$conn = array( 'host' => 'dev.xxxxx.vmc',
'username' => 'vmc\adam',
'password' => 'xxxxxx)',
'dbname' => 'report1',
'pdoType' => 'dblib' );
try {
$db = new Zend_Db_Adapter_Pdo_Mssql($conn);
$db->getConnection();
} catch (Zend_Db_Adapter_Exception $e) {
}
The getConnection function, is throwing an error:
SQLSTATE[] (null) (severity 0)
And when I look up this error HERE, it appears to be a bug PRE 5.2.10, and we are running 5.2.17. But, some of the other comments say it is still a bug in 5.3.
*edit
It seems that if using a domain account, windows auth must be enabled. However, it is not through our PHP. So I need to set up a database specific user for our PHP connection.
In your VB snippet, you are connecting to SQL Server, and in your PHP snippet you are connecting to MySQL. If you need to use SQL Server from PHP, look at this. If you are on a non windows platform you can try FreeTDS. Here is an example of how to get started with it