I am mystified. The below code works just fine if it's enclosed in tags and the $data1, $data2 variables are gotten via $POST. However I'd like it enclosed in a function, and if I do:
function ($input1, $input2) { (then the code here) }
It fails. Is it something to do with the variables? Or the that you (just a guess) can't "require" something within a function?
Anyway...here's the code. I feel like this is something simple and syntactic, but I'm totally stumped. Here's the code:
//Set the connection or die returning an error.
require "connection.php";
echo 'connected';
// Make the query:
$query = "INSERT INTO message (col1, col2) VALUES ('$somedata1', '$somedata2')";
$result = @mysqli_query ($myconnection, $query); // Run the query.
if ($result) { // If it ran OK.
echo "Success!";
} else { // If it did not run OK.
echo "Error";
} // End of if
mysqli_close($myconnection); // Close the database connection.
//Free the result set.
mysqli_free_result($result);
//Close the connection.
mysqli_close($myconnection);
echo "<span style='color:red;'>Done.</span>";
EDITING to add some more code:
First, the DB connection is as follows:
<?php
DEFINE ('DB_USER', 'abcdef');
DEFINE ('DB_PASSWORD', '12345');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'mydb');
// Make the connection:
echo "Defined.";
$myconnection = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die ('Could not connect to MySQL: ' . mysqli_connect_error() );
echo "Connected.";
// Set the encoding...
mysqli_set_charset($myconnection, 'utf8');
?>
And I was not calling this anywhere else in the page that had the function. My hope was to have everything needed to connect and store all tightly there inside the function. Maybe this helps or makes more sense?
I had not gotten to the point where I was calling the function. Just including it at the top with the other functions was causing a white, blank page to appear.
You are using the variables $myconnection
, $data1
and $data2
which are defined outside the function. Add this line to the start of the function and it will work. Note that you have to put every variable's name there that is used but not defined in the function.
global $myconnection, $data1, $data2;
Also, don't put the require
in the function.
EDIT: As many have suggested, I'll include other ways.
Function argument:
function func($myconnection, $data1, $data2) {
// ...
}
// Calling the function
func($myconnection, $data1, $data2);
$GLOBALS
:
Replace all occurrences of $myconnection
, $data1
and $data2
with $GLOBALS['myconnection']
, $GLOBALS['data1']
and $GLOBALS['data2']
.