[SOLVED] Execute function after connect to database

Issue

I have a problem, I’m trying to do functions who can execute SQL syntax, but when I’m trying to execute it mysqli_query causes an error, because this function needs two parameters. But I have another function to connect to database, how can I fix this problem?

function connect_to_database($servername, $username,$password,$dbname) {
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
}
    
function execute($get_sql) {
    $sql[0] = $get_sql;
    mysqli_query($sql[0]);
}
    
connect_to_database("localhost","root","root","m1_14");
execute("INSERT INTO teszt_1 (email,username,order,createdate) VALUES ('[email protected]','test','test',NOW())");

Solution

Do this :

mysqli_query need two parameters and you give only once, so give yout execute function all the parameters for mysqli_query function

function connect_to_database($servername, $username,$password,$dbname) {
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    //return connection or define connection as global and use as global scenario
    return $conn;
}

function execute($get_sql, $connect) {
    $sql[0] = $get_sql;
    mysqli_query($connect, $sql[0]);
}

$connection = connect_to_database("localhost","root","root","m1_14");
execute("INSERT INTO teszt_1 (email,username,order,createdate) VALUES ('[email protected]','test','test',NOW())", $connection);

Answered By – jean-max

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.