MySQL connect on PHP

2019-02-28 12:23发布

what is the best way to connect PHP application on MySQL.

So far I had the below connection classes.

class Connection{
    private static $server = "127.0.0.1";
    private static $catalog = "schemadb";
    private static $username = "rootuser";
    private static $password = "password";
    public static $current = null;

    public static function Open(){
        self::$current = mysqli_init();
        if(!self::$current){
            die("Failed to initialize connection");
        }
        if(!self::$current->real_connect(self::$server,self::$username,self::$password,self::$catalog)){
            die("Cannot connect to server");
        }
        return self::$current;
    }
    public static function Close(){
        self::$current->close();
    }
}

and also I have

abstract class abstractDAO
{
    protected function getConnection()
    {
        $mysqli = new mysqli("127.0.0.1","rootuser","password","schemadb");
        return $mysqli;
    }

}

or if there's any other best approach to connect PHP application on MySQL. Please advise thanks..

3条回答
你好瞎i
2楼-- · 2019-02-28 12:46

try this

<?php

  $user = $_POST["username"];//if this doesnt work try the next line
  $user = (isset($_POST["username"]) ? $_POST["username"] : "");

  $host = "localhost";//mysql password
  $username = "";//mysql username
  $password = "";//mysql password
  $db_name = "database";//database name
  $tbl_name ="test";//table name
  //make the connection
  $con = mysql_connect("$host","username","password")or die("Could not connect.");
  $conn = mysql_select_db("$db_name")or die("Could not select database.");

  $sql = "SELECT * FROM $tbl_name WHERE username='$username'";
  //query mysql
  $result = mysql_query($sql);

  if($result){
  //if it works show this

  }else{

  //if it doesnt work show this

  }

?>

ive tryed a lot of times to make a connection to a database and i finaly found one.

查看更多
Melony?
3楼-- · 2019-02-28 12:50

You can try using the PDO object:

<?php
try {
    $dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

Have a look at PHP PDO documentation page

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-02-28 12:54

Try to use php frameworks like codeigniter, Yii, cake php. If you implement in any one of this framework no need to write php mysql query It will automatically generate. You just need to enter your database configuration like give in below

$db['default']['hostname'] = 'localhost';
$db['default']['username'] = 'root';
$db['default']['password'] = '';
$db['default']['database'] = 'sample';
查看更多
登录 后发表回答