Jump to content

PDO - Uncaught Error: Call to a member function


Go to solution Solved by Barand,

Recommended Posts

I am brand new to PDO and i am very sure this is a simple issue but i am struggling to work it out.

My connection file:

<?php
  $host_name = '*******.hosting-data.io';
  $database = '******';
  $user_name = '******';
  $password = '******!';


  try {
    $pdo = new PDO("mysql:host={$host_name}; dbname={$database}", $user_name, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
  } catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
  }

?>

and the function that i am trying to run:

function getClientName($display)
{
	$pdo = require 'includes/dbconn.php';

	$sql = "SELECT id, name from clients";

	$stmt = $pdo->query($sql);

	$clients = $stmt->fetchAll(PDO::FETCH_ASSOC);
	if ($display == 'select') {
		if ($clients) {
			$out = "<div class='input-group mb-3'>
						<label class='input-group-text' for='inputGroupSelect01'>Client Name</label>
						<select class='form-select' id='inputGroupSelect01'>
							<option selected disabled>Please Select</option>
							<option value='0'>-- New Client --</option>";
			foreach ($clients as $client) {
				$out .= "<option value='{$client['id']}'>{$client['name']}</option>";
			}
			$out .= "</select>
					</div>";
		}
	}
	return $out;
}

I am getting an error on line 9 of the function which is:

	$stmt = $pdo->query($sql);

I am trying to figure out what is causing this error and if my PDO is not correct.

I am getting the connection successful message.

Edited by Adamhumbug

So i am calling the function like this:

<?=getClientName($pdo, 'select');?>

and needed to ammend the function name like this:?

function getClientName($pdo, $display)

That gives me:

Fatal error: Uncaught Error: Call to a member function query() on int in /homepages/20/d832698785/htdocs/platforms/quote-master/includes/functions.php:9 Stack trace: #0 /homepages/20/d832698785/htdocs/platforms/quote-master/new-quote.php(12): getClientName(1, 'select') #1 {main} thrown in /homepages/20/d832698785/htdocs/platforms/quote-master/includes/functions.php on line 9

 

Edited by Adamhumbug
1 minute ago, Barand said:

PS

Also, require is not a function

image.png.4b52f8acc8873e8443e62250eb6e114c.png

The $pdo  variable is created inside the code within your page scope.

I think that was the issue here, i removed the bit you suggested and all seems to be working - looks like i was breaking the variable there.

 

Thanks very much!

5 minutes ago, Adamhumbug said:

and needed to ammend the function name like this:?

function getClientName($dpo, $display)

 

Yes (except fot the typo)

function getClientName($pdo, $display)
{
    ....
}

 

I would also NOT include/require the connection code within a function.  That means every time you call it you re do the connection.  Not at all necessary.

I would put your connection code into a function that returns the pdo handle ($pdo).  And when I call that connection function it would be:

$pdo = PDOConnect($dbname)

Now you have a handle to use throughout your script and inside other function if you pass it to them.   I also wrote my connect function to pass in the dbname to make it more universal.

Feeling magnanimous today, here's the function I use to connect:

function PDOConnect($l_dbname=NULL, $l_msg=null, $l_options=null)
{
	if ($l_options == null)
	{	// set my default options
	  $l_options = array(PDO::ATTR_EMULATE_PREPARES => false,
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
			PDO::MYSQL_ATTR_FOUND_ROWS => true,
			PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);
	}
	if ($l_dbname == null)
		$host="mysql:host=localhost;charset=utf8";
	else
		$host="mysql:host=localhost;dbname=$l_dbname;charset=utf8";
	$uid = "xxx";
	$pswd = "yyy";
	try
	{
		$pdo = new PDO($host, $uid, $pswd, $l_options);
	}
	catch (PDOException $e)
	{
		if (strtoupper($l_msg) == "SHOWMSG")
			echo "Fatal Error<br>Failed to connect to mysql via PDO.  PDO Error msg is:<br>".$e->getMessage();
		else
			echo "Fatal Error<br>Possible bad dbname?<br>Failed to connect to database server.  Sensitive error msg may be viewed with additional parm to call to PDOConnect(dbname,'showmsg')";
		return false;
	}
	if (!$pdo)
		return false;
	else	// all worked - return handle to pdo connection.
		return $pdo;
}

This assumes that you will want the assoc array format returned from your queries.  You can easily override that in your fetch calls if you need to do something different at that point.

Stick this in some 'php' folder outside of your web tree so that only php scripts (and not html/web pages) can see it.  Then simply call it ONCE in your script by:

$pdo = PDOConnect($dbname);

  • Great Answer 1

when you make the database connection, you should also set the character set and some more options. see this post - 

also, for catching database exceptions in your code, there's no point in doing this except for user recoverable errors, such as when inserting/updating duplicate or out of range values, where the catch logic would test for the appropriate sql error numbers and setup messages telling the user what was wrong with the data that they submitted. in all other cases, there's nothing the user can do to recover from the type of error that would be occurring and even letting a hacker know that they were able to trigger a database error is not something you want to do, so, you might as well just let php catch the exceptions in these cases, simplifying your code.  also, outputting the raw error message, like you are doing in the connection code, will only help hackers, when they intentionally do things to trigger errors, e.g. you can trigger a connection error by making a large number of requests that use connections, and the connection error message contains your database host name/ip, the connection username, if you are using a password or not, and web server path information. you DON'T want hackers to see this type of information.

 

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.