Simple PHP Database Connections

扶醉桌前 提交于 2019-12-11 02:37:46

问题


I am making a simple page to test a database connection. When I tried accessing it from my browser, it says:

Server error

The website encountered an error while retrieving http://localhost:8888/blah/blah/test.php. It may be down for maintenance or configured incorrectly.

Here are some suggestions:

Reload this webpage later. HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfill the request.

All I am doing is connecting to a database and displaying the tables. Here is what I have so far as the PHP code:

<?php
// Get Variables
$dbname = $_GET["dbname"];
$dbusername = $_GET["dbusername"];
$dbpass = $_GET["dbpass"];
$dbhost = $_GET["dbhost"];






$connection = mysql_connect("$dbhost","$dbusername","$dbpass");
if (!$connection)
{
    die('Could not connect: ' . mysql_error());
}
else
{
    echo "Connected";

    $dbcheck = mysql_select_db("$dbname");
    if (!$dbcheck) {
        echo mysql_error();
    }else{
        echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
// Check tables
        $sql = "SHOW TABLES FROM `$database`";
        $result = mysql_query($sql);
        if (mysql_num_rows($result) > 0) {
            echo "<p>Available tables:</p>\n";
            echo "<pre>\n";
            while ($row = mysql_fetch_row($result)) {
                echo "{$row[0]}\n";
            }
            echo "</pre>\n";
        } else {
            echo "<p>The database '" . $database . "' contains no tables.</p>\n";
            echo mysql_error();
        }



    }

// some code

    mysql_close($con);



    ?>

My error in the WAMP Apache logs is:

[03-Feb-2013 22:47:37 UTC] PHP Parse error:  syntax error, unexpected end of file                              in /Applications/MAMP/htdocs/coursemanager/default/verify1.php on line 52

What would a unexpected end of file be?


回答1:


You forgot a } on the end to close: else{ echo "Connected";

<?php

// Get Variables
$dbname = $_GET["dbname"];
$dbusername = $_GET["dbusername"];
$dbpass = $_GET["dbpass"];
$dbhost = $_GET["dbhost"];


$connection = mysql_connect("$dbhost", "$dbusername", "$dbpass");
if (!$connection) {
    die('Could not connect: ' . mysql_error());
} else {
    echo "Connected";

    $dbcheck = mysql_select_db("$dbname");
    if (!$dbcheck) {
        echo mysql_error();
    } else {
        echo "<p>Successfully connected to the database '" . $database . "'</p>\n";
// Check tables
        $sql = "SHOW TABLES FROM `$database`";
        $result = mysql_query($sql);
        if (mysql_num_rows($result) > 0) {
            echo "<p>Available tables:</p>\n";
            echo "<pre>\n";
            while ($row = mysql_fetch_row($result)) {
                echo "{$row[0]}\n";
            }
            echo "</pre>\n";
        } else {
            echo "<p>The database '" . $database . "' contains no tables.</p>\n";
            echo mysql_error();
        }
    }
}
// some code. no need to close mysql and no need to close php



回答2:


It is very simple PHP database connection

<?php
    $dbhost = "dbhostname";
    $dbusername = "dbusername";
    $dbpassword = "dbpassword";
    $dbname = "dbname";

$connection = mysql_connect($dbhost, $dbusername, $dbpassword) or die('Could not connect');
$db = mysql_select_db($dbname);
?>



回答3:


Using the PDO (PHP extension) is reliable and efficient method to connect to MySQL. PDO also gives more configuration to users and it can handle exception also.

PDO connection code will be like this:

 $hostname='localhost';$username='root';$password='';
 try {    
    $dbh = new PDO("mysql:host=$hostname;dbname=stickercollections",$username,$password);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line    echo 'Connected to Database<br/>';
} catch(PDOException $e) {
  echo $e->getMessage();    
}

By using the PDO method, you can avoid this 500 errors and other exceptions. You can configure global error messages in a professional way.

Reference : Connect php to database




回答4:


Also, $database is undefined variable. It should be $dbname in place of $database in your context.




回答5:


var $hostname;
var $username;
var $password;
var $database;

public function dbconnect($hostname=DB_HOST, $username=DB_USER, $password=DB_PASS, $database=DB_NAME)
{
    $this->hostname  = $hostname;
    $this->username  = $username;
    $this->password  = $password;
    $this->database  = $database;
    $this->connect();

    $this->select_db();
}
public function connect()
{ 
$this->handler = mysql_pconnect($this->hostname, $this->username, $this->password) or $this->throw_error(mysql_error(), __LINE__);  
}
public function select_db()
{
   mysql_select_db($this->database, $this->handler) or $this->throw_error(mysql_error(), __LINE__);
}
public function DoSelect($query)
{

    $result = mysql_query($query);
    $grandvalue="";
    $RecordCounter=0;
    if(!mysql_error() && mysql_num_rows($result))
    {
        if(mysql_num_rows($result)>0)
        {
            // Make sure we get some rows back before we try to fetch them
            while ($row = mysql_fetch_array($result,MYSQL_NUM))
            {
                    $grandvalue[$RecordCounter]=$row;
                    $RecordCounter++;
            }
            return $grandvalue;
        }
        else
        {
          return null;
        }
    }

}
public function DoInsert($query)
{
    //echo $query;

    $this->dbconnect();

    $val=mysql_query($query);


   // echo $val;



}
public function DoUpdate($query)
{
   $this->dbconnect();

    $val=mysql_query($query);
   return $val;
}
public function DoDelete($query)
{
    $this->dbconnect();
    mysql_query($query);
}

}

$connection     =   new mysql_db();
$connection->dbconnect();
?>`enter code here`


来源:https://stackoverflow.com/questions/14718260/simple-php-database-connections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!