Php database connection _ MySQL

Source: Internet
Author: User
With PHP, you can easily connect to the database, request data and display it on your web site, or even modify data in the database. MySQL is a very popular database, and there are many tutorials on PHP and MySQL on the Internet. MySQL is free, which may attract many people. Because of its wide application, I don't want to repeat MySQL users here. with PHP, you can easily connect to the database, request data, and display it on your web site, or even modify the data in the database. MySQL is a very popular database, and there are many tutorials on PHP and MySQL on the Internet. MySQL is free, which may attract many people. Because of its wide application, I don't want to repeat MySQL usage here. Oracle is widely used in enterprise applications, so we use Oracle to introduce the connection between PHP and database. Of course we will not mention the design principles of Oracle databases, because this is beyond our scope of discussion.
PHP provides two sets of functions connected to Oracle: ORA _ and OCI. The ORA _ function is somewhat outdated. OCI function updates are said to be better. The syntax is almost the same. As mentioned above, your PHP installation options should support both.
For more information about installing an Apache server that supports PHP3 on Microsoft Windows and about Oracle databases, see the following URL: www.csoft.net /~ Vsbabu/articles/oraphp.html.
4.1 Connection

If ($ conn = Ora_Logon ("user @ TNSNAME", "password "))
{
Echo "SUCCESS! Connected to database \ n ";
}
Else
{
Echo "Failed:-(cocould not connect to database \ n ";
}
Ora_Logoff ($ conn );
Phpinfo ();
?>
The above code uses the Oracle database name, user name, and password defined by TNSNAME (specified in your tnsnames. ora file) to connect to the database. Based on successful connections, the ora_logon function returns a non-zero connection ID and stores it in the variable $ conn.

4.2 Query

If the connection to the database is ready, we will query the database using the actual application. The following code demonstrates a typical connection and Query example:
/*
* Connect to the database and perform query
*/
Function printoraerr ($ in_cur)
{
// Check for Oracle errors
// If an error exists, it is displayed.
// This function is called after each request to Oracle when the pointer is activated
If (ora_errorcode ($ in_cur ))
Echo "Oracle code-". ora_error ($ in_cur). "\ n ";
Return;
}
/** Main program */
If (! ($ Conn = ora_logon ("user @ TNSNAME", "password ")))
{
Echo "Connection to database failed \ n ";
Exit;
}
Echo "Connected as connection-$ conn
\ N ";
Echo "Opening cursor...
\ N ";
$ Cursor = ora_open ($ conn); printoraerr ($ cursor );
Echo "Opened cursor-$ cursor
\ N ";
$ Qry = "select user, sysdate from dual ";
Echo "Parsing the query $ qry...
\ N ";
Ora_parse ($ cursor, $ qry, 0); printoraerr ($ cursor );
Echo "Query parsed
\ N ";
Echo "Executing cursor...
\ N ";
Ora_exec ($ cursor); printoraerr ($ cursor );
Echo "Executed cursor
\ N ";
Echo "Fetching cursor...
\ N ";
While (ora_fetch ($ cursor ))
{
$ User = ora_getcolumn ($ cursor, 0); printoraerr ($ cursor );
$ Sysdate = ora_getcolumn ($ cursor, 1); printoraerr ($ cursor );
Echo "row = $ user, $ sysdate
\ N ";
}
Echo "Fetched all records
\ N ";
Echo "Closing cursor...
\ N ";
Ora_close ($ cursor );
Echo "Closed cursor
\ N ";
Echo "Logging off from oracle...
\ N ";
Ora_logoff ($ conn );
Echo "Logged off from oracle
\ N ";
?>
(Note: The above code segment lacks comments. For more information, see the Oracle database function section of PHP Manual)

4.3 Display results

The following code describes how to query a database and output the result:
Function printoraerr ($ in_cur, $ conn)
{
// Check for Oracle errors
// If an error exists, it is displayed.
// This function is called after each request to Oracle when the pointer is activated
// If it encountered an error, we exit immediately
If (ora_errorcode ($ in_cur ))
{
Echo "Oracle code-". ora_error ($ in_cur )."
N ";
Ora_logoff ($ conn );
Exit;
}
Return;
}

Function exequery ($ w_qry, $ conn)
{
$ Cursor = ora_open ($ conn); printoraerr ($ cursor, $ conn );
Ora_parse ($ cursor, $ w_qry, 0); printoraerr ($ cursor, $ conn );
Ora_exec ($ cursor); printoraerr ($ cursor, $ conn );
$ Numrows = 0;
$ W_numcols = ora_numcols ($ cursor );
// Display the header
Echo"

\ N ";
For ($ I = 0; $ I <$ w_numcols; $ I ++)
{
$ Align = (ora_columntype ($ cursor, $ I) = "NUMBER ")? "RIGHT": "LEFT ";
Echo "\ t". ora_columnname ($ cursor, $ I). "\ n ";
}
Echo"
\ N ";
While (ora_fetch ($ cursor ))
{
Echo "\ n ";
For ($ I = 0; $ I <$ w_numcols; $ I ++)
{
$ Align = (ora_columntype ($ cursor, $ I) = "NUMBER ")? "RIGHT": "LEFT ";
If (ora_columntype ($ cursor, $ I) = "LONG ")
Echo "".
Ora_getcolumn ($ cursor, $ I )."
\ N ";
Else
Echo "". ora_getcolumn ($ cursor, $ I). "\ n ";
Printoraerr ($ cursor, $ conn );
}
$ Numrows ++;
Echo"
\ N ";
}
If ($ numrows = 0)
Echo "Query returned no records

\ N ";
Else
{
Echo "\ n ";
Echo "Count \ n ";
Echo "$ numrows \ n ";
Echo"
\ N ";
}
Echo "\ n ";
Ora_close ($ cursor );
Return;
}

// Main program
If (! ($ Conn = ora_logon ("user @ SID", "password ")))
{
Echo "Error: Cannot connect to database \ n ";
Exit;
}
$ Qry = "SELECT
Deptno \ "Dept \"
, Empno \ "Emp \"
, Empnm \ "Name \"
, Salary \ "Salary \"
FROM
Employee
Order by 1, 2 ";
Exequery ($ qry );
Ora_logoff ($ conn );
?>
(Note: The above code segment lacks comments. For more information, see the Oracle database function section of PHP Manual)

4.4 HTTP-based Oracle login

Add the following code before the PHP page code to confirm Oracle login. Note that you must set $ SID correctly.
If (! Isset ($ PHP_AUTH_USER ))
{
Header ("WWW-authenticate: basic realm = \" $ SID \"");
Header ("HTTP/1.0 401 Unauthorized ");
$ Title = "Login Instructions ";
Echo"


You are not authorized to enter the site

\ N ";
Exit;
}
Else
{
If (! ($ Conn = ora_logon ("$ PHP_AUTH_USER @ $ SID", $ PHP_AUTH_PW )))
{
Header ("WWW-authenticate: basic realm = \" $ SID \"");
Header ("HTTP/1.0 401 Unauthorized ");
$ Title = "Login Instructions ";
Echo"

You are not authorised to enter the site

\ N ";
Exit;
}
}
?>

CNBIE BLOG
--------------------------------------------------------------------------------

Php sends emails via smtp
Original article: php sends emails via smtp

/***************************************
** Filename...: class. smtp. inc
** Project ......: SMTP Class
** Version...: 1.00b
** Last Modified...: 30 September 2001
***************************************/



Define ('smtp _ STATUS_NOT_CONNECTED ', 1, TRUE );
Define ('smtp _ status_connected', 2, TRUE );



Class smtp {



Var $ connection;
Var $ recipients;
Var $ headers;
Var $ timeout;
Var $ errors;
Var $ status;
Var $ body;
Var $ from;
Var $ host;
Var $ port;
Var $ helo;
Var $ auth;
Var $ user;
Var $ pass;



/***************************************
** Constructor function. Arguments:
** $ Params-An assoc array of parameters:
**
** Host-The hostname of the smtp server Default: localhost
** Port-The port the smtp server runs on Default: 25
** Helo-What to send as the HELO command Default: localhost
** (Typically the hostname of
** Machine this script runs on)
** Auth-Whether to use basic authentication Default: FALSE
** User-Username for authentication Default:
** Pass-Password for authentication Default:
** Timeout-The timeout in seconds for the call Default: 5
** To fsockopen ()
***************************************/



Function smtp ($ params = array ()){



If (! Defined ('crlf '))
Define ('crlf ', "\ r \ n", TRUE );

$ This-> timeout = 5;
$ This-> status = SMTP_STATUS_NOT_CONNECTED;
$ This-> host = 'localhost ';
$ This-> port = 25;
$ This-> helo = 'localhost ';
$ This-> auth = FALSE;
$ This-> user = ';
$ This-> pass = ';
$ This-> errors = array ();



Foreach ($ params as $ key => $ value ){
$ This-> $ key = $ value;
}
}



/***************************************
** Connect function. This will, when called
** Statically, create a new smtp object,
** Call the connect function (ie this function)
** And return it. When not called statically,
** It will connect to the server and send
** The HELO command.
***************************************/



Function connect ($ params = array ()){



If (! Isset ($ this-> status )){
$ Obj = new smtp ($ params );
If ($ obj-> connect ()){
$ Obj-> status = SMTP_STATUS_CONNECTED;
}



Return $ obj;



} Else {
$ This-> connection = fsockopen ($ this-> host, $ this-> port, $ errno, $ errstr, $ this-> timeout );
Socket_set_timeout ($ this-> Connections, 0, 250000 );



$ Greeting = $ this-> get_data ();
If (is_resource ($ this-> connection )){
Return $ this-> auth? $ This-> ehlo (): $ this-> helo ();
} Else {
$ This-> errors [] = 'failed' to connect to server: '. $ errstr;
Return FALSE;
}
}
}



/***************************************
** Function which handles sending the mail.
** Arguments:
** $ Params-Optional assoc array of parameters.
** Can contain:
** Recipients-Indexed array of recipients
** From-The from address. (used in mail from :),
** This will be the return path
** Headers-Indexed array of headers, one header per array entry
** Body-The body of the email
** It can also contain any of the parameters from the connect ()
** Function
***************************************/



Function send ($ params = array ()){



Foreach ($ params as $ key => $ value ){
$ This-> set ($ key, $ value );
}



If ($ this-> is_connected ()){



// Do we auth or not? Note the distinction between the auth variable and auth () function
If ($ this-> auth ){
If (! $ This-> auth ())
Return FALSE;
}



$ This-> mail ($ this-> from );
If (is_array ($ this-> recipients ))
Foreach ($ this-> recipients as $ value)
$ This-> rcpt ($ value );
Else
$ This-> rcpt ($ this-> recipients );



If (! $ This-> data ())
Return FALSE;



// Transparency
$ Headers = str_replace (CRLF. '.', CRLF. '...', trim (implode (CRLF, $ this-> headers )));
$ Body = str_replace (CRLF. '.', CRLF. '...', $ this-> body );
$ Body = $ body [0] = '.'? '.'. $ Body: $ body;



$ This-> send_data ($ headers );
$ This-> send_data (');
$ This-> send_data ($ body );
$ This-> send_data ('.');



Return (substr (trim ($ this-> get_data (), 0, 3) === '20140901 ');
} Else {
$ This-> errors [] = 'not ccted! ';
Return FALSE;
}
}

/***************************************
** Function to implement HELO cmd
***************************************/



Function helo (){
If (is_resource ($ this-> connection)
AND $ this-> send_data ('helo'. $ this-> HELO)
AND substr (trim ($ error = $ this-> get_data (), 0, 3) = '20140901 '){



Return TRUE;



} Else {
$ This-> errors [] = 'Helo command failed, output: '. trim (substr (trim ($ error), 3 ));
Return FALSE;
}
}

/***************************************
** Function to implement EHLO cmd
***************************************/



Function ehlo (){
If (is_resource ($ this-> connection)
AND $ this-> send_data ('ehlo'. $ this-> helo)
AND substr (trim ($ error = $ this-> get_data (), 0, 3) = '20140901 '){



Return TRUE;



} Else {
$ This-> errors [] = 'ehlo command failed, output: '. trim (substr (trim ($ error), 3 ));
Return FALSE;
}
}

/***************************************
** Function to implement AUTH cmd
***************************************/



Function auth (){
If (is_resource ($ this-> connection)
AND $ this-> send_data ('auth login ')
AND substr (trim ($ error = $ this-> get_data (), 0, 3) = '20140901'
AND $ this-> send_data (base64_encode ($ this-> user) // Send username
AND substr (trim ($ error = $ this-> get_data (), 334) = '20140901'
AND $ this-> send_data (base64_encode ($ this-> pass) // Send password
AND substr (trim ($ error = $ this-> get_data (), 235) = '20140901 '){



Return TRUE;



} Else {
$ This-> errors [] = 'auth command failed: '. trim (substr (trim ($ error), 3 ));
Return FALSE;
}
}



/***************************************
** Function that handles the mail from: cmd
***************************************/

Function mail ($ from ){



If ($ this-> is_connected ()
AND $ this-> send_data ('mail FROM: <'. $ from.'> ')
AND substr (trim ($ this-> get_data (), 0, 2) === '20140901 '){



Return TRUE;



} Else
Return FALSE;
}



/***************************************
** Function that handles the rcpt to: cmd
***************************************/

Function rcpt ($ ){



If ($ this-> is_connected ()
AND $ this-> send_data ('rcpt TO: <'. $ to.'> ')
AND substr (trim ($ error = $ this-> get_data (), 0, 2) = '25 '){



Return TRUE;



} Else {
$ This-> errors [] = trim (substr (trim ($ error), 3 ));
Return FALSE;
}
}



/***************************************
** Function that sends the DATA cmd
***************************************/



Function data (){



If ($ this-> is_connected ()
AND $ this-> send_data ('data ')
AND substr (trim ($ error = $ this-> get_data (), 0, 3) = '20140901 '){

Return TRUE;



} Else {
$ This-> errors [] = trim (substr (trim ($ error), 3 ));
Return FALSE;
}
}



/***************************************
** Function to determine if this object
** Is connected to the server or not.
***************************************/



Function is_connected (){



Return (is_resource ($ this-> connection) AND ($ this-> status === SMTP_STATUS_CONNECTED ));
}



/***************************************
** Function to send a bit of data
***************************************/



Function send_data ($ data ){



If (is_resource ($ this-> connection )){
Return fwrite ($ this-> connection, $ data. CRLF, strlen ($ data) + 2 );
} Else
Return FALSE;
}



/***************************************
** Function to get data.
***************************************/



Function & get_data (){



$ Return = ';
$ Line = ';



If (is_resource ($ this-> connection )){
While (strpos ($ return, CRLF) === false or substr ($ line, 3,1 )! = ''){
$ Line = fgets ($ this-> connection, 512 );
$ Return. = $ line;
}
Return $ return;



} Else
Return FALSE;
}



/***************************************
** Sets a variable
***************************************/

Function set ($ var, $ value ){



$ This-> $ var = $ value;
Return TRUE;
}



} // End of class
?>

/***************************************
** Filename...: test. php
** Project ......: SMTP Class
** Last Modified...: 30 September 2001
***************************************/



/***************************************
** Include the class. The header () makes
** The output look lovely.
***************************************/
Include ('class. smtp. Inc ');
Header ('content-Type: text/plain ');



/***************************************
** Setup some parameters which will be
** Passed to the smtp: connect () call.
***************************************/
$ Params ['host'] = 'smtp .sohu.com '; // The smtp server host/ip
$ Params ['port'] = 25; // The smtp server port
$ Params ['helo'] = exec ('hostname'); // What to use when sending the helo command. Typically, your domain/hostname
$ Params ['auth'] = TRUE; // Whether to use basic authentication or not
$ Params ['user'] = 'phw82 '; // Username for authentication
$ Params ['pass'] = 'xxxxxxx'; // Password for authentication



/***************************************
** These parameters get passed to
** Smtp-> send () call.
***************************************/



$ Send_params ['referents'] = array ('phw82 @ sohu.com '); // The recipients (can be multiple)
$ Send_params ['headers'] = array (
'From: "Pan" ', // Headers
'To: phw82@sohu.com ',
'Subject: Test email'
);
$ Send_params ['from'] = 'phw82 @ sohu.com '; // This is used as in the MAIL from: cmd
// It shoshould end up as the Return-Path: header
$ Send_params ['body'] = '. Test email.'; // The body of the email




/***************************************
** The code that creates the object and
** Sends the email.
***************************************/
?>






New Document









If (is_object ($ smtp = smtp: connect ($ params) AND $ smtp-> send ($ send_params )){
Echo 'email sent successfully! '. "\ R \ n ";



// Any recipients that failed (relaying denied for example) will be logged in the errors variable.
Print_r ($ smtp-> errors );



} Else {
Echo 'error sending mail'. "\ r \ n ";

// The reason for failure shocould be in the errors variable
Print_r ($ smtp-> errors );
}



?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.