Jump to content

PHP Conn: Difference between revisions

From Drywall Wiki
No edit summary
No edit summary
 
Line 4: Line 4:
$servername = "localhost"; // Server Name                               
$servername = "localhost"; // Server Name                               
$username = "root"; //mysql username
$username = "root"; //mysql username
$password = "password";  //Database Password                                          
$password = "password";  //Database Password                                          
$dbname = "dbname";  //Database Name
$dbname = "dbname";  //Database Name



Latest revision as of 14:22, 7 January 2026

//PHP PDO Connection to MySQL

<$php $servername = "localhost"; // Server Name $username = "root"; //mysql username $password = "password"; //Database Password $dbname = "dbname"; //Database Name

try { $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); //set the PDO error mode to exception

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $conn->prepare("SELECT Roll_No, Name, City FROM 'Student Details'"); $stmt->execute();

//set the resulting array to associative

   $result = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo "

    "; foreach ($result as $row) { echo "
  • Roll No: " . $row["Roll_No"] . " - Name: " . $row["Name"] . " | City: " . $row["City"] . "
  • "; } echo "

";

   } catch(PDOException $e)  {

echo "Error: " . $e->getMessage();

   }

$conn = null; // close connection ?>