2016-04-02 24 views
1

Veritabanına kayıt eklemek için basit bir formum var. Bu şuna benzer:Ayrı dosyadan işlev kullanılarak veritabanına bağlanma

Bu kod çalışır
<form action="" method="post"> 
<label>Student Name :</label> 
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br /> 
<label>Student Email :</label> 
<input type="email" name="stu_email" id="email" required="required" placeholder="[email protected]"/><br/><br /> 
<label>Student City :</label> 
<input type="text" name="stu_city" id="city" required="required" placeholder="Please Enter Your City"/><br/><br /> 
<input type="submit" value=" Submit " name="submit"/><br /> 
</form> 

<?php 
if(isset($_POST["submit"])){ 
$hostname='localhost'; 
$username='root'; 
$password=''; 

try { 
    $dbh = new PDO("mysql:host=$hostname;dbname=college",$username,$password); 

    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line 
    $sql = "INSERT INTO students (student_name, student_email, student_city) 
    VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."')"; 
    if ($dbh->query($sql)) { 
     echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>"; 
    } 
    else{ 
     echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>"; 
    } 

    $dbh = null; 
} 
catch(PDOException $e) 
{ 
    echo $e->getMessage(); 
} 

} 
?> 

i veritabanına bağlanmak ve bazı kayıtlar ekleyebilir.

<?php 

class Database { 

public function getConnection() { 
    $result = false; 
    try { 
     $result = new PDO('mysql:host=localhost;dbname=college', 'root', ''); 
    } catch(PDOException $e) { } 
    return $result; 
} 
} 
$db = new Database(); 
$conn = $db->getConnection(); 
if (!$conn) { 
die("Error connecting to the database"); 
} 

?> 

cevap

3

Sen veritabanı komut şunları içerebilir: Sorum yerine ilk kodundan bağlantının diğer dosyadan kod kullanarak veritabanına bağlanmak istiyorsanız ne, bu kodu değiştirmek zorunda olduğunu ve sonra yeni PDO nesnesini oluşturmak ve $dbh kullanarak tüm veritabanı işlemleri için $conn kullanın.

require_once('database.php'); 

try { 
    if ($conn->query($sql)) { 
     ... 
     ... 
    } 
} 
catch(PDOException $e) 
{ 
    echo $e->getMessage(); 
} 

Yan not: Sorgunuz SQL Injection'a karşı savunmasızdır. Değerleri SQL'de birleştirmek yerine Prepared Statement kullanın.

1

Veritabanı sınıfını sadece php gereksinim ifadesiyle birlikte kullanın.

<?php 
     // file: database.class.php 
     class Database { 
      ... 
     } 
    ?> 

Ve başka bir dosya

<?php 
     // file another_file.php 
     require('./your/path/to/Database.class.php'); 
     $db = new Database(); 
     $connection = $db->getConnection(); 
    ?> 
İlgili konular