I am trying to set up a basic shopping cart application with a link to a database. Obviously I have the connection set up at the top of the code with:
$dsn = "mysql:dbname=MYDATABASE";
$username = "root";
$password = "MYPASSWORD";
try {
global $conn;
$conn = new PDO( $dsn, $username, $password );
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch ( PDOException $e ) {
echo "Connection failed: " . $e->getMessage();
}
And then I have my first step, which asks for various information, and then would save it to a database. The way that I am doing this is as follows:
function processStep1() {
$_SESSION["firstname"] = $_POST["firstname"];
$_SESSION["lastname"] = $_POST["lastname"];
$_SESSION["address"] = $_POST["address"];
$_SESSION["city"] = $_POST["city"];
$_SESSION["state"] = $_POST["state"];
$_SESSION["zip"] = $_POST["zip"];
$sql = "INSERT INTO customers VALUES ( '" . $_SESSION["firstname"] . "', '" . $_SESSION["lastname"] . "', '" . $_SESSION["address"] . "', '" . $_SESSION["state"] . "', '" . $_SESSION["city"] . "', '" . $_SESSION["zip"] . "' );";
try {
$conn->query( $sql );
} catch ( PDOException $e ) {
echo "Query failed: " . $e->getMessage();
}
displayStep2();
}
When I run this page, however, I get the error:
"Notice: Undefined variable: conn" as well as "Fatal error: Call to a member function query() on a non-object".
I did manage to read online that this is because $conn
is not being passed to the function, but I am not sure how I would go about passing it, because my method for calling the function processStep1()
is as follows:
if ( isset( $_POST["step"] ) and $_POST["step"] >= 1 and $_POST["step"] <= 5 ) {
call_user_func( "processStep" . (int)$_POST["step"] );
} else {
displayStep1();
}
So as to facilitate a multi-page system in a streamlined fashion, it simply checks for the step number whenever the form is submitted and then assembles the function call using call_user_func, so how would I pass $conn
into that? I'm not certain.
Any help would be appreciated!