-1

Hello i just want write own function to get option value from mysql. My index.php file looks in this way:

<?
include ('config.php'); // here i have database connection details
include ('global-functions.php');
include ('minifier.php');
include ('cache-start.php');
?>
<!DOCTYPE html>
<html lang="jezyk strony z bazy danych">
USTAWIC META! sekcje head<br>
Sprawdzić czy dodac przekierowanie w php z www na bez www !!
<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">


(...) rest of the file

config.php file looks:

<?php

$host = "localhost";
$dbname = "xxxx";
$username = "xxx";
$password = "xxxx";

// Create connection
$conn = new mysqli($host, $username, $password, $dbname);

?>

Now i try to do function to take specified option, i put this function in global-functions.php:

<?php


// Get option

function get_option( $option_name ) {

    $sql = "SELECT opcja_value FROM opcje WHERE opcja_name='" . $option_name . "'";
    $result = mysqli_fetch_array($conn->query($sql));

    return $result[$option_name];

}

?>

Now i going to call function to get value of my option. So:

echo get_option('cache');

or doing simple if :

if ( get_option('cache') == '1' ) {
 // do stuff
} else {
 echo 'option disabled, sorry :(';
}

After call function i get Fatal error:

Fatal error: Call to a member function query() on null in /framework/includes/global-functions.php on line 10

robimy seo
  • 53
  • 1
  • 1
  • 6

2 Answers2

4

Scope scope scope! $conn does not exist within the scope of your function. You can declare it with global, or pass it in, like so:

function get_option( $option_name, $conn ) { // Pass in $conn here

    $sql = "SELECT opcja_value FROM opcje WHERE opcja_name='" . $option_name . "'";
    $result = mysqli_fetch_array($conn->query($sql));

    return $result[$option_name];

}
aynber
  • 22,380
  • 8
  • 50
  • 63
  • Hello, thanks for reply. i just change code and i have now this: Missing argument 2 for get_option(), called in /framework/includes/minifier.php on line 4 and defined in /framework/includes/global-functions.php on line 7 // My minifier.php file just call this function. How i can use conn globaly? Meaby problem is with include, meaby i must use require ?? – robimy seo Nov 16 '16 at 14:09
  • You also need to add $conn whenever you call the function `get_option($optionshere, $conn);` – aynber Nov 16 '16 at 14:11
0

I suggest reading this

You are accessing a global variable inside a function ($conn). To make that variable accessible inside the function just use global $conn; at the start of your function.

Community
  • 1
  • 1
JensV
  • 3,997
  • 2
  • 19
  • 43