Created
April 24, 2015 13:16
-
-
Save itssalman/a50f9a3eff5ab5d30243 to your computer and use it in GitHub Desktop.
PHP: PDO
This file contains hidden or 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 | |
/** | |
* Created by PhpStorm. | |
* User: SALMAN ASLAM | |
* Date: 13-Jan-15 | |
* Time: 12:13 AM | |
*/ | |
// connect to database | |
try { | |
$pdo = new PDO('mysql:host=localhost; dbname=company;charset=utf8', 'root', 'salman'); | |
}catch (PDOException $ex){ | |
echo $ex->getMessage(); | |
} | |
/*SELECT DATA*/ | |
/* | |
// CREATE A QUERY | |
$statement = $pdo->query("SELECT * FROM employees"); | |
// set the fetch mood | |
$statement->setFetchMode(PDO::FETCH_OBJ); | |
?> | |
<h1>Employees</h1> | |
<table width="500px" cellpadding="5" cellspacing="5" border="1"> | |
<tr> | |
<th>ID#</th> | |
<th>First Name</th> | |
<th>Last Name</th> | |
<th>Department</th> | |
<th>Email</th> | |
</tr> | |
<?php while($row = $statement->fetch()): ?> | |
<tr> | |
<td><?php echo $row->id; ?></td> | |
<td><?php echo $row->first_name; ?></td> | |
<td><?php echo $row->last_name; ?></td> | |
<td><?php echo $row->department; ?></td> | |
<td><?php echo $row->email; ?></td> | |
</tr> | |
<?php endwhile;?> | |
</table> | |
*/ | |
// Insert data | |
/* | |
// dummy variables | |
$first_name = "M"; | |
$last_name = "Z"; | |
$dept = "CS"; | |
$email ="[email protected]"; | |
$stmnt = $pdo->prepare("INSERT INTO employees(first_name,last_name,department,email) | |
VALUES (:first_name,:last_name,:department,:email) | |
"); | |
// bind values | |
$stmnt->bindParam(':first_name',$first_name); | |
$stmnt->bindParam(':last_name',$last_name); | |
$stmnt->bindParam(':department',$dept); | |
$stmnt->bindParam(':email',$email); | |
// execute statement | |
$stmnt->execute(); | |
echo'Employee added :)'; | |
*/ | |
// update data | |
/* | |
// dummy variables | |
$id = 1; | |
$first_name = "Salu"; | |
$dept = "BSCS"; | |
$email ="[email protected]"; | |
$stmnt = $pdo->prepare("Update employees set first_name = :first_name , department = :department , email=:email WHERE id = :id"); | |
// bind values | |
$stmnt->bindParam(':first_name',$first_name); | |
$stmnt->bindParam(':department',$dept); | |
$stmnt->bindParam(':email',$email); | |
$stmnt->bindParam(':id',$id); | |
// execute statement | |
$stmnt->execute(); | |
echo'Employee record updated :)'; | |
*/ | |
// delete data | |
// dummy variables | |
$id = 9; | |
$stmnt = $pdo->prepare("DELETE FROM employees WHERE id = :id"); | |
// bind values | |
$stmnt->bindParam(':id',$id); | |
// execute statement | |
$stmnt->execute(); | |
echo'Employee deleted '; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment