• PHP Help
  • Passing a database connection into a function

Hi. I need help with a PDO connection. I am tyring to upgrade to PDO as my web host is doing a major upgrade. I have a working connection object at the top of the file. On line 72 I need to pass it into the function LpgMeX2(). I can’t pass it as an argument because the calling function only supplies 3 arguments. It doesn’t know about the database.
If I do function LogMeX2($conn, $name , $pwd1, $Sector) then I get an error
Warning: Missing argument 4 for LogMeX2()
CODE:
`` <?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

define ('HOSTNAME1', 'mysql09.iomart.com');
define ('USERNAME1', 'otoogc692');
define ('PASSWORD1', 'mauritius');
define ('DATABASE1', 'otoogc692');

$host = HOSTNAME1;
$user = USERNAME1;
$pass = PASSWORD1;
$MyDB = DATABASE1;

$conn = new PDO("mysql:host=$host; dbname=$MyDB; charset=UTF8", $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);

function Session_Init()
{
if (!isset($GET['counter']))
$
GET['counter'] = "";
if (!isset($SESSION['current_page']))
$
SESSION['current_page'] = '';
if (!isset($SESSION['Event_Log']))
$
SESSION['Event_Log'] = '';
if (!isset($SESSION['K9']))
$
SESSION['K9'] = '';
if (!isset($SESSION['Survalance']))
$
SESSION['Survalance'] = '';
if (!isset($SESSION["K208"]))
$
SESSION["K208"] = '';
if (!isset($SESSION["Error_1"]))
$
SESSION["Error_1"] = '';
if (!isset($SESSION["Error_2"]))
$
SESSION["Error_2"] = '';
if (!isset($SESSION["Error_3"]))
$
SESSION["Error_3"] = '';
if (!isset($SESSION["Error_4"]))
$
SESSION["Error_4"] = '';
if (!isset($SESSION["Error_5"]))
$
SESSION["Error_5"] = '';
if (!isset($SESSION["Current"]))
$
SESSION["Current"] = '';

// Email Sessions
if (!isset($SESSION["Name"]))
$
SESSION["Name"] = '';
if (!isset($SESSION["Name2"]))
$
SESSION["Name2"] = '';
if (!isset($SESSION["Email"]))
$
SESSION["Email"] = '';
if (!isset($SESSION["Subject"]))
$
SESSION["Subject"] = '';
if (!isset($SESSION["Msg"]))
$
SESSION["Msg"] = '';
}

function FindMe()
{
$CookiePresent = 0;
if (isset($COOKIE["Headquarters"]))
{
if($
COOKIE["Headquarters"] == "Bananarama")
$CookiePresent = 1;
}
return $CookiePresent;
}

function LogMeX2($conn, $name , $pwd1, $Sector) // E101
{
$Name = md5($name);
$Pwd1 = md5($pwd1);
$ThisSector = $Sector;
$valid = 0;
$sqlValid = $conn->query("SELECT current FROM LIBusersX WHERE UserKey = '$Pwd1' AND UserN = '$Name' AND K_Type = 1 AND current > 0");
exit;
$qValid = mysql_query($sqlValid) or die ("E101-100A");
$total = mysql_num_rows($qValid);
if($rows === FALSE) die('E101-101B');
//
// echo $sqlValid . "<br>" . $total;
// exit;
if($total == 0)
$ret = 0;
if($total > 1)
$ret = -1;
if($total == 1)
$ret = 1;

 if($ret == 1)
{
	$ret = 0;
	$rs = mysql_fetch_array($qValid) or die ("E101-100B");
	$temp = $rs['current'];
	if($temp < 99)
	{
		$temp -= 1;
		$update = "UPDATE LIBusersX SET current = $temp WHERE UserKey = '$Pwd1' AND UserN  = '$Name'  AND K_Type = 1";
		echo $update;
		exit;
		$result = mysql_query($update);
	}
	$sqlUser = "SELECT User FROM LIBusersX WHERE UserKey = '$Pwd1' AND UserN = '$Name'";
	$qUser = mysql_query ($sqlUser) or die ("E101-100C");
	$rs = mysql_fetch_array($qUser) or die ("E101-100D");
	// Checl valid sector
	$ThisUser = $rs['User'];
	$ValidSector = "SELECT * FROM LibSectors WHERE User = '$ThisUser' AND SectorMarker = '$ThisSector'";
	$qValid = mysql_query($ValidSector) or die ("E101-100E");
	$total = mysql_num_rows($qValid);
	if($total > 0)
	   $ret = $ThisUser;		   	
}

return $ret;
}

?>
``

    To post code on the forum using markdown, it's three back-ticks, and these must be on a line before and after the code. You may still have the ability to edit your post above to correct this.

    The cause of the current error is probably the same as your previous error about an undefined variable when there was a single parameter. Wherever or however you are running this php code isn't getting the changes or is taking some time for the changes to take effect, due to caching.

    An important point about updating code from the old mysql extension, is that the small amount of security that php provided for sting values, via magic_quotes, has also been removed. You need to use a prepared query when you are supplying external, unknown, dynamic values to a query. The link you received (elsewhere) to the phpdelusion.net PDO extension/examples shows how to do this. Just about every place you have a php variable inside an sql query statement will need to be converted to use a prepared query place-holder, the query will need to be prepared, then executed, with an array of the input values being supplied to the ->execute([...]) call.

    The PDO extension always uses exceptions for connection errors, and in php8+ by default uses exceptions for query, prepare, execute, and exec errors. When using exceptions for errors, your or die(...) logic for these statements will no longer ever be executed and should be removed. In most cases, errors with these statements are programming mistakes, won't normally occur, and you would simply let php catch and handle exceptions from these statements, where php will use its error related settings to control what happens with the actual error information (database statement errors will 'automatically' get displayed/logged the same as php errors). The exception to this rule is when inserting/updating duplicate data values (your database table would have any column that must not contain duplicate values defined as a unique index.) In these cases, you would have exception try/catch logic in your code, detect if a duplicate index error number has occurred, and setup a message for the user letting them know what was wrong with the data that they submitted. For all other error numbers, just re-throw the exception and let php handle it.

    Sorry I am lost wityh this. Do I replace single apostraphy and replace with double quotes? remove the escapr back slashes?or remove or die statments. I don't use escape back slashes. this is just text surrounded by double qiuotes surounded by bracket. I can remove these if it is a problem.

    The function file needs to check. LogMeX2 requires access to the PDO connection but I can't have
    LogMeX2(Connection, Name, Password, Bank) as this is an extra argument. So how do I
    function LogMeX2($Name , $password, "Bank")
    {
      $sqlValid = $conn->query(  arguments in here);
    }```

    Incidentally, you might want to ask your hosting provider why they're upgrading to a version of PHP that has been unsupported for more than three months (the currently-supported versions of PHP are all version 8).

    Sorry I am lost wityh this. Do I replace single apostraphy and replace with double quotes? remove the escapr back slashes?or remove or die statments. I don't use escape back slashes. this is just text surrounded by double qiuotes surounded by bracket. I can remove these if it is a problem.

    No-one mentioned apostrophes or double quotes or backslashes.

    otuatail The function file needs to check. LogMeX2 requires access to the PDO connection but I can't have
    LogMeX2(Connection, Name, Password, Bank) as this is an extra argument. So how do I
    function LogMeX2($Name , $password, "Bank")
    {
    $sqlValid = $conn->query( arguments in here);
    }```

    Why not

    function LogMeX2($conn, $Name , $password, $Sector)
    {
      $sqlValid = $conn->query(  arguments in here);
    }

    ? Or however you want to name your variables for consistency. And then call it with four arguments: the connection and whatever three arguments were you supplying originally.

    otuatail Sorry I am lost wityh this. Do I replace single apostraphy and replace with double quotes? remove the escapr back slashes?or remove or die statments. I don't use escape back slashes. this is just text surrounded by double qiuotes surounded by bracket. I can remove these if it is a problem.

    I don't know which part of the phpdelusions site you were pointed to last time, but the error handling pbismad is referring to is described in the Error handling. Exceptions section.

    otuatail or remove or die statments.

    Also, see the top user comment in the manual's die page.

      Write a Reply...