Inserting & Fetching Database
try
{
$conn = new PDO ( "mysql:host=localhost; dbname=pdo" , "root", "");
$conn -> setAttribute (PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//-- echo "Connected Successfully";
}
catch (PDOException $e)
{
echo "Connection Failed...". $e -> getMessage();
}
if (isset($_POST['submit']))
{
$name = $_POST['name'];
$class = $_POST['class'];
$address = $_POST['address'];
$city = $_POST['city'];
if(!empty($name) || !empty($class) || !empty($address) || !empty($city))
{
$query = $conn -> prepare ("insert into studentlist (name, class, address, city) values ('$name', '$class', '$address', '$city')");
if (!$query -> execute())
{
echo "Fail";
}
else
{
echo "Passed";
}
}
else{echo "All Fields are Mendatory...";}
}// ------- if isset
Connection Failed...SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)
Fetching Database
try
{
$query = $conn -> prepare("select * from studentlist");
$query->execute();
$students = $query -> fetchAll();
$i = 1;
foreach ($students as $key)
{
echo"".$i++." | ".$key['name']." | ".$key['class']." | ".$key['address']." | ".$key['city']." |
";
}
}
catch (PDOException $e)
{
echo "Error ... ". $e->getMessage();
}
$conn = null;
S. No. | Name | Class | Address | City |