This question already has answers here:
Giving my function access to outside variable
(6 answers)
Closed 8 years ago.
I have a problem. I am including my database details in my functions.php file. Like this:
db.php:
$dbhost = "localhost";
$dbname = "test";
$dbuser = "root";
$dbpass = "root";
$dbc = new PDO("mysql:host=" . $dbhost . "; dbname=" . $dbname ."", $dbuser, $dbpass);
functions.php:
include_once 'db.php';
function retrieve($count)
{
$query = "SELECT * FROM table WHERE column = ?";
$sth = $dbc->prepare($query);
$sth->bindValue(1, $count);
$sth->execute();
$resultCount = $sth->rowCount();
}
file.php:
include 'functions.php';
...
When I try to call my functions file in file.php, so I can use the function retrieve, my php_error.log file shows the following:
[Date] PHP Notice: Undefined variable: dbc in functions.php on line 6
My goal is to create an instance of PDO and use that in all the other pages so I don't have to create an instance over, and over again. I tried to achieve this by creating the $dbc variable and instancing a new PDO connection to it in db.php. Then, I would include it in functions.php so whenever a function is called, the $sth variable will hold the methods used, using $dbc (the instance of the PDO connection).
Does anyone know why am I getting this error, and possibly, could anyone give me some advice on how to parametrize the creation of an instance of PDO and use it/them throughout other pages?
Thank you for your time and help!
Cheers!
You have to pass the database connection to the function where your query is in order for it to work.
Related
This question already has answers here:
PDO closing connection
(6 answers)
Closed 6 years ago.
This is mysql Connection code.
$db_host = "localhost";
$db_name = "propstor_image";
$db_user = "root";
$db_pass = "";
try{
$db_con = new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_pass);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}?>
When I try to Close mysql connection by using mysql_close($db_con); It shows following error
" mysql_close() expects parameter 1 to be resource, object given in C:\wamp\www\property\member\include\login.php on line 57" .Please can you help me how to close mysql connection.
For PDO
The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
reference link : Link
You could try this:
<Connection variable>.Close();
Example:
conn.Close();
I hope this helps!
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Attempting to try and join my table called 'UserCaseMessages' with my other table called 'Comments' using this exact sql command in php:
$sql = "
SELECT UserCaseMessages.DefendantID, Comments.CommentID
FROM UserCaseMessages
INNER JOIN Comments
ON UserCaseMessages.DefendantID = Comments.SenderID
";
$result = $conn->query($sql);
if ($result->num_rows > 0) // ERROR GETS THROWN ON THIS LINE {
}
Here is the connection part to my database (which occurs prior to the query):
$servername = "localhost";
$username = "username";
$password = "password";
// Get the username from the post
$userUsername = $_POST['string'];
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
I get the following error:
PHP Notice: Trying to get property of non-object
I cannot figure out what I am doing wrong here!! Everything is spelled correctly and a checked and checked for any syntax errors and I can't find any, however I am new to this particular method. Please help!
Since you haven't responded to my comments (some 20+ minutes prior to my submitting this), I am posting the following answer.
You didn't choose a database here:
$servername = "localhost";
$username = "username";
$password = "password";
$conn = new mysqli($servername, $username, $password);
so you need to add the database parameter:
$servername = "localhost";
$username = "username";
$password = "password";
$database = "your_DB";
$conn = new mysqli($servername, $username, $password, $database);
Read the manual on connecting with the MySQLi API:
http://php.net/manual/en/function.mysqli-connect.php
Check for errors on the query also:
http://php.net/manual/en/function.mysql-error.php
Plus, make sure the POST array does contain a value. Something in regards to the HTML form you didn't post.
The form's element must contain a matching name attribute:
name="string" and there must be a POST method for <form>.
method="post".
FYI: <form> is the equivalent to <form method="get"> as it defaults to a GET method if POST isn't implied.
Check for errors with error reporting also:
http://php.net/manual/en/function.error-reporting.php
Although, if your form does not have a POST method as I already mentioned, you won't get errors for it, strangely enough.
Sidenote about $userUsername.
That is ambiguous. If you are trying to run a query against that variable, you would need to use a WHERE clause.
I.e.: WHERE column = '$userUsername'
I have a func.php file that contains a function that gets my user's details:
require_once 'connection.php';
function getUI($username){
$query = "SELECT * FROM usernames WHERE username = ?";
$sth = $pdo->prepare($query);
$sth->bindValue(1, $username);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
return $result;
}
in my connection.php I have:
require_once 'details.php';
$pdo = new PDO("mysql:host=" . $dabhost . "; dbname=" . $dabname ."", $dabusern, $dabpassw);
and in details.php I have:
$dabhost = "localhost";
$dabname = "dab1";
$dabusern = "root";
$dabpassw = "root";
And ultimately, I have my userdetails.php that has a bunch of HTML code and displays the results that the function getUI() would bring back. I require func.php at the beginning:
require_once 'folder1/func.php';
My directory looks like this:
rootfolder/userdetails.php
rootfolder/folder1/details.php
rootfolder/folder1/connection.php
rootfolder/folder1/func.php
The issue is that when I open userdetails.php, I get an error in my php_error.log file that says the following:
PHP Notice: Undefined variable: pdo in /rootfolder/folder1/func.php on line 58
PHP Fatal error: Call to a member function prepare() on null in /rootfolder/folder1/func.php on line 58
Where if I were to just put all the code at the top of my userdetails.php, it would work and bring back the expected results. Therefore, there is something wrong with how I am requiring the files/scope of the variables I think...
Could someone explain to me what am I doing wrong?
Your help is much appreciated!
Thanks a lot!
UPDATE:
Passing my $pdo connection as a second argument in the function solved my proble, but now I am unable to retrieve x result from my returned $return variable, for instance:
echo $result['date'];
It says that the variable $result is not defined. Any idea why is this occurring?
Thanks a lot again!
When you declare
function getUI($username) {}
$pdo is not available because it is outside the scope of the function.
You'll need to pass it in as an additional parameter or find some other mechanism for getting $pdo inside getUI().
If you need more information
require_once 'connection.php';
function getUI($username,$pdo){
$result = null ;
$query = "SELECT * FROM usernames WHERE username = ?";
$sth = $pdo->prepare($query);
$sth->bindValue(1, $username);
$sth->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
return $result;
}
Note : Pass PDO object as second parameter when you call above function.
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 9 years ago.
This is code is made to return the name of a chosen $ID from the database,
#DB Informations (username/password)
require('/path/to/db_informations.php');
# This function return the 'name of the $ID from the db
function getName($ID){
$link = new PDO($dsn, $user, $pwd);
$query = "SELECT `name` FROM `tables` WHERE `id`=$ID";
$smt = $link->prepare($query);
$smt->execute();
$name = $smt->fetch(PDO::FETCH_ASSOC);
return $name['name'];
}
# db_informations contain the credentials to connect the database. ($dsn, $user, $pwd)
Mmh require(/path/to/db_informations.php') is not working inside the function even if I put `require();' function in the body. I do not understand my mistake, can you please explain me:
Why the /path/to/file is not included by PHP? and How to?
Your DB variables are not in scope of your getName() function. You need, at bare minimum:
function getName(...) {
global $dsn, $user, $pwd;
...
}
In the greater picture, you should NOT be using global variables, nor should you be creating a DB connection in every function call. Connect to the database ONCE in your db setup file, then simply re-use that connection for the rest of the DB operations in your script.
This is a variable scope issue.
$dsn, $user, $pwd are global variables and not defined within the getName() function scope.
The quickest way to resolve this is to use global.
function getName($ID) {
global $dsn, $user, $pwd;
// code...
}
However, I do not recommend using global (they are evil). The better thing to do would be to define your database object (PDO) at the global scope and pass it around to your functions/classes. This is called dependency injection.
This question already has answers here:
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 2 years ago.
I have a file that corrals my re-usable functions into one file (functions.php). It's include_once()'d on every page that needs it. I'm getting an error when my custom functions are trying to access a MySQL connection outside their own scope. The source is a bit like this:
<?php
// functions.php
$connect = mysql_connect("localhost", "user", "pass") or die("MySQL said: ".mysql_error());
mysql_select_db("database", $connect) or die("MySQL said: ".mysql_error()); // no error
/* ... */
function getmotd($user) {
$query = "SELECT cid FROM `users`
WHERE id = ".$user;
$query = mysql_query($query, $connect); // error occurs here, $connect is not a valid MySQL link-resource
/* ... */
}
?>
Why can't my function access variables declared above it's scope? I can get a successful connection by reproducing $connect's declaration within the function.
Any insight into how I can work around this or what I'm doing wrong here?
You can't access $connect because it is outside the scope of the function; that is, PHP can only see the variables within the function when it's inside it. You could use the global keyword to let PHP know the variable is outside the function's scope as Kemal suggests, but I think a better course of action is to pass the connection into the function. This will give you better encapsulation. If you learn to write your functions (and later classes) with passing in the resources and data you need (a practice known as "dependency injection"), you'll find you have cleaner and more maintainable code. Here's the example:
function getmotd($db, $user) {
$query = "SELECT cid FROM users WHERE id = " . (int)$user;
$result = mysql_query($query, $db);
/.../
}
$connect = mysql_connect(...);
mysql_select_db(...);
$motd = getmotd($connect, $user);
Hope this helps.
Use the global keyword.
Example
function getmotd($user) {
global $connect;
$query = "SELECT cid FROM `users`
WHERE id = ".$user;
$query = mysql_query($query, $connect); // error occurs here, $connect is not a valid MySQL link-resource
/* ... */
}
You can also do it like this
function getmotd($user) {
$query = "SELECT cid FROM `users`
WHERE id = ".$user;
$query = mysql_query($query, $GLOBALS['connect']); // error occurs here, $connect is not a valid MySQL link-resource
/* ... */
}
If you want to make re-usable codes, you'd probably be better off with OOP. Create a class for the database, and add some properties for the database info, and access them from the functions by using the this keyword.