Jump to content

Not passing Variables from functions correctly?


fireice87

Recommended Posts

Hey

I know the code i've got here works fine, but i feel I've iv learnt enough about php now to start writing code with functions and includes. The issue im having i think is due to the way im trying to get variables from the  function. below is the important bits from my code:

index.php

<?php require('Functions/functionlist.php'); ?>
<body>
<div class="#container" id="container">
<?php require('Includes/header.php'); ?>
<?php require('Includes/left_column.php'); ?>
<?php require('Includes/featured_products.php'); ?>
</div>
</body>

featured_products.php

<div class="#products" id="products">
<?
dbconnect($conn, $db);
$sql = "Select * FROM ug_products";  
$result= @mysql_query($sql, $conn )or die("Could not pull products");
?>

functionlist.php

<?php 
function dbconnect($conn, $db)
{
       $conn = @mysql_connect( "*****", "*****, "*****")
or die ("could not connect to mysql");  #Connect to mysql
$db = @mysql_select_db( "gigshare_site", $conn )
or die ("Could not select database"); #select database
}	
dbconnect($conn, $db)	
?>

 

All i keep getting is the "Could not pull products" statment ffrom my sql or die script.

This code worked fine before i re-formatted it into functions.

Im pretty sure its to do with the $conn variable.

 

Any help would be much appreciated

Thanks

 

Why are you sending the $conn and $db info into the function if your just gonna define them inside the function?

 

You send variables in the call when it's like dbconnect($host, $user, $pw); then function dbconnect($host, $user, $pw) { $conn = mysql_connect($host, $user, $pw); }.

it's many way to solve this

1st change

function dbconnect($conn, $db)

to

function dbconnect(&$conn, &$db)

 

2nd change

$result= @mysql_query($sql, $conn )or die("Could not pull products");

to

$result= @mysql_query($sql)or die("Could not pull products");

 

3rd

change your function to return $conn

 

 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.