The direct connection in mysqli I do so ...
$mysqli = new mysqli("localhost", "usuario", "senha", "bancodedados");
if ($mysqli->connect_errno) {
echo "Falha ao conectar com o mysql: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
echo $mysqli->host_info . "\n";
If you need to send the connection port, it would look like this ...
$mysqli = new mysqli("localhost", "usuario", "senha", "bancodedados", 3306);
If you want to work object oriented uses the PDO guy, I believe it will help you a lot more, and it is much easier to work object oriented with it ...
Below the class I have here that makes this connection, and an example of another file using this connection ...
<?php
class Conexao {
public $conn;
function Conexao() {
$string = "mysql:";
$string .= "host=localhost ";
$string .= "port=5432 ";
$string .= "dbname=nomedobanco";
$string .= "user=usuario";
$string .= "password=senha";
try {
$this->conn = new PDO($string);
}catch(PDOException $e){
echo $e->getMessage();
}
}
}
?>
If you do not want to use the new PDO with the variable $ string you can use it as well ...
new PDO('mysql:host=localhost;dbname=testdb;charset=utf8mb4', 'username', 'password');
If you want a hint, create a file "class.conexao.php" with this code and in "class.suaclasse.php", you use, as in the example below ...
<?php
require('class.conexao.php');
class Querys extends Conexao {
function validaLogin($login, $senha) {
$sql =
"
select nome, cpf from validaUsuario('".$login."', '".$senha."');
";
$stmt = $this->conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
}
}
This function in the case validates login, then you can create for what you need ...
this part
$stmt = $this->conn->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
is to prepare the query that you are going to execute, and then execute and return the associated results ....
You would use the return in this way ..
<?php
require_once('class.querys.php');
class Login extends Querys {
function validarLogin() {
$query = new Querys();
$retorno = $query->validaLogin(aqui vem os parametros));
return $retorno;
}
}
?>
In this way, you are working on object-oriented.