Dino Geek, try to help you

How to connect MariaDB to PHP?


To connect your PHP application to a MariaDB database, you can use the mysqli or PDO extension that is included in new distributions of PHP. Here’s a sample code on how you can do that:

Method 1: Using mysqli extension.

```
$servername = “your_server”;
$username = “your_username”;
$password = “your_password”;
$dbname = “your_database”;

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

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

Method 2: Using PHP Data Objects (PDO).

```
$servername = “your_server”;
$username = “your_username”;
$password = “your_password”;
$dbname = “your_database”;

try { $conn = new PDO; // set the PDO error mode to exception $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo “Connected successfully”; }
catch(PDOException $e) { echo “Connection failed: “ . $e->getMessage(); }
?>
```

Remember to replace ‘your_server’, ‘your_username’, ‘your_password’, and ‘your_database’ with your actual server name, username, password, and database name respectively.

These scripts will make a connection to your MariaDB when they run. If the connection fails, it will exit the script and print a message telling you connection failure.

Don’t forget to close the connection at the end of your PHP script to free up system resources that your database server would otherwise hold onto.
```
// Close connection
$conn = null; //for PDO
mysqli_close($conn); //for MySQLi
```
It’s important to be aware of SQL Injection and other types of database attack, so always use prepared statements or PDO in production code.

Ensure the database user only has necessary permissions for operation, for example, if your app only needs to select data then the user only requires SELECT permissions.

Your host, username, password, and database name should not be hard-coded in your scripts, and should be stored in environment variables or in some form of configuration that is not accessible to the public.


Simply generate articles to optimize your SEO
Simply generate articles to optimize your SEO





DinoGeek offers simple articles on complex technologies

Would you like to be quoted in this article? It's very simple, contact us at dino@eiki.fr

CSS | NodeJS | DNS | DMARC | MAPI | NNTP | htaccess | PHP | HTTPS | Drupal | WEB3 | LLM | Wordpress | TLD | Domain name | IMAP | TCP | NFT | MariaDB | FTP | Zigbee | NMAP | SNMP | SEO | E-Mail | LXC | HTTP | MangoDB | SFTP | RAG | SSH | HTML | ChatGPT API | OSPF | JavaScript | Docker | OpenVZ | ChatGPT | VPS | ZIMBRA | SPF | UDP | Joomla | IPV6 | BGP | Django | Reactjs | DKIM | VMWare | RSYNC | Python | TFTP | Webdav | FAAS | Apache | IPV4 | LDAP | POP3 | SMTP

| Whispers of love (API) | Déclaration d'Amour |






Legal Notice / General Conditions of Use