Terry
Terry

Reputation: 55

Did I write this function wrong? Can someone tell me where I am making my mistake?

Here is the function:

 <?php
 $connect = mysqli_connect('localhost','root','test123','joomla');

 function parseDescription($id)
 {
    $sql = "SELECT raw_description FROM n0dap_jevents_vevdetail WHERE evdet_id='$id'";
            $result=mysqli_query($connect,$sql);
            if (mysqli_num_rows($result) > 0)
            {
            return mysqli_fetch_array($result);
            }
     }              
     ?>

Here are the Errors:

Notice: Undefined variable: connect in C:\xampp\htdocs\Try\includes\function.inc.php on line 6

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\Try\includes\function.inc.php on line 6

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\Try\includes\function.inc.php on line 7

If I convert all this the Mysql instead of Mysqli it works but then all my regular expressions are all messed up. I've been at this for a few hours which pretty much tells you I'm a novice and really could use some help.

Upvotes: 0

Views: 52

Answers (2)

Nishant Solanki
Nishant Solanki

Reputation: 2128

This can be a bit difficult than regular functional programming, but oop is good way for managing your code..

Here I have declared $connect as a private variable of the class

Let me know if any further help needed regarding oop..

<?php

class MyClass
{
    private $connect;
    function __construct()
    {
        $this->connect = mysqli_connect('localhost', 'root', 'test123', 'joomla');
    }

    function parseDescription($id)
    {
        $sql = "SELECT raw_description FROM n0dap_jevents_vevdetail WHERE evdet_id='$id'";
        $result = mysqli_query($this->connect, $sql);
        if (mysqli_num_rows($result) > 0)
        {
            return mysqli_fetch_array($result);
        }
        else
        {
            return false;
        }
    }

}

$object = new MyClass();
$answer = $object->parseDescription($id);
if($answer)
{
  // do your stuff here
}
?>

Upvotes: 1

Dan Smith
Dan Smith

Reputation: 5685

As mentioned in comments, your connect variable is defined outside the scope of the function and so it's not able to make use of it. You'll need to pass that variable in to your function as a parameter like this:

 $connect = mysqli_connect('localhost','root','test123','joomla');

 function parseDescription($id, $connect)
 {
    // Your connection code
 }              

Upvotes: 2

Related Questions