将数据插入数据库php

时间:2017-01-24 12:34:06

标签: php mysql

我正在创建一个网站,我想从表单(method =“post”)将数据插入到phpmyadmin表中它不起作用我已经连接到数据库但是当我在表单中键入内容时它没有插入表中,这是我的php部分:

<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
try {
    $conn = new PDO("mysql:host=$hostname;dbname=Database", $username, $password);
    echo 'Connected to database';
}
catch(PDOException $e)
{    
    echo $e->getMessage();
}
$nom = $_POST['nom'];
$prenom =$_POST['prenom'];
$email = $_POST['email'];
$password = $_POST['password'];
$type = $_POST['type'];
$sql = "INSERT INTO client (nom, prenom, email,password,type)
                    VALUES ($nom, $prenom, $email, $password , $type)"; 
}
$conn->connection = null;
?>

1 个答案:

答案 0 :(得分:1)

  

我不会评论太多,还有很多学习和   你需要做的练习。请慢慢来   这个博客,从中阅读和练习,不要急于花时间   https://phpdelusions.net/pdo

您的代码应该类似于下面的代码:

<?php
$hostname = 'localhost';
$username = 'root';
$password = '';
try {
    $conn = new PDO("mysql:host=$hostname;dbname=Database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

}
catch (PDOException $e) {

    echo $e->getMessage();

}


$nom      = $_POST['nom'];
$prenom   = $_POST['prenom'];
$email    = $_POST['email'];
$password = $_POST['password'];
$type     = $_POST['type'];


try {

    $sql = "INSERT INTO client (nom, prenom, email,password,type)   VALUES (?,?,?,?,?)";

    $stmt = $conn->prepare($sql);
    if ($stmt->execute(array(
        $nom,
        $prenom,
        $email,
        $password,
        $type
    ))) {

        echo "Data inserted";
    } else {

        echo "could not insert";
    }

}
catch (Exception $ex) {

    error_log($ex->getMessage());

}


?>