Jump to content

PDO error - Undefined function 'pdoConnect'.


LeonLatex

Recommended Posts

24 minutes ago, ginerjm said:

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.

 

NO ERROR!

Link to comment
Share on other sites

And I have no errors when I run what I have just given you.  Here is the combined code:

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;
}
//************************************
$mydbname = '****';
if(!$pdo = pdoConnect($mydbname))
{
	echo "Could not make db connection to database: $mydbname";
	exit();
}
$ROOT = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']) . '/';
$HOST = 'http://' . $_SERVER['HTTP_HOST'] . '/';

$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();


//****
//			***********************************
//			************************************
//****
function DisplayPage()
{
	global $errmsg;
	$code=<<<heredocs
	<!DOCTYPE html>
	<html lang='en'>
    <head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
	<meta name="viewport" content="width=device-width,initial-scale=1">
	</head>
	<body>
heredocs;
	echo $code;
	//**********************
	$myrow['cats'] = "D\"Reilly";
	echo "<div style='margin:2%;border:2px solid black;padding:5px;width:30%;'>".PHP_EOL;
	echo "<span style='color:red;'>$errmsg</span>".PHP_EOL;
	echo "<br><br>".PHP_EOL;
	echo "<form method='POST'>".PHP_EOL;
	echo "<label>Choose from the below list:</label>".PHP_EOL;
	echo "<br>&nbsp;&nbsp;&nbsp;".PHP_EOL;
	echo "<select size='2' style='width:130px;' name='dropdown'>".PHP_EOL;
	echo "<option value='0'>Pick one</option>".PHP_EOL;
	echo "<option value=\"{$myrow['cats']}\">{$myrow['cats']}</option>".PHP_EOL;
	echo "</select>".PHP_EOL;
	echo "<br><br>".PHP_EOL;
	echo "<input type='submit' name='btn' value='Show Selection'>".PHP_EOL;
	echo "</form>".PHP_EOL;
	echo "</div>".PHP_EOL;
	exit();
}

Hopefully you are all set and we are done.

Link to comment
Share on other sites

26 minutes ago, ginerjm said:
try
	{
		$db = new PDO($host, $username, $password);                       // ***    CLEARLY A CALL TO PDO::__construct()   ***
	}
	catch (PDOException $e)
	{
		echo "Fatal Error<br>Failed to connect to mysql via PDO.  PDO Error msg is:<br>".$e->getMessage();
		return false;
	}

 

@ginerjm So what's this BS about your not using a class to connect with PDO? Have you read your own code?

Link to comment
Share on other sites

14 minutes ago, ginerjm said:

And I have no errors when I run what I have just given you.  Here is the combined code:

Hopefully you are all set and we are done.

Not exactly. Because i got this ERROR left. How to stop the one session and where, I tried to find out, but nope. Could not find it.

 

4.png

Link to comment
Share on other sites

14 minutes ago, ginerjm said:

I told you earlier that I looked at it and saw that.  Didn't you read that post?

I dont think so because as i wrote to Barand now:

That'  how it is when it's to much fort and back to many times and things are going to fast. Many funny episodes because of that in my memory 😂

Link to comment
Share on other sites

3 hours ago, LeonLatex said:

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();

 

You should be using require here, not include.  The script cannot continue if the file fails to be included so you should just let it fail on the error of not finding the include file rather than a later undefined function error that can get you confused as to what the real problem might be.

50 minutes ago, LeonLatex said:

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

Opening your include (like db_inc.php) files directly usually isn't going to give you any helpful information, and might just send you down a wrong path.  If there's an error with the file it will show up when you include it into the main script you want to run.

The session start errors you are seeing suggest you may have PHP configured with session.auto_start=1, either disable the automatic session start or remove your session_start calls.

The re-defined function error suggests you are either including your db_inc.php twice.  Looks like in marina.php you include header.php and header.php includes db_inc.php.  Later on in marina.php you again include db_inc.php which results in the error.  You could change your code to use require_once to avoid this problem, or re-structure it so you only include the file once.

 

Link to comment
Share on other sites

34 minutes ago, ginerjm said:

you should only have one sessionstart in a script.  Only put it in the starting script that gets called to get you running.  None other.  Make the very first line (after the php tag)

Yes. I got a session start in both the header.php file and in the login file I can see. And after i put in your code in the db_inc.php (hope I said it right now) i get an error in the login php file when i click the log in button and i have the correct username and password. Do you want the error message from "login.php" ginerjm?

 

5.png

Edited by LeonLatex
Link to comment
Share on other sites

27 minutes ago, kicken said:

Opening your include (like db_inc.php) files directly usually isn't going to give you any helpful information, and might just send you down a wrong path.  If there's an error with the file it will show up when you include it into the main script you want to run.

The session start errors you are seeing suggest you may have PHP configured with session.auto_start=1, either disable the automatic session start or remove your session_start calls.

The re-defined function error suggests you are either including your db_inc.php twice.  Looks like in marina.php you include header.php and header.php includes db_inc.php.  Later on in marina.php you again include db_inc.php which results in the error.  You could change your code to use require_once to avoid this problem, or re-structure it so you only include the file once.

 

 

You should be using require here, not include.  The script cannot continue if the file fails to be included so you should just let it fail on the error of not finding the include file rather than a later undefined function error that can get you confused as to what the real problem might be.

Thanks kicken. I will try your tip .

Opening your include (like db_inc.php) files directly usually isn't going to give you any helpful information, and might just send you down a wrong path.  If there's an error with the file it will show up when you include it into the main script you want to run.

Do you mean by cut and paste it all into one file?

The re-defined function error suggests you are either including your db_inc.php twice.  Looks like in marina.php you include header.php and header.php includes db_inc.php.  Later on in marina.php you again include db_inc.php which results in the error.  You could change your code to use require_once to avoid this problem, or re-structure it so you only include the file once.

Ok. So I will change it to "require_once". Where all this calling on all the connections is from I don't understand...or I mean I don't remember. Do you know if they just can be there or stay as they are if I use the "require_once"? I guess I got more of them in other files too since I got some other files with the same error.

I dont know where you guys are from except Barand and Gizmola. I am from Norway, so i understand bedtime tierd etc is not the same as in Norway/Europe. But I hope you stay with me (not only me,  but stay here at PHP Freaks) as long as possible whereever you are in the world. I am screaming (almost) for help. And I am grateful to everyone who gives me a push.

Link to comment
Share on other sites

1 hour ago, LeonLatex said:

Do you mean by cut and paste it all into one file?

I mean opening your include files in your browser directly.  Accessing them directly to see if there are any errors is at best pointless and at worst misleading.  It's pointless because any errors that exist would be shown by PHP when it tries to parse the file during the include process.  It can be misleading because the file might depend on variables/functions defined in the main file which are not available when accessed directly and cause errors that otherwise wouldn't exist.

1 hour ago, LeonLatex said:

Ok. So I will change it to "require_once". Where all this calling on all the connections is from I don't understand...or I mean I don't remember. Do you know if they just can be there or stay as they are if I use the "require_once"? I guess I got more of them in other files too since I got some other files with the same error.

If you use require_once, then PHP will essentially ignore any attempts to require the same file after the first attempt.  This can allow you to simply require the file and not worry about if it was already required elsewhere or not.  Ideally you would re-structure the code so that the file is only required a single time, but using require_once would be a quick solution while you work towards something better later.

Link to comment
Share on other sites

21 minutes ago, kicken said:

 

I mean opening your include files in your browser directly.  Accessing them directly to see if there are any errors is at best pointless and at worst misleading.  It's pointless because any errors that exist would be shown by PHP when it tries to parse the file during the include process.  It can be misleading because the file might depend on variables/functions defined in the main file which are not available when accessed directly and cause errors that otherwise wouldn't exist.

I am aware of that. That's why I'm flipping backward. It may seem cumbersome to you Kicken, but it's not to me. It is also a way for me to learn the script and how it is connected.

If you use require_once, then PHP will essentially ignore any attempts to require the same file after the first attempt.  This can allow you to simply require the file and not worry about if it was already required elsewhere or not.  Ideally you would re-structure the code so that the file is only required a single time, but using require_once would be a quick solution while you work towards something better later.

I removed all included in the site and removed the session_start(); from header.php. Then it was a short way to make all work. Now there are some "modules" not working, but I am not going to use them in my next project. That is for a friend who asked me if I could make him a music management system for his vinyl collection. He got about 5000- 6000 LP and singles. Thanks for your help Kicken

Link to comment
Share on other sites

I want to say a BIG THANK YOU to all of you who helped me with this problem. It meant a lot to me. I solved it myself in the end, but I would never have been able to do it without their help to kick me in the right direction, so I got on the right track. Thank you very much 😊👍

I would like to give you a donation. It's just a problem. Most of you do not have a PayPal account. How can I show my gratitude to you? 🤓🤔

Link to comment
Share on other sites

Personally I would like to notice the improved knowledge and tougher questions that would tell us that you have learned from your experience with this forum.   Just to be see that would be great!  Of course that means you will be continuing to work with us when you need to and eventually come to be able to actually provide assistance to those 'noobs' that are soon to follow.   HTH

Link to comment
Share on other sites

Dont be afraid of that. We have many years ahead of us. I try hard and get back to where I was 12-15 years ago, both in business and knowledge. There have been many tragedies along the way. It started with a business fall from 1000 meters and lots of lost money, many deaths in close family and relationships, one broken marriage, close personal bankruptcy, and ended up drinking two liters of vodka or whiskey straight up a day for 4-5 years, one brain stroke, one daughter (now 25) nearly left me (too), one grandchild 2 years old in October (she's the reason i was waking up ++ etc, etc. + I was exposed to a traffic accident 34 years ago that broke my body in small pieces and which was close to taking my life + ADHD that can not be medicated. Of course, it has given me a lot of life experience. This has among other things taught me to listen to others and share what I have. is knowledge, money, etc. One should never give up. Life is fragile and life is what one makes it. We must live and fulfill our dreams while we can. One day it is too late. So now my goal is to come back to where I was in knowledge and business. It's not easy as 50 years and with so many scars r, a lot of new on the front we work, but there I go. When it comes to business Barand knows a little about what a ride I had in the last half of the 90s and early 2000s.

As time goes on, you will notice that Leon can also help, not just ask questions. I appreciate all of you and what you do for me. Thanks! I want to continue and be here. For me, this is the beginning of something long. 1.5 years have already passed. Take care guys 😊

  • Like 1
Link to comment
Share on other sites

On 7/2/2022 at 11:23 AM, mac_gyver said:

.....

 

18 hours ago, kicken said:

.....

 

16 hours ago, ginerjm said:

.....

 

22 hours ago, Barand said:

I read the version of that post before you edited it.

IIt's certainly not over yet. It turns out that when I log in, that's not what happens. Because I removed all error check and set everything to requierd_once. Therefore, it seemed to me yesterday that the site logged in. Because it now runs on whether it is wrong or not due to null error check and requierd_once. So now that I have finally slept a few hours and am a little more awake than yesterday, it is back to troubleshooting today as well. It was probably solved a lot yesterday because of your help here at PHP Freaks, but I think I may need you today as well. For it is you who point me in the right direction. I'm not to good enough yet to read the error messages.
I hope you can be with me this evening as well if I need you.

Link to comment
Share on other sites

Yes, when i run the script stand alone it is ok, but i get a lot of errors when the rest of the script is connected together i get the errors. It is like you warned me about. 
So sorry to hear you won't keep up with me. That is an honest choice. Hope to see you around any way from time to time in my weird PHP world.

Link to comment
Share on other sites

1 hour ago, ginerjm said:

It sure seemed to us that yesterday's problem was indeed solved.

Sorry I can't keep up with you.  G'bye.

Yes, when i run the script stand alone it is ok, but i get a lot of errors when the rest of the script is connected together. It is like you warned me about. 
So sorry to hear you won't keep up with me. That is an honest choice. Hope to see you around any way from time to time in my weird PHP world.

Link to comment
Share on other sites

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.