If you have error like "Trying to clone an uncloneable object of class..." when trying connect, add record
php_value zend.ze1_compatibility_mode 0
in your .htaccess file. This resolve connection problem.
mysqli_connect
mysqli()
(PHP 5)
mysqli_connect -- mysqli() — Abre uma nova conexão com o servidor MySQL
Descrição
Estilo de procedimento
Estilo orientado a objeto (construtor):
A função mysqli_connect() tenta abrir uma conexão com o servidor MySQL que esteja rodando em host o qual pode ser um nome de servidor ou um endereço IP. Passando NULL ou a string "localhost" para este parâmetro, é assumido o servidor local. Quando possível, serão usados pipes ao invés do protocolo TCP/IP. Se for bem sucedida, a função mysqli_connect() irá retornar um objeto representando a conexão com o banco de dados, ou FALSE em caso de falha.
Os parâmetros username e password especificam o nome de usuário e a senha para usar ao conectar com o servidor MySQL. Se a senha não for dada (é passado o valor NULL), the MySQL server will attempt to authenticate the user against those user records which have no password only. This allows one username to be used with different permissions (depending on if a password as provided or not).
Se for dao o parâmetro dbname , irá especificar o banco de dados padrão a ser usado ao se executar consultas.
Os parâmetros port e socket são usados em conjunto com o parâmetro host para maior controle de como conectar com o servidor de banc de dados. O parâmetro port especifica o número da porta a ser usada ao tentar conectar com o servidor MySQL, enquanto o parâmetro socket especifica um socket ou named pipe que deve ser usado.
Nota: especificar o parâmetro socket não irá determinar explicitamente o tipo de conexão a ser usada ao conectar com o servidor MySQL. Como a conexão é feita com o banco de dados MySQL é determinada pelo parâmetro host .
Valores de retorno
Retorna um objeto que representa a conexão com o servidor MySQL ou FALSE se a conexão falhar.
Exemplo
Exemplo #1 Estilo orientado a objeto
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf("Host information: %s\n", $mysqli->host_info);
/* close connection */
$mysqli->close();
?>
Exemplo #2 Estilo de procedimento
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf("Host information: %s\n", mysqli_get_host_info($link));
/* close connection */
mysqli_close($link);
?>
Os exemplos acimas devem produzir a seguinte saída:
Host information: Localhost via UNIX socket
mysqli_connect
25-Sep-2008 10:14
13-Sep-2008 01:03
There's a known bug using the OO $mysqli->connect_error, so don't pay attention to the example above until this bug is fixed ( http://bugs.php.net/bug.php?id=45940&edit=2 )
In the meantime, use the procedural style: mysqli_connect_error()
25-May-2008 01:10
The Object oriented style
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
?>
always returns a object which represents connection to a MYSQL,also connection faild , so the code below won't throw a Exception when connection faild:
<?php
try {
$db = new mysqli('localhost', 'userName', 'passWord', 'dbName');
if(!$db){
throw new Exception('connect databases faild!');
}
}
catch (Exception $e){
echo $e->getMessage();
}
?>
you must check connection with mysqli_connect_errno()
<?php
try {
$db = new mysqli('localhost', 'userName', 'passWord', 'dbName');
if(mysqli_connect_errno()){
throw new Exception('connect databases faild!');
}
}
catch (Exception $e){
echo $e->getMessage();
}
?>
28-Jan-2008 04:52
To specify charset in my.cnf file you just have to add
skip-character-set-client-handshake directive after
[mysqld]
default-character-set=utf8
30-Jul-2007 09:53
When you need more(less) timeout, you can use this. This only guarantees that host and port are opened. It is suitable on the very high speed networks(LAN) and where one second is not acceptable.
$timeoutInSeconds can be set to any numeric value
e.g. "1/2", "0.500","0.1","0.01" etc.
--------------------------------------------------------------
function getmicrotime()
{
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
$time_start = getmicrotime();
$fp = fsockopen("$mysqlHost",$mysqlPort, $errno, $errstr,$timeoutInSeconds);
if (!$fp)
{
//timeout mostly
echo "ERR: $errno - $errstr<br>\n";
$time_end = getmicrotime();
$time = $time_end - $time_start;
echo "Timeout $time sekund";
}
else
{
fclose($fp);
}
06-Jul-2007 06:29
This helped me:
<?php
$db = mysqli_connect($host, $login, $pass, $dbName);
$db->set_charset('utf8');
...
?>
17-Feb-2007 11:52
Yes, it's totally odd that php.ini doesn't seem to allow you to global specify the client connection as utf-8. You might try this in the
my.cnf file
[client]
default-character-set=utf8
[mysqld]
default-character-set=utf8
It didn't work for me, but others may have better luck. In the end I had to specify in the php code as noted below.
31-Jan-2007 11:13
A quick word about the connection encoding for this extension. It doesn't appear to be documented anywhere that I can find, but this defaults to latin1 encoding for the connection, regardless of PHP's or MySQL's settings. I run in a completely UTF-8 setup, and spent days trying to discover the cause of corrupted characters from the Db. If, like me, you need to work with other than latin1, use the set_charset function/method to switch to your encoding of choice.
