This question already has answers here:
Giving my function access to outside variable
(6 answers)
Reference: What is variable scope, which variables are accessible from where and what are "undefined variable" errors?
(3 answers)
Closed 4 years ago.
Hello I am pretty sure they are in the same scope and am unsure why I am getting this error now as it was working before.
These are the other files in the same folder as
the php file :
dbh.php
recipeLookUp.php
It is line 9 that I am getting the error
this is the recipeLookUp.php
<?php
function lookup($sql,$column_name){
$results_search=array();
include_once 'dbh.php';
$results=mysqli_query($conn,$sql);
$resultsCheck = mysqli_num_rows($results);
if ($resultsCheck > 0) {
while ($row = mysqli_fetch_assoc($results)){
$info= $row[$column_name];
$results_search[]=$info;
}
return $results_search;
}
}
and here is my other file
<?php
$dbServername = 'localhost';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'Recipe';
$conn = mysqli_connect($dbServername,$dbUsername,$dbPassword,$dbName);
Im sure it probaly something small but I can't find it please help!!!
The include_once 'dbh.php'; within your function seems fishy. What are you gonna do if you have other functions which need to perform SQL queries as well?
Instead, I would put the include_once 'dbh.php'; outside (above) your function, and perhaps use require_once instead of include once. And then inside your function, put global $conn; above the mysqli_query call, so your $conn variable is defined there when you pass it along to mysqli_query.
However, if you are worried about creating unnecessary SQL connections (e.g. in case your lookup function is never actually called) I think it would be even better to put this in your dbh.php :
<?php
$conn = null;
function Query($sql)
{
global $conn;
if (!$conn) // will only connect if connection does not exist yet
{
$dbServername = 'localhost';
$dbUsername = 'root';
$dbPassword = 'xxxxxxxxxxx';
$dbName = 'Recipe';
$conn = mysqli_connect($dbServername,$dbUsername,$dbPassword,$dbName);
}
return mysqli_query($conn,$sql);
}
?>
And now in your main PHP file, or any PHP file where you include require_once 'dbh.php'; you can directly use Query($sql) to perform queries, which will take care of the connection itself (and only do so if necessary).
Related
This question already has answers here:
mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource
(31 answers)
Is it possible to use both MySQLi and PDO?
(2 answers)
Closed 5 years ago.
here is my code which I pass two variables from android studio to php. xampp has both apache and MySQL running on the default ports. my aim is to compare variables got from android studio with ones in the database table; but i get an error that says:
Uncaught Error: Call to a member function bindParam() on boolean in C:\xampp\htdocs\digikala\index.php:10 Stack trace: #0 {main} thrown in C:\xampp\htdocs\digikala\index.php on line 10.
I should also mention windows 10 pro is running on my system.
could any of you guys could help me get over this problem? thanks in advance.
here is my connect.php code:
<?php
function OpenCon()
{
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "digikala";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
return $conn;
}
function CloseCon($conn)
{
$conn -> close();
}
?>
and this is my main code which error belong to. if I remove bindParam and put $email and $pass directly in sql code the same error happens for line contains $result->execute():
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
include "connect.php";
$email=$_POST["user"];
$pass =$_POST["pass"];
$conn = OpenCon();
$query = 'SELECT * FROM member WHERE email=:email AND pass=:pass';
$result= $conn->prepare($query);
$result->bindParam(':email',$email);
$result->bindParam(':pass',$pass);
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
if ($row == false ){
echo("not existed!");
}else{
echo("welcome" . $email);
}
CloseCon($conn);
?>
This question already has answers here:
Call to a member function prepare() on a non-object PHP Help [duplicate]
(8 answers)
Closed 6 years ago.
I have a following code
//dsn.php
//Object Oriented way
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database";
//check connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($conn->connect_error) {
die("could not connect:".$conn->connect_error);
}
//index.php
include 'dsn.php';
function a() {
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
$sql = "sql command";
$result = $conn->query($sql);
//not working
$conn->close();
}
This will display warning and notice that says:
Warning: mysqli::query(): Couldn't fetch mysqli
Notice: Trying to get property of non-object
Warning: mysqli::close(): Couldn't fetch mysqli
However this one works:
include 'dsn.php';
function a() {
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
include $dsn.php
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
How do I use just one include file for DSN and use repeatedly on other functions?
EDIT
sorry I forgot to mention
function a($conn) {}
function b($conn) {}
I passed the variable $conn but it still displays the warning and notice I mentioned above
When you include a file, you can imagine that in the background it is just copy-pasting that code into the current document.
There are 2 problems with your code...
The $conn variable is not in scope inside function a or b.
Even if it was in scope and accessible, you are closing the connection after each query. A better way to do it is to open the connection, run all queries and close the connection when it is no longer needed.
The second piece of code you gave works because it is creating a new variable $conn inside of b(), but this is not ideal as it will create a new database connection every time you execute that function.
Something like this may suit your needs:
include 'dsn.php';
function a($conn) {
$sql = "sql command";
$result = $conn->query($sql);
return $result;
}
function b($conn) {
$sql = "sql command";
$result = $conn->query($sql);
return $result;
}
$aResult = a($conn);
$bResult = b($conn);
$conn->close();
Notice that we are only including 'dsn.php' once, and then passing around that existing connection to the functions that need it.
This is very simple. On page load, the connection file is included which makes $conn the connection object available to the remaining codes. The $conn is used by the functiona() and it is then closed at the end of the function. $conn->close(); destroys the database connection object means, $conn is no more object hence it should not be treated as object. But the Function b() is treatong it as database connection object and resulting into error.
But if you again include the connection file, inside the function b() then $conn becomes available to the function as local object. And works as it should.
Do not close the $conn() on the any function till you are dealing with DB.
function a() {
incDbConnectionFile();
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function b() {
incDbConnectionFile();
$sql = "sql command";
$result = $conn->query($sql);
//working
$conn->close();
}
function incDbConnectionFile() {
include 'dsn.php';
}
I know this is little bit strange but some variables are undefined when including these variables.
This is my web structure:
details.php:
$login['server'] = 'server';
$login['database'] = 'db';
$login['username'] = 'user';
$login['password'] = 'pass';
define ('constant1' , 'ok');
main.php:
include ('subfile.php');
subfile.php:
echo $login;
echo constant1;
index.php:
include ('details.php');
include ('main.php');
And output is undefined $login and ok. I already tried with get_included_files() in subfile.php and this function shows details.php as included file.
This is a general example.
The application has 3 files.
conn.inc.php -- setting up the database connection
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "hmt";
$conn = new mysqli($db_host, $db_username, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
func.inc.php -- file including functions
<?php
function load_module($module_name){
$sqlCmd = "SELECT content FROM modules WHERE name='$module_name' LIMIT 1";
$result = $conn->query($sqlCmd);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$module_footer = $row["content"];
}
}else {
echo 'Error while loading module '.$module_name;
}
return $result;
$result->free_result();
}
?>
index.php -- the main page to display content
<?php
include 'conn.inc.php';
include 'func.inc.php';
if (!isset($_GET['page_name'])) { // if page_name is not set then reset it to the homepage
$page_name = 'module_footer';
}else{
$page_name = $_GET['module_footer'];
}
$module_content = load_module($page_name);
echo $module_content;
?>
Now my goal was to include functions inside the func.inc.php file and database into conn.inc.php, so as to keep separate and easier to read in the future.
My problem now is that the $conn variable declared in conn.inc.php cannot be used inside the function and it can't get my head around how to use it. I even tried using GLOBALS with no success.
The error for the files is this:
Notice: Undefined variable: conn in ./func.inc.php on line 4
Fatal error: Call to a member function query() on a non-object in ./func.inc.php on line 4
Which (I assume) is because the $conn variable is not in a global scope.
Now my question is. How can I keep the nested files but have the functions working? Is there a mistake in my approach or is it not possible to use a nested call to a mysql object?
Eventually you'll want to get into object-oriented coding but for now lets make what you have a little prettier.
When including files, you'll want to avoid things like global variables. They sound great, but end up being a pain when handling scope. So instead include a set of functions to call.
conn.inc.php
function getConnection(){
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "hmt";
$conn = new mysqli($db_host, $db_username, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
return $conn;
}
Then function.inc.php
<?php
function load_module($module_name){
$sqlCmd = "SELECT content FROM modules WHERE name='$module_name' LIMIT 1";
//Here is where we get our database connection.
$conn = getConnection();
$result = $conn->query($sqlCmd);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$module_footer = $row["content"];
}
}else {
echo 'Error while loading module '.$module_name;
}
return $result;
$result->free_result();
}
And finally finish up with your index page the way it is. So now, any page that wants a database connection will need to include the conn.inc.php and simply call getConnection() to get a mysqli connection object.
Think of your program as being a series of individual functions working together. And eventually you'll get to it being a series of objects working together. Nothing should be just floating off in global space. Try to encapsulate everything in some sort of function or object to be called over and over with consistent results.
You'd have to do something like this:
$conn = '';
function connect() {
global $conn;
... do db stuff
}
But this is usually bad practice. A more common method is to use a singleton object to "carry" your db handle, and you new that singleton everywhere you need to do DB operations.
function do_something() {
$conn = new DBSingleton();
... do db stuff
}
My problem is,
This is the file that is being included ,
<?php
$dbhost = "localhost";
$dbuser = "****";
$dbpass = "***";
$dbname = "****";
$MYSQL_ERRNO = "";
$MYSQL_ERROR = "";
// Connect To Database
function db_connect() {
global $dbhost, $dbuser, $dbpass, $dbname;
global $MYSQL_ERRNO, $MYSQL_ERROR;
$link_id = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$link_id) {
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = "Connection failed to $dbhost.";
return 0;
}
else if(!mysql_select_db($dbname)) {
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
}
else return $link_id;
}
?>
The main file has the following code to make db connection ,
<?php
require_once 'file.php';
$link_id = db_connect($dbname);
......
?>
But i got function undefined error.
Using Apache in Windows with PHP 5.3
1) Check relative paths for your includes.
2) Just because the PHP documentation says you can use require_once without parenthesis doesn't mean you should. Stay consistent, use require_once("file.php");.
3) Be consistent with curly braces in your function. You're missing one or two up there. I'd like to know if you rewrite your function the following way if it works:
function db_connect() {
global $dbhost, $dbuser, $dbpass, $dbname, $MYSQL_ERRNO, $MYSQL_ERROR;
$link_id = mysql_connect($dbhost, $dbuser, $dbpass);
if ($link_id === false) {
$MYSQL_ERRNO = 0;
$MYSQL_ERROR = "Connection failed to $dbhost.";
return 0;
} elseif (mysql_select_db($dbname) === false) {
$MYSQL_ERRNO = mysql_errno();
$MYSQL_ERROR = mysql_error();
return 0;
} else {
return $link_id;
}
}
And remember, checking your web server error logs usually helps.
Edit:
According to the comments for this answer, you're not including the file you think you are. Use an absolute path for the include so you're 100% sure of the file being included.
A logic.
Sometimes we need it.
Let's sort out your case.
you can see whatever "function undefined error." (Although I'd prefer literal and exact PHP error messages as they contain A LOT of useful information, let's assume it's regular PHP error thrown right in this place).
We can conclude from the (1) that you can see alll errors occurred.
So, from (2) we can tell the if there was a file not found error, you'd be notified of it.
So, we can assume from (3) that there is no error and file being included correctly.
What's next?
The most possible reason for you getting this error is the wrong code you posted here.
For example, if you include your file not as file.php but as http://example.com/file.php the result will be exactly as described.
Or there can be 2 files named 'file.php', one contains the function definition and another without it.
Or there can be a typo in the function's name as well.
So, you just have to double check your names and print some debugging info to be sure you are including the right file and calling the right function.