Jump to content

PHP Conn: Difference between revisions

From Drywall Wiki
Created page with "//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 =..."
 
No edit summary
Line 10: Line 10:
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
//set the PDO error mode to exception
//set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);


Line 16: Line 17:


//set the resulting array to  associative
//set the resulting array to  associative
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);


echo "<ul>";
echo "<ul>";
foreach ($result as $row)  {
foreach ($result as $row)  {
echo "<li>Roll No: " . $row["Roll_No"] . " - Name: " . $row["Name"] . " | City: " . $row["City"] . "</li>";
echo "<li>Roll No: " . $row["Roll_No"] . " - Name: " . $row["Name"] . " |  
        City: " . $row["City"] . "</li>";


}
}
echo "</ul>";
echo "</ul>";


} catch(PDOException $e)  {
    } catch(PDOException $e)  {
  echo "Error: " . $e->getMessage();
  echo "Error: " . $e->getMessage();
}
    }


$conn = null; // close connection
$conn = null; // close connection
?>
?>

Revision as of 14:21, 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 ?>