<?php
try {
// 예외가 발생할 수 있는 코드
throw new InvalidArgumentException('Invalid argument.');
} catch (InvalidArgumentException $e) {
// InvalidArgumentException을 처리하는 코드
echo 'Caught invalid argument exception: ', $e->getMessage(), "\n";
} catch (Exception $e) {
// 다른 모든 예외를 처리하는 코드
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
PDO 객체 사용법
<?php
$dsn = 'mysql:host=localhost;dbname=testdb'; // 데이터베이스 소스 네임
$username = 'root'; // 데이터베이스 사용자명
$password = ''; // 데이터베이스 비밀번호
try {
// PDO 객체 생성
$pdo = new PDO($dsn, $username, $password);
// 에러 모드를 예외 모드로 설정
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// SQL 쿼리 준비 및 실행
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(['id' => 1]);
// 결과 처리
$user = $stmt->fetch(PDO::FETCH_ASSOC);
print_r($user);
} catch (PDOException $e) {
// 예외 처리
echo 'Connection failed: ' . $e->getMessage();
}
?>
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 테이블에 데이터 삽입
$stmt = $conn->prepare("INSERT INTO 데이터베이스명 (number, count) VALUES (:number, :count)");
foreach ($data1 as $row) {
$stmt->bindParam(':number', $row['number']);
$stmt->bindParam(':count', $row['count']);
$stmt->execute();
}
// 업로드 저장 성공 후 리다이렉트
header("Location: main.php");
exit;
} catch(PDOException $e) {
echo "데이터베이스 오류: " . $e->getMessage();
}