“Connectez PHP à DB” Réponses codées

Comment se connecter à une base de données dans PHP

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

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
AlikeIATS

Connexion de la base de données dans PHP

<?php

$hostName = 'localhost';
$userNmame = 'root';
$password = '';
$dbname = 'topproduct';
$db_name = "mysql:host=$hostName;dbname=$dbname";
$conn = new PDO($db_name,$userNmame,$password);

if(!$conn){
    echo 'Error database connection';    
}
Homely Hamerkop

Connectez PHP à DB

This is an update to a note I wrote earlier concerning how to set multiple attributes when you create you PDO connection string.

You can put all the attributes you want in an associative array and pass that array as the fourth parameter in your connection string. So it goes like this:
<?php
$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_CASE => PDO::CASE_NATURAL,
    PDO::ATTR_ORACLE_NULLS => PDO::NULL_EMPTY_STRING
];

// Now you create your connection string
try {
    // Then pass the options as the last parameter in the connection string
    $connection = new PDO("mysql:host=$host; dbname=$dbname", $user, $password, $options);

    // That's how you can set multiple attributes
} catch(PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}
?>
Mushy Macaque

Réponses similaires à “Connectez PHP à DB”

Questions similaires à “Connectez PHP à DB”

Plus de réponses similaires à “Connectez PHP à DB” dans PHP

Parcourir les réponses de code populaires par langue

Parcourir d'autres langages de code