-3

I'm trying to make the registration page with PHP, but I'm new to this language and MySQL. So I've been following a tutorial about it. I followed everything correctly and checked multiple times. But I can't see the problem. config.php:

<<?php

$db_user = "root";
$db_pass = "";
$db_name = "useraccounts";

$db = new PDO('mysql:host=localhost;db_name=$db_name', $db_user, $db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

registration.php

<?php
    if (isset($_POST['create'])) {
        if ($_POST['password'] == $_POST['confirm-password']) {
            $username = $_POST['username'];
            $email = $_POST['email'];
            $password = $_POST['password'];

            $sql = "INSERT INTO users (username, email, password) VALUES(?,?,?)";
            $stmtinsert = $db->prepare($sql);
# line 30 \/ \/ \/ \/
            $result = $stmtinsert->execute([$username, $email, $password]);
            if ($result) {
                echo "yeeeet";
            } else {
                echo "nope";
            }
        }
    } else {

    }
    ?>

Error: Fatal error: Uncaught PDOException: SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected in C:\xampp\htdocs\Website\registration.php:30 Stack trace: #0 C:\xampp\htdocs\Website\registration.php(30): PDOStatement->execute(Array) #1 {main} thrown in C:\xampp\htdocs\Website\registration.php on line 30

jun2040
  • 37
  • 6
  • Please check whatever your PDO connection string contains, as in: dump it. There's a huge difference between single and double quotes ;) – Nico Haase Jan 31 '20 at 09:29

3 Answers3

1

You have not a proper string for dns use double quote for eval var in string (and not single quote)

$db = new PDO("mysql:host=localhost;db_name=$db_name", $db_user, $db_pass);
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
-1

if you pull php variable in single quotes php treat that as string for eg:

$dbName = 'mydb';
echo '$var';

above statement will output you $var not mydb. so you can try like this

$db = new PDO('mysql:host=localhost;db_name='. $db_name, $db_user, $db_pass);

or you can use double quotes like:

$db = new PDO("mysql:host=localhost;db_name=$db_name", $db_user, $db_pass);
udit rawat
  • 221
  • 1
  • 5
  • Nope, I don't think that's the source of the error. I just realized the error was from line 30 in registration.php file(Should have posted it in first place, sorry). I've posted the error. – jun2040 Jan 31 '20 at 11:52
-1

The source of the error is in your PDO $dsn string. You have to:

  1. Remove the underscore in db_name=
  2. Change single quotes to double quotes so the $db_name is recognized as variable

This should do the trick:

$db = new PDO("mysql:host=localhost;dbname=$db_name", $db_user, $db_pass);
vojtech
  • 24
  • 5