Execute function after connect to database
Solution 1:
You need to declare variables "global" :
<?php
$conn = null; // ◄■■■
$result = null; // ◄■■■
function connect_to_database($servername, $username,$password,$dbname)
{ global $conn; // ◄■■■
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
}
function execute($get_sql)
{ global $conn; // ◄■■■
global $result; // ◄■■■
$sql[0] = $get_sql;
$result = mysqli_query($conn,$sql[0]); // ◄■■■ $CONN AND $RESULT.
}
connect_to_database("localhost","root","root","m1_14");
execute("INSERT INTO teszt_1 (email,username,order,createdate) " .
"VALUES ('[email protected]','test','test',NOW())");
execute("select * from teszt_1");
foreach ( $result as $row ) // ◄■■■ USE $RESULT HERE.
echo $row["email"];
Global variables let you pass values from one function to another.
In case of a "insert" you don't need $result
, in case of a "select" you can use $result
to access the values.