Jump to content

mysqli_connect() won't work inside include file


bulrush

Recommended Posts

First, I'm kind of new to PHP though I've been programming for many years. I'm still getting used to the little "gotcha's" of PHP.

 

Second, I'm working on a program with about 10+ php files now. I want to make my code more modular so I put, in a require_once file, a function "crqrySelect" to run a select query and return a variable. The require_once file is called "crutil.php".

 

My problem is, my variables to connect to the mysql db is in a file called "connectvars.php", which is put into "crutil.php" via require_once('connectvars.php'). However, in my function "crqrySelect" I get an error in mysqli_connect which indicates that the db variables are not set.

 

Here is "connectvars.php":

<?php
global $host;
global $user;
global $password;
global $database;

$host="i.aabb..com";
$user="cr88";
$password="mypw";
$database="dbcr";
?>

 

Here is the "crutil.php" file. The function names are in alpha order.

<?php
require_once('connectvars.php');
//Functions:
//crCreateSelect($query, $name)
//crCreateTextbox($type, $name, $maxlen, $size)
//crDebug($func, $myerr)
//crError($func, $myerr, $bool)
//crqryExec($query)
//crqrySelect($query)
//====================================================
function crCreateSelect($query, $name, $field)
//$field=name of field which contains value to display in 
//select box.
{
$query=trim($query);
$name=trim($name);
if (empty($query))
{
$s=$_SERVER['PHP_SELF'].' crCreateSelect ERROR: param 1 query is empty.';
die($s);
}
if (empty($name))
{
$s=$_SERVER['PHP_SELF'].' crCreateSelect ERROR: param 2 name is empty.';
die($s);
}

$s='<select name="'.$name.'" id="'.$name.'">'."\n";
//Do query and error checking here.
if (!$result=mysqli_query($dbc,$query))
    {
    $msg=mysql_error();
    echo '<p class="error">'.__FUNCTION__.' ERROR: '.$msg.'<br/>'.$query.'</p>';
    die();
    }
$num=mysqli_num_rows($result);
if ($num==0)
    {
    $msg="<p class=\"error\">'.__FUNCTION__.' ERROR: No data found. $query</p>";
    die($msg);
    }

//Do loop here to construct options.
while ($row = mysqli_fetch_array($result))
{
$n=$row[$field]; //Get value from named field.
$s.='<option value="'.$n.'">'.$n;
$s.='</option>';
$s.="\n";
} //while

$s.='</select>';

echo "$s\n";
return;
}
//====================================================
function crCreateTextbox($type, $name, $maxlen, $size)
{
$type=trim($type);
$name=trim($name);
if (empty($type))
{
$s=$_SERVER['PHP_SELF'].' crCreateTextbox ERROR: param 1 type is empty.';
die($s);
}
if (empty($name))
{
$s=$_SERVER['PHP_SELF'].' crCreateTextbox ERROR: param 2 name is empty.';
die($s);
}

$s='';
$s.='<input type="'.$type.' name="'.$name.'" id="'.$name.'" ';
if (!empty($size))
{
$s.='size="'.$size.'" ';
}
if (!empty($maxlen))
{
$s.='maxlen="'.$maxlen.'" ';
}
$s.=' />';
echo "$s\n";
return;
}
//====================================================
function crDebug($myerr)
//Display error, then die.
{
$msg=mysql_error();
echo '<font color="Green">DEBUG: '.$myerr.'</font><br/>';
return;
}
//====================================================
function crError($func, $myerr, $b)
//Display error, set $b to true to die.
{
$msg=mysql_error();
echo '<p class="error">ERROR in '.$func.': '.$myerr.'</p>';
if ($b)
{
die();
}
return;
}
//====================================================
//Run a INSERT or UPDATE query. No records should be returned.
function crqryExec($query)
{
//echo "Query: $query<br/>";
if (!$result=mysqli_query($dbc,$query))
    {
    $msg=mysql_error();
    echo '<p class="error">'.__FUNCTION__.' ERROR: '.$msg.'<br/>'.$query.'</p>';
    die();
    }

return;
}
//====================================================
//Run a select query. There should be >0 records returned.
function crqrySelect($query)
{
//echo "Query: $query<br/>";
if (strlen($query)==0)
{
$msg='Query is blank.';
    $s='<p class="error">'.__FUNCTION__.' ERROR: '.$msg.'<br/>'.$query.'</p>';
    die($s);
}
$dbc = mysqli_connect($host, $user, $password, $database); //Line 132 error here

if (!$result=mysqli_query($dbc,$query)) //Line 134 error here.
    {
    $msg=mysql_error();
    $s='<p class="error">'.__FUNCTION__.' ERROR: '.$msg.'<br/>'.$query.'</p>';
    die($s);
    }
$num=mysqli_num_rows($result);
if ($num==0)
    {
    $msg='<p class="error">'.__FUNCTION__.' ERROR: No data found. <br/>'.$query.'</p>';
    die($msg);
    }

return $result;
}
?>

 

My guess is I'm not understanding how global variables work, or how require_once files work.

 

In my login.php script, which calls crqrySelect, I also do require_once('connectvar.sphp') follwed by require_once('crutil.php'). Then "crutil.php" also does require_once('connectvars.php'). I hope that is not a problem.

 

The exact error is:

Warning: mysqli_connect() [function.mysqli-connect]: (HY000/2002): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) in /nfs/c01/h04/mnt/6787/domains/i.com/proto3/crutil.php  on line 132

Warning: mysqli_query() expects parameter 1 to be mysqli, boolean given in /nfs/c01/h04/mnt/6787/domains/i.com/proto3/crutil.php on line 134

Anyone know what might be wrong?

 

Link to comment
Share on other sites

At first glance you have your execute query the wong way round.

mysqli_query($dbc, $query)

should be:

mysql_query($query, $dbc)
//or even just
mysql_query($query)

also I notice that you are stripping all the white space out of your query before you run it.  Personal recomendation would be to not do that, it can cause problems with WHERE clauses on occasion.  Give some thought to using something like this:

$query_check=trim($query);
if (empty($query_check))
{
$s=$_SERVER['PHP_SELF'].' crCreateSelect ERROR: param 1 query is empty.';
die($s);
}
...
$result = mysql_query(mysql_real_escape_string($query))

 

Just a thought though.

Link to comment
Share on other sites

require_once will only load the file once hence the name ;) So if its already been loaded it will not be loaded again. I believe globals are used to create a variable in a function that you will need to access outside of the function but I could be wrong. You should just be able to define the variables and they should work. Try define() http://php.net/manual/en/function.define.php

Link to comment
Share on other sites

I've been programming for many years

 

Then you should already know that the code and variables in a function are local to that function so that they can perform the task needed by that function without needing to worry about any unintended interaction with anything outside of that function and that you must pass any values into a function as parameters in the function call.

 

If you have variables and functions that are so closely related that they will always be used together, you should be using OOP/classes.

Link to comment
Share on other sites

At first glance you have your execute query the wong way round.

mysqli_query($dbc, $query)

should be:

mysql_query($query, $dbc)
//or even just
mysql_query($query)

 

Actually he's using mysqli_query() right.

Link to comment
Share on other sites

Actually, I need the following variables to be global because they are set in "connectvars.php" and will be used in many php files: $host, $user, $password, $database.

 

And yes, mysqli_connect() does have the correct syntax. The variables are in the opposite order as mysql_connect().

 

So, any clues as to why I get an error in mysqli_connect in crqrySelect in "crutil.php"?

 

Link to comment
Share on other sites

Each of your mysqli_query() statements is going to have the same problem referencing the $dbc connection variable.

 

I suggest you rethink what you are trying to use functions for. They are not designed to share variables between functions or to directly access main program variables.

Link to comment
Share on other sites

Each of your mysqli_query() statements is going to have the same problem referencing the $dbc connection variable.

What I make $dbc a global in "connectvars.php"? Then set it in my main program so my functions can use it in mysqli_query()? Will that work?

I suggest you rethink what you are trying to use functions for. They are not designed to share variables between functions or to directly access main program variables.

If the variables are global then shouldn't the functions be able to use those global vars? Or does PHP not work this way?

 

Link to comment
Share on other sites

The global keyword you are using in connectvars.php code does NOT do what you think it does.

 

Those variables are already in the global (main program) scope and putting the global keyword anywhere in the main program has absolutely no meaning.

Link to comment
Share on other sites

PFM, you are kind of right. This is how I got things to work.

function crqrySelect($query)
{
global $dbc; //Define this var as the global version.
//echo "Query: $query<br/>";
if (strlen($query)==0)
{
$msg='Query is blank.';
    $s='<p class="error">'.__FUNCTION__.' ERROR: '.$msg.'<br/>'.$query.'</p>';
    die($s);
}

if (!$result=mysqli_query($dbc,$query))...

 

By putting "global $dbc;" right after my function definition, I was able to get this function to see the $dbc variable defined in my main program, and it all works like I thought. Success!

 

Now I can reuse these functions for doing SELECT statements (which return records) and INSERT and UPDATE statements (which do not return records).

 

I got my info from http://www.php.net/manual/en/language.variables.scope.php

 

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.