Jump to content

Recommended Posts

Why do I get this error message?
This is the error message i get:

ERRORUndefined function 'pdoConnect'.

 

include $ROOT.'db_inc.php';

 

 

<?php
$pdo = pdoConnect();

 

define("HOST",'*****');         // Database host.

define("USERNAME",'*****');     // Database username .

define("PASSWORD",'*****');              // Database password.

define("DATABASE", '*****');    // Database name.

 

function pdoConnect($dbname=DATABASE)

{
?>

    $db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD);

    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

    return $db;

}

Link to comment
https://forums.phpfreaks.com/topic/314989-pdo-error-undefined-function-pdoconnect/
Share on other sites

the posted code contains a php syntax error (a closing ?> tag inside the function definition) and doesn't run at all, so that's not the actual code producing that error.

a few possibilities why the function definition is not present in the current program scope -

  1. the function definition is inside of a conditional statement, and so isn't defined until the code where that statements is at has been executed and the conditional statement is true.
  2. the function definition is inside of another function definition, and so isn't defined until the parent function has been called.
  3. the function definition is being required (you should use require for things your program just have) using a url, not a file system path, and is not in the same instance of your program as the function call.

after you correct the php syntax error, the posted code produces an undefined constant error because the function call is before the point where the constants are defined.

it would take seeing the actual code producing the error to help with what is wrong with it.

  • Thanks 1
2 hours ago, mac_gyver said:

the posted code contains a php syntax error.......

 

Thanks, mac_gyver. My head feels like a stone now. I have only slept 3 hours in 36-37 hours. I will look through the script for the error. I need to fix it myself so I can learn it. If I can't find it I will come back. But, till then I will try to fix it my self. I just need a kick in the right direction, thanks.

(The reason why i was so sure the error was in the PDO part is because MS VSC told me so.)

I get the same error on more of the files in the system. It says:

Undefined function 'pdoConnect'.

I have to start flipping backward to find the error. Because it must be connected to pdoConnect? The error message tell me so what ever file i try to open. It is so strange that it (pdoConnection) is retrieved from a separate file by the name "db_inc.php". That's the one I posted for you. No, I have to start scrolling back and forth  by file to find the error.

4 hours ago, mac_gyver said:

the posted code contains a php syntax error (a closing ?> tag inside the function definition) and doesn't run at all, so that's not the actual code producing that error.

a few possibilities why the function definition is not present in the current program scope -

45 minutes ago, Barand said:

Reminded me of what mc_gyver told me


You are both so right. It was not this one. It turned out that this was one I had put on when I pasted it here on PHP Freaks. I just have to scroll back file by file and line by line to find the error. Because the error is deeper in the system than the "db_inc.php" file itself. I guess... no, I am sure I will come back with idiotic questions that are self-explanatory, but this is how it is when you do not have enough sense in your head to give up troubleshooting when you have looked blindly at error after error, are tired and tired, and do not really understand anyone thing. it's good to have men like you here at PHP Freaks.

3 hours ago, LeonLatex said:

MS VSC told me so

relying on a Microsoft product as a programming aid is foolish. if you are not posting actual errors that you got from PHP on your localhost web server when you tried to run your code, you are wasting yours and our time.

1 hour ago, LeonLatex said:

It turned out that this was one I had put on when I pasted it here on PHP Freaks

if you are not posting, copy/pasting, your actual code, you are wasting our time as well.

VSC reporting that the function is not defined is because VSC is not smart enough to know that the function can be defined in a separate file or if the code you posted at the top of this thread is an accurate arrangement of code in a single file (doubtful now), that you can define a function anywhere in a php project with respect to where it is called, provided it's not conditionally defined or conditionally required/included (the first two cases I posted.)

You have been side-tracked by VSC's reporting of a problem that doesn't actually exist. You are going to have to actually learn the fundamentals of php programming so that you are smarter then the Microsoft tool you are trying to use.

15 minutes ago, mac_gyver said:

relying on a Microsoft product as a programming aid is foolish. if you are not posting actual errors that you got from PHP on your localhost web server when you tried to run your code, you are wasting yours and our time.

if you are not posting, copy/pasting, your actual code, you are wasting our time as well.

I can agree with that in certain situations, but now I have been so stupid that I relied to much on my self, on ther self-proclaimed specialists here at PHP freaks say VSC was recommended to use. I have used it before, but that is wery long time and many years ago. I know it can be silly to rely too much on it since there are a lot of strange things to do, but when you are desperate to find the mistakes it is easy to fall into the same trap that I can also warn against, and that is to rely too much on what is said in a forum. THEN YOU ARE AGAIN WITH AS MANY DIFFERENT ANSWERS AS THERE ARE PERSONS WITH AN INTERNET SUBSCRIPTION. But one eventually learns to trust the right ones. You quickly find out who are the best. I do not need to mention names, but you are one of those I feel is in that category along with someone else in here.

18 minutes ago, mac_gyver said:

relying on a Microsoft product as a programming aid is foolish. if you are not posting actual errors that you got from PHP on your localhost web server when you tried to run your code, you are wasting yours and our time.

if you are not posting, copy/pasting, your actual code, you are wasting our time as well.

 

10 minutes ago, ginerjm said:

Nine hours (and counting) and the OP hasn't been able to remove one (hopefully) errant php tag?

It was a little silly to put in the ?> after pasting the code. That was because I thought I missed it. So before checking, I pasted it and posted my posting. Sorry, I don't want to waste your time guys.
But sometimes (in desperation) we act stupid before we think. We are just humans... So I am deeply very sorry if you have the feeling that I am wasting your time. It was not my intention 😞 I really appreciate your help , from all of you.

2 minutes ago, ginerjm said:

So is it working now?  And if not, be sure to post the code for us to work with.

No, it does not. I try to find the errors myself as well. I care about three files now. If I find the errors in the three files then I have solved the problem in all the others as well. I will make sure to get pasted the correct versions. I have ADHD so I can not promise that it always happens right after the book, but I will try my best so I do not correct what I have already pasted. (😂 that's so stupid).

You misunderstand me a little. I am doing that. I am concentrating on the PDO error in the db_inc.php file. I haven't eaten in 18 - 20 hours because I had to deliver two the design mission, but after that, I will paste the correct ones. Or... I can wait to eat 🙂

This is the db_inc.php file:

define("HOST",'*****');
define("USERNAME",'*****');
define("PASSWORD",'*****');
define("DATABASE", '*****');

function pdoConnect($dbname=DATABASE)
{
    $db = new PDO("mysql:host=".HOST.";dbname=$dbname;charset=utf8",USERNAME,PASSWORD);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    return $db;
}

This is the login.php file:

<?php
session_start();
$ROOT = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) . '/';
$HOST = 'http://' . $_SERVER['HTTP_HOST'] . '/';

include $ROOT.'db_inc.php';
$pdo = pdoConnect();

$loggedin =  $_SESSION['member_id'] ?? 0;

unset( $_SESSION['member_id'], $_SESSION['isadmin']);

if ($loggedin)  {
    header("Location: {$HOST}marina.php");
    exit;
}

$msg = '';

if ($_SERVER['REQUEST_METHOD']=='POST') {
    $res = $pdo->prepare("SELECT password
                               , member_id
                               , admin
                          FROM member
                          WHERE email = ?     
                         ");
    $res->execute([ $_POST['email'] ]);
    $row = $res->fetch();
    if ($row && password_verify($_POST['password'], $row['password'])) {
        $_SESSION['member_id'] = $row['member_id'];
        if ($row['admin'] == 1) {
            $_SESSION['isadmin'] = 1;
        }
        header("Location: {$HOST}index.php");
        exit;
    }
    else $msg = "<div class='w3-panel w3-red w3-padding'><p>Ugyldig innlogging</p></div>";                     
}
?>
<!DOCTYPE html>
<html lang='no'>
<head>
<title>Brandbu SmåbåtForening båtplasser</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css">
<link href='css/footer.css' rel='stylesheet' type="text/css">
</head>
<body>
    <div class='w3-content w3-card-4 w3-light-gray' style='margin-top: 100px;'>
        <div class='w3-panel w3-black w3-padding'>
            Marina Management System - Logg Inn
        </div>
        <?=$msg?>
        <form method='POST' class='w3-padding'>
            <label>E-mail</label>
            <input type='text' class='w3-input w3-border' name='email'>
            <label>Password</label>
            <input type='password' class='w3-input w3-border' name='password'>
            <br>
            <button type='submit' class='w3-button w3-blue w3-right'>Logg Inn</button>
            <br><br><br>
        </form>
    </div>
</body>
</html>

This is the header.php file:

<?php
$disabl1 = isset($_SESSION['member_id']) ? '' : 'w3-disabled'; 
$disabl2 = isset($_SESSION['member_id']) && isset($_SESSION['isadmin']) ? '' : 'w3-disabled';  
$log_btn = isset($_SESSION['member_id']) ?  'Logg ut' : 'Logg inn'; 
?>
<?php
session_start();
$ROOT = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) . '/';
$HOST = 'http://' . $_SERVER['HTTP_HOST'] . '/';

include $ROOT.'db_inc.php';
$pdo = pdoConnect();

$loggedin =  $_SESSION['member_id'] ?? 0;

unset( $_SESSION['member_id'], $_SESSION['isadmin']);

if ($loggedin)  {
    header("Location: {$HOST}index.php");
    exit;
}

$msg = '';

if ($_SERVER['REQUEST_METHOD']=='POST') {
    $res = $pdo->prepare("SELECT password
                               , member_id
                               , admin
                          FROM member
                          WHERE email = ?     
                         ");
    $res->execute([ $_POST['email'] ]);
    $row = $res->fetch();
    if ($row && password_verify($_POST['password'], $row['password'])) {
        $_SESSION['member_id'] = $row['member_id'];
        if ($row['admin'] == 1) {
            $_SESSION['isadmin'] = 1;
        }
        header("Location: {$HOST}members.php");
        exit;
    }
    else $msg = "<div class='w3-panel w3-red w3-padding'><p>Error: Kunne ikke logge inn!</p></div>";                     
}
?>
<!DOCTYPE html>
<html lang='no'>
<head>
<title>Nikolivia Marina Management System&trade;</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<link rel='stylesheet' href='https://www.w3schools.com/w3css/4/w3.css'>
<link rel='stylesheet' href='css/main.css'>
<link rel='stylesheet' href='css/footer.css'>
<style>


/* Create four equal columns that floats next to each other */
.column {
  float: left;
  width: 25%;
  padding: 10px;
}

/* Clear floats after the columns */
.row:after {
  content: "";
  display: table;
  clear: both;
}

/* Responsive layout - makes a two column-layout instead of four columns */
@media screen and (max-width: 900px) {
  .column  {
    width: 50%;
  }
}

/* Responsive layout - makes the two columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) {
  .column  {
    width: 100%;
  }
}
</style>
	
</head>
<body>
<header class='w3-container'>
<div class="w3-center" style="font-size: 15pt;"><!--<?=PAGETITLE?>--></form></div>
<div class="w3-left" style="display: inline-block; padding-top: 16px; font-size: 18pt;"></div>
    <div style="display: inline-block; padding-top: 16px; font-size: 14pt; margin-right: 10px;" class="w3-right"></div>
	<div>
	<div>
	</div></div></div></div>
</header>

	<div class="w3-bar w3-blue-gray w3-margin-bottom w3-padding">
	<a id="nav-home" href="<?=$HOST?>index.php"class="w3-bar-item w3-button">Ta meg hjem</a>
	<a id="nav-register"href="<?=$HOST?>register.php" class="w3-bar-item w3-button">Registrering</a>
	<a id="nav-marina" href="<?=$HOST?>marina.php" class="w3-bar-item w3-button">Båtplass</a>
	<a id="nav-members" href="<?=$HOST?>members.php" class="w3-bar-item w3-button <?=$disabl1?>">Medlemmer</a>
	<a id="nav-panel" href="<?=$HOST?>invoice/invoice.php" class="w3-bar-item w3-button <?=$disabl2?>">Faktura</a
	</div>
<a id="nav-login" href="<?=$HOST?>login.php" class="w3-bar-item w3-button w3-right"><?=$log_btn?></a>
</div>

 

Edited by LeonLatex

Does your PDO class work properly?  Why do you have a class for creating a db connection? You are not using any classes when you do a prepare or an execute or fetch so why the class just to make the connection?

Edited by ginerjm

Actually I just had a look at my code and I do use an OO connection.  But no more OO when I use it.  I am a procedural guyy.

Ok  so does your dbinc.php code work in other scripts without errors?  If so we can ignore it in this topice

Edited by ginerjm
37 minutes ago, ginerjm said:

Does your PDO class work properly?  Why do you have a class for creating a db connection? You are not using any classes when you do a prepare or an execute or fetch so why the class just to make the connection?

Eaten and full... 🙂
I tried to check if the class was following over to another site. So i used the login form to log in, but i get the same error there. OR i can log in, so the connection must be working, but.. There was something. Then i tried to use the registration form to see if it was held open, but error there as well.
Is not what has been created as a class something you save on and save for reuse later. Then the class in this connection is probably a DB connection. In this regard, to keep the DB connection open, or am I completely wrong? This is what I have read and Barand is probably the one who made me read about this if I remember correctly, but it must be 1.5 years ago (if i dont remember totaly wrong, but it was among that time we talked together, and you made me the marina script. I guess you have allready deen that this is a part of that system. Unfornatley i have destroyed that script totaly. I am trying to fix so i can reuse parts of it to another project. So i want to use re.

I think it's better to use this from you ginerjm:
 

error_reporting(E_ALL);
ini_set('display_errors', '1');

I will post the screen dumps.

Are you saying that you pdo connection is WORKING or it is NOT working?  Please be sure. 

 

Show us JUST the code that you are running  for your last post.  Nothing else.  I don't want stuff that doesn't matter.  And we really don't need all the html if it can be avoided.  AND the error message and point us to the line that gives that message

Edited by ginerjm

This is some of your code which seems to work for me except I did not do a DB connection.

session_start();
$ROOT = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) . '/';
$HOST = 'http://' . $_SERVER['HTTP_HOST'] . '/';

// COMMENTED OUT FOR THIS TEST
//include $ROOT.'db_inc.php';
//$pdo = pdoConnect();

$loggedin =  $_SESSION['member_id'] ?? 0;

unset( $_SESSION['member_id'], $_SESSION['isadmin']);

if ($loggedin)
{
	header("Location: {$HOST}marina.php");
	exit;
}
$msg = '';
if ($_SERVER['REQUEST_METHOD']=='POST')
{
	$res = $pdo->prepare("SELECT password
		, member_id
		, admin
		FROM member
		WHERE email = ?
		");
	$res->execute([ $_POST['email'] ]);
	$row = $res->fetch();
	if ($row && password_verify($_POST['password'], $row['password']))
	{
		$_SESSION['member_id'] = $row['member_id'];
		if ($row['admin'] == 1)
		$_SESSION['isadmin'] = 1;
		header("Location: {$HOST}index.php");
		exit;
	}
	else
		$msg = "<div class='w3-panel w3-red w3-padding'><p>Ugyldig innlogging</p></div>";
}
?>
<!DOCTYPE html>
<html lang='no'>
<head>
<title>Brandbu SmåbåtForening båtplasser</title>
<meta http-equiv='Content-Type' content='text/html; charset=utf-8'>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.1/css/all.css">
<link href='css/footer.css' rel='stylesheet' type="text/css">
</head>
<body>
<div class='w3-content w3-card-4 w3-light-gray' style='margin-top: 100px;'>
<div class='w3-panel w3-black w3-padding'>
Marina Management System - Logg Inn
</div>
<?=$msg?>
<form method='POST' class='w3-padding'>
<label>E-mail</label>
<input type='text' class='w3-input w3-border' name='email'>
<label>Password</label>
<input type='password' class='w3-input w3-border' name='password'>
<br>
<button type='submit' class='w3-button w3-blue w3-right'>Logg Inn</button>
<br><br><br>
</form>
</div>
</body>
</html>
<?php
exit();

So we can eliminate this code from any error solving?

1 hour ago, ginerjm said:

Show us JUST the code that you are running  for your last post.  Nothing else.  I don't want stuff that doesn't matter.  And we really don't need all the html if it can be avoided.  AND the error message and point us to the line that gives that message

 

I am now opening each file as a single file with "error_reporting(E_ALL); ini_set('display_errors', '1');" in the top of each file.

db_inc.php No ERROR.

login.php No ERROR when entering the file, but when i try to login with password and username i get this ERROR (image 1 and 2):
header.php Se image 3


 

 

 

 

 

 

 

1.png

2.png

3.png

Edited by LeonLatex

Since you haven't posted anything here is something that works for me:

//include $ROOT.'db_inc.php';
//************************************
//  TRY THIS FUNCTION FOR DB_INC.PHP
function pdoConnect($dbname=null)
{
	$username = '****';
	$password = '****';
	if ($dbname == null)
		$host="mysql:host=localhost;charset=utf8";
	else
		$host="mysql:host=localhost;dbname=$dbname;charset=utf8";
	try
	{
		$db = new PDO($host, $username, $password);
	}
	catch (PDOException $e)
	{
		echo "Fatal Error<br>Failed to connect to mysql via PDO.  PDO Error msg is:<br>".$e->getMessage();
		return false;
	}
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
	$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
	return $db;
}
//************************************

Not used to using constants so wasn't sure if you had a problem there or not.  No need for them anyway.  Just set the vars inside the function and leave them alone.  Ran this code against my own db and it worked fine.  And this code added to the code I sent before it also worked just fine.

1 hour ago, ginerjm said:

Are you saying that you pdo connection is WORKING or it is NOT working?  Please be sure. 

 

Show us JUST the code that you are running  for your last post.  Nothing else.  I don't want stuff that doesn't matter.  And we really don't need all the html if it can be avoided.  AND the error message and point us to the line that gives that message

 

NO ERROR when entering the file directly in the browser.

Edited by LeonLatex
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.