1

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..

Pragnesh Chauhan
  • 8,175
  • 9
  • 41
  • 52
Bryan
  • 1,215
  • 4
  • 22
  • 34
  • What is the best way to subtract one number from another? – zerkms Nov 22 '12 at 06:50
  • so the best way to connect to mysql is to use `new mysqli()`. Does this count as an answer? – zerkms Nov 22 '12 at 06:54
  • 5
    @zerkms: no need to be condescending. He is unsure of the soundness of his object model and asks us for advice. I think this is a perfectly valid question. – Botond Balázs Nov 22 '12 at 06:54
  • 2
    `PDO` would technically be better, as it would not tie you to a single database's interface – Steven Moseley Nov 22 '12 at 06:56
  • 1
    If you're curious about design - rewrite question so it sounded about design. The first hint: you don't need static properties for the connection settings here. – zerkms Nov 22 '12 at 06:57
  • Yes. Storing the connection parameters in a config file would be better. – Botond Balázs Nov 22 '12 at 07:01
  • 1
    i can't confirm that using pdo makes an application more reusable. i don't know any application with good performance where you can switch the database interface without huge changes in the code. so using new mysqli() seems perfect. – iRaS Nov 22 '12 at 07:10
  • @iRaS: perfectly valid point. The DBAL API is the least evil thing in moving to another DBMS process. – zerkms Nov 22 '12 at 07:12
  • You should also consider using a singleton pattern (if you need only one connection). – Thomas Glaser Nov 22 '12 at 08:08

4 Answers4

3

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

Reza S
  • 8,954
  • 3
  • 52
  • 83
0

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';
RoadieRich
  • 5,983
  • 3
  • 37
  • 51
Arockiaraj
  • 253
  • 2
  • 4
  • 20
0

You can connect through data using PDO, here is an example

<?php
$servername = "localhost";
$username = "root";
$password = "nopass";

try {
    $conn = new PDO("mysql:host=$servername;dbname=wireframe", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully"; 

    $stmt = $conn->prepare("SELECT * FROM todolist"); 
    $stmt->execute();

    }
catch(PDOException $e)
    {
    echo "Connection failed: " . $e->getMessage();
    }
?>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<body>

<table border="1" align="center">
<tr>
  <th>name</th>
  <th>type</th>
  <th>status</th>
</tr>




<?php

foreach($stmt->fetchAll() as $k=>$v){
     echo
   "<tr>
    <td>{$v['name']}</td>
    <td>{$v['type']}</td>
    <td>{$v['status']}</td>
   </tr>\n";

}


?>
</table>
</body>
</html>
ANIK ISLAM SHOJIB
  • 2,652
  • 1
  • 25
  • 29
-4

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.