Simple example of pdo connecting to database and inserting data implemented by PHP

  • 2021-12-05 05:45:45
  • OfStack

This article describes the PHP implementation of pdo connection database and insert data function. Share it for your reference, as follows:

Create a configuration file

pdo_config.php


<?php
$db_Type = "mysql";// Database type 
$host = "localhost";// Hostname 
$dbName = "test";// Database name 
$userName = "root";// User name 
$password = "root";// Password 
$dsn = "{$db_Type}:host={$host};dbname={$dbName}";
?>

pdo Insert Database

pdo_insert.php


<?php
header('Content-type:text/html; charset=utf-8');
require 'pdo_config.php';
try{
    $pdo = new PDO ($dsn,$userName,$password);// Create 1 Connection objects 
    $pdo->exec('set names utf8');// Set code 
    $sql = "INSERT student (name,email) VALUES (' Li 4','123@qq.com')";
    $pdo->exec($sql);
}catch (PDOException $e){
    die(' Operation failed '.$e->getMessage());
}
// Close the connection 
$pdo = null;
?>

For more readers interested in PHP related contents, please check the topics on this site: "Summary of PHP Database Operation Skills Based on pdo", "Summary of php+mysqli Database Programming Skills", "Introduction to php Object-Oriented Programming", "Summary of php String Usage (string)", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: