Last active
September 1, 2016 18:53
-
-
Save arsho/60a7a9180c9f7a7d5fe1710b6d541962 to your computer and use it in GitHub Desktop.
Insert and Select operation using PDO
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$server_name = 'localhost'; | |
$db_username = 'DB_USERNAME'; | |
$db_password = 'DB_PASSWORD'; | |
$db_name = 'DB_NAME'; | |
try{ | |
$conn = new PDO("mysql:host=$server_name;dbname=$db_name",$db_username,$db_password); | |
$conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$username = 'newuser2'; | |
$blog_text = 'blog text of newuser2'; | |
$sql_query = "INSERT INTO users(`username`,`blog_text`) VALUES ( :username, :blog_text )"; | |
$stmt = $conn -> prepare($sql_query); | |
$stmt -> bindParam(':username',$username); | |
$stmt -> bindParam(':blog_text',$blog_text); | |
$stmt -> execute(); | |
$sql_query = "SELECT * FROM users"; | |
$stmt = $conn -> prepare($sql_query); | |
$stmt -> execute(); | |
$res = $stmt -> fetchAll(PDO::FETCH_ASSOC); | |
foreach($res as $row){ | |
echo $row['username'].'-->'.$row['blog_text']."<br>"; | |
} | |
} | |
catch(Exception $e){ | |
echo 'Exception: '.$e->getMessage().'<br>'; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment