D
D
Danil Buzoverya2020-04-25 09:59:23
PHP
Danil Buzoverya, 2020-04-25 09:59:23

Error Undefined variable: dbh and Undefined variable: dbh Call to a member function prepare() on null?

I decided to write a small private api, but it didn’t work out with the database right away, I set everything up fine, but the server writes two errors when running this script:

Undefined variable: dbh
Call to a member function prepare() on null

I tried everything I know , but it always gives these two errors.

The code:

<?php

// MySQL Config
$host = "localhost";
$dbname = "api";
$user = "root";
$pass = "password";
$dbh = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);


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

  function keyRegister($token) {

    $sth = $dbh->prepare("SELECT * FROM api WHERE token = ?");
    $sth->execute(array($token));
    $tokenbd = $sth->fetchAll();

    if ($token == $tokenbd) {
        echo(json_encode(array('response' => 1)));
    }
  }
}

keyRegister('ThisIsTestKey');

?>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2020-04-25
@DeezYT

Inside the function has its own scope . The $dbh variable does not exist in this scope.

F
FanatPHP, 2020-04-25
@FanatPHP

The whole problem is that you write code for no reason. Example: why do you need a function here? For beauty?
The function code itself is also written without the slightest understanding .
if ($token == $tokenbd) {
What are you comparing to what here? And why? What does the fetchAll() function return? What result do you expect from this comparison? What for in general to compare if you already in request compared?
Here you go, in order of charity
pdo.php

<?php

// MySQL Config
$host = "localhost";
$dbname = "api";
$user = "root";
$pass = "password";
$charset = "utf8mb4"; // кодировку за тебя кто задавать будет? Максим Галкин?

$dbh = new PDO("mysql:host=$host;dbname=$dbname;charset=$charset", $user, $pass);
// про ошибки кто будет сообщать? Доктор комаровский?
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

the file itself
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    require 'pdo.php';
    $sth = $dbh->prepare("SELECT 1 FROM api WHERE token = ?");
    $sth->execute(array($token));
    $tokenOK = $sth->fetchColumn();

    if ($tokenOK) {
        echo(json_encode(array('response' => 1)));
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question