0

i'm new to php and coding in general. For a school project where i'm creating a website, i need to create a login page who's making the link with my batabase in mysql. So, i make a function connect to my database and i made an other function for inssert data on my sql. But, it dosen't work when i make it this why. But when i call my function connect on my function inssert, it doesn't work. Why ? I want to understand. Thank you by advanced.

This is my code :

function connect_db($host,$port,$dbname,$username,$passwd) {

        try {
            $bdd = new PDO('mysql:host=localhost;port=3306;dbname=my_shop', 'newuser', '0504');
            //$dbh = null;
        } 
        catch (PDOException $e) {
            print "Erreur !: " . $e->getMessage() . "<br/>";
            die();
        }
}

    if ($_SERVER["REQUEST_METHOD"] == "POST") {

connect_db ($host,$port,$dbname,$username,$passwd)

        $username = $_POST['username'];
        $password = $_POST['password1'];
        $email = $_POST['email'];

        $request= $bdd->prepare('INSERT INTO users (username,password,email) VALUES("'.$username.'","'.$password.'","'.$email.'")');
        $request->execute();
        print_r($request);
    }
aynber
  • 22,380
  • 8
  • 50
  • 63
  • You are wide open for SQL injection. Since you're using PDO, take advantage of [prepared statements](https://secure.php.net/manual/en/pdo.prepared-statements.php) and [bindParam](http://php.net/manual/en/pdostatement.bindparam.php) or [bindValue](http://php.net/manual/en/pdostatement.bindvalue.php). **This will take care of any pesky quoting issues that may occur.** – aynber Jun 30 '21 at 13:11
  • `$bdd` does not exist outside of the function. Return it from the function, and assign it when you call the function. – aynber Jun 30 '21 at 13:12
  • 1
    also $bdd is out of scope when you try to use it lower down your script - if only exists inside the connect_db function. You'd need to return it from the function and then use it. TBH it would appear your core knowledge and experience is not at the level yet where you could realisticlally expect to build a reliable, secure login system - it's not a trivial topic - too easy to screw things up - and not really one for beginners. Use an existing authentication module and focus your efforts instead on learning some more fundamentals of the language and adding simpler features to your site. – ADyson Jun 30 '21 at 13:13
  • Thank you, i will make changes and i know i don't have level for this, but no choice. I think you all for your answer that will improve my skills. – dumas gwladys Jun 30 '21 at 15:05

0 Answers0