how to connect mysql to php code example

Example 1: php connect to mysql

$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";


Simplified

$conn = mysqli_connect('localhost', 'username', 'password');
$database = mysqli_select_db($conn, 'database');

Example 2: database connectivity in php

<?php
///////////neha jaiswal/////
/////set variable/////////
$serve="localhost";
$user="root";
$password="";
$db="cart_system";///database name
///create connection with db////
$conn=mysqli_connect($serve,$user,$password,$db);
////check condition for connection fail or not
 if ($conn) {
 echo "connection success"; 
 }else
{echo "connection unsuccess"; 
 }
  ?>

Example 3: how do you connect the database

I USE JDCB
I use CONNECTION database to make connection
I create STATEMENT than I use statement to create query 
And run the query and get the RESULT SET


Connection = import java.sql.Connection;
Driver manager = import java.sql.DriverManager;
Connection connection = DriverManager.getConnection(url, userName, passWord);

Connection String Syntax:
jdbc:DataBaseType"subprotocal:Host:port:SID

After succesfully created the connect next step is STATEMENT

import java.sql.Statement;
Statement statement = connection.createStatement();

-We use createStatement() method to create the statement from our connection.
-The result we get from this type of statement can only move from top to bottom,
not other way around

Once we have statement we can run the query and get the result to
ResultSet format 
		import java.sql.ResultSet;
        
We use the method executeQuery() to execute our queries

ResultSet result = statement.executeQuery("Select * from employees");

Example 4: php mysql connect

$host = 'localhost'; // URL to the server
$user = 'root'; // Username (xampp = root)
$pw = ''; // Password (xampp = )
$dbname = 'database'; // The name of your database 
$dsn = "mysql:host=$host;dbname=$dbname";
$options = [PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8']; // If you want to use utf-8 use this line

$db = new PDO($dsn, $user, $pw, $options); // Database Object
$db -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // Use this if you want an associate array
// $db -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); Use this if you want an indexed array

$qry = 'select * from table;'; // Your query
$result = $db -> query($qry); // execute query

while ($row = $result -> fetch()) {
    $id = $row[/*column-name*/];
}

Tags:

Sql Example