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.