1

I created a plugin and defined a shortcode there. This includes my own PHP scripts (pages). The data are in a second database. The direct mysql query works fine (testcode), but the db.class create a warning in debug.log: PHP Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /usr/www/users/samtgt/2019-Wordpress/wp-content/eigeneScripte/Classes/db.class.php on line 47

sql.inc.php

$con = mysqli_connect($data["host"],$data["user"],$data["pwd"],$data["db"]);
if ( !$con) die('Die SQL-Datenbank ist ausgefallen, bitte versuchen Sie es zu einem späteren Zeitpunkt noch einmal'.mysqli_connect_error());
mysqli_set_charset($con,"utf8");

test.php This code works fine.

$dir = __DIR__."/";
include_once($dir."sql.inc.php");

// Testcode Anfang
if ($result = mysqli_query($con,"SELECT Aemter FROM Aemter")) {
    while($obj = $result->fetch_object()){
        $line.=$obj->Aemter."<br>";
    }
    echo $line;
    
    $result->close();
}
// Testcode Ende

This code create an error

$dir = __DIR__."/";
require_once($dir."sql.inc.php");//die("ja");
require_once($dir."Classes/db.class.php");

function lebenslage() {
    $DB = new db_query();
    $DB->execute("SELECT * FROM Lebenslagen ORDER BY Lebenslagen");
    echo "<center>\n";
    echo "<form style=\"padding-top:20px\" action=\"".$_SERVER["PHP_SELF"]."\">\n";
    echo "<select name=\"Lebenslagen\">\n";
    echo "<option selected>Lebenslage</option>\n";
    while($DB->next()){
        echo "<option value=\"".$DB->value("Lebenslagen_id")."\">".$DB->value("Lebenslagen")."</option>\n";
    } // while
    echo "</select>&nbsp;&nbsp;&nbsp;";
    echo "<input type=\"SUBMIT\" name=\"step\" value=\"anzeigen\" />\n";
    echo "</form>\n</center>\n";
}

db.class.php

class db_query
{
        /**
         * Das Handle der DB-Connection
         */
      public $con;

        /**
         * Pointer innerhalb der aktuellen Query
         */
      public $queryptr;

        /**
         * Anzahl der Ergebniszeilen
         */
      public $rowcount;

        /**
         * Ergebnis der Query-Operation als assoziatives Array
         */
      public $result;

        /**
         * Ausfhren eines SQL-Befehls
         *
         * Speichert den Pointer auf das Ergebnis des Befehls in $queryptr
         * und die Anzahl der erhaltenen Zeilen in $rowcount
         */
      function execute($sql)
    {
            global $debug;
            global $con;
// here is line 47
            $this->queryptr = mysqli_query($con,$sql)
                or die ("<br></tr></table>Fehler beim Absetzen des SQL-Statements:<br><b>$sql</b><br><i>".mysqli_error($con))."</i>";
            $this->rowcount = mysqli_affected_rows($con);


      } 
      
        /**
         * Ausf¸hren von INSERT oder UPDATE ohne R¸ckgabewerte
         *
         */
      function exec($sql)
      {
            global $con;
            mysqli_query($con,$sql)
                or die ("<br></tr></table>Fehler beim Absetzen des SQL-Statements:<br><b>$sql</b><br><i>".mysqli_error($con));
      }

      /**
         * Holen der nÔøΩhsten Resultat-Zeile der Query
         *
         * Speichern der Inhalte der Resultat-Zeile im assoziativen Array $result
         */
      function next()
      {
            global $con;
            $this->result = mysqli_fetch_array($this->queryptr);
            if (!$this->result) {
            return (false); } else {
            return (true); };
      }

      /**
         * R¸ckgabe des gewnschten Wertes aus der aktuellen Resultat-Zeile
         */
      function value($col)
      {
            return($this->result["$col"]);
      }
      

        /**
         * In die Result-Zeile $jmp springen (klappt nicht so ganz)
         */
      function jump($jmp)
      {
              $this->result = mysql_data_seek($this->queryptr,$jmp);
      }
    
    /**
     * die zuletzt eingegebene id zurückliefern
     */
    function last_id()
    {
        global $con;
        return mysqli_insert_id($con);
        //or die ("<br></tr></table>Fehler beim Absetzen des SQL-Statements:<br><b>$sql</b><br><i>".mysqli_error($con));
    }
}

Who can help? Bernd

  • 1
    None of that code is WordPress code. You should not be creating standalone PHP files that get called on your site directly by the browser for security and maintenance reasons. If you need to make AJAX requests, use the REST API, if you need to handle form requests, submit the form with action="" and test the GET/POST parameters in the template that rendered the form or on the init hook. If you need to make an SQL query, use $wpdb, and if you need to query a remote DB or use different details, create a new WPDB object – Tom J Nowell Aug 5 '20 at 19:37
  • Otherwise, for generic PHP questions, ask on stackoverflow, there's more general PHP expertise on that stack, you're more likely to get help with mysqli – Tom J Nowell Aug 5 '20 at 19:38
  • Also, you will need to explain where $data comes from, remember that PHP programs only exist for a single request and are loaded from a blank slate on every request. You can't declare a variable on a page load then use it on another – Tom J Nowell Aug 5 '20 at 19:40
1

This isn't a Wordpress question it's a PHP question, but probably what's happening is that you need to declare global $con everywhere before you both use and set $con.

So in your sql.inc.php put a global $con; before you set it the first time. Then obviously make sure you do global con; before every place you use it.

EDIT:

Using globals in this way is pretty messy when you can control all the code in a self contained but of functionality like this. It's better when you can to pass variables directly to exactly the places that it's needed. In this case you should probably pass $con in to the constructor of the class, save it as a private property on the class and then reference it with $this->con instead of globaling it.

The reason for doing this is because when you come to debug or change code, having used global variables makes it very hard to trace the places that you need to change or debug. It's convenient in the short term but in the long term takes much much more of your time to change and debug later.

  • I added global $con to sql.inc.php, it works. Thank you – berndhs Aug 10 '20 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.