abolfazl ebrahimi
abolfazl ebrahimi

Reputation: 11

No connection to the database in pdo

I want the form information to be stored in the database, but I failed at this. I do not receive errors, but the information is not stored in the database.

Database connection:

<?php

define("DB_HOST",'localhost');
define('DB_USER',"root");
define("DB_PASS","");
define("DB_NAME","test2");

try {
    $conn = new PDO("mysql:host=".DB_HOST.";dbname".DB_NAME,DB_USER,DB_PASS );
    $conn->setAttribute(PDO::ATTR_ERRMODE ,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo $e->getMessage();
}

And insert into database:

<?php

require 'config.php';

if($_SERVER['REQUEST_METHOD'] == "POST") {
    if(isset($_POST['username']) && isset($_POST['password'])) {
        if(!empty($_POST["username"]) && !empty($_POST['password'])) {
            //echo $_POST['username'].$_POST['password'];

            $user=$_POST['username'];
            $pass=$_POST['password'];

            $sql = "INSERT INTO  userinfo (user ,pass) VALUES(:username , :password)";
            $conn = new PDO("mysql:host=".DB_HOST.";dbname".DB_NAME,DB_USER,DB_PASS );

            $query =$conn ->prepare($sql);
            $query->bindParam(':username',$user,PDO::PARAM_STR);
            $query->bindParam(':password',$pass,PDO::PARAM_STR);

            $query->execute();

        } else {
            echo"incorrect";
        }
    }
}

Upvotes: 1

Views: 309

Answers (1)

Schlotter
Schlotter

Reputation: 105

Remove the Database Connection from your config and try this code in your code:

<?php
require 'config.php';

if($_SERVER['REQUEST_METHOD'] == "POST") {
    if(isset($_POST['username']) && isset($_POST['password'])) {

        $user=$_POST['username'];
        $pass=$_POST['password'];

        $sql = "INSERT INTO userinfo (user, pass) VALUES($user, $pass);";
        
        try {
            $conn = new PDO("mysql:host=".DB_HOST.";dbname".DB_NAME,DB_USER,DB_PASS);
            $conn->setAttribute(PDO::ATTR_ERRMODE ,PDO::ERRMODE_EXCEPTION);
        } catch (PDOException $e) {
            echo $e->getMessage();
        }

        $query =$conn ->prepare($sql);

        $query->execute() ? print 'Success' : print 'Error';

    } else {
        echo"incorrect";
    }
}
?>

I tried on my Server and it worked for me, so it should work for you too.

Upvotes: 1

Related Questions