Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning code into a function, but it's not working

I use this code to count how many times a person appears in a database (across 15 columns).

$name = "Clint Irwin";
$query = mysqli_query($con, "
    SELECT * FROM `players` 
    WHERE MATCH (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15)
    AGAINST ('$name' IN BOOLEAN MODE) 
    AND rank <= 1000");
$result = mysqli_num_rows($query);
echo $name.' '.$result;

This works... however, I want to make it easier so I can run it on a ton of different names... So I tried this...

function gw($name) 
{   
    $query = mysqli_query($con, "
        SELECT * FROM `players`
        WHERE MATCH (p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15) 
        AGAINST ('$name' IN BOOLEAN MODE)
        AND rank <= 1000");
    $result = mysqli_num_rows($query);
    echo $name.' '.$result;
}

//run it for certain person names,
gw("Clint Irwin");

And it doesn't work. I just get the following error message

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in /Applications/XAMPP/xamppfiles/htdocs/test.com/index.php on line 19

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, null given in /Applications/XAMPP/xamppfiles/htdocs/test.com/index.php on line 21
Clint Irwin

Any idea how I can get it working? It seems simple to fix, but I just can't figure it out.

like image 316
Cully Avatar asked May 25 '26 03:05

Cully


2 Answers

$con isn't in-scope within your function, so you're passing in a local variable whose unitialized value will be null. You need to make it a global, or pass the connection as a parameter:

function gw($name) {
   global $con;
}

OR

function gw($name, $con) {
}

gw('foo', $con);
like image 95
Marc B Avatar answered May 26 '26 16:05

Marc B


You are trying to reach $con which is not defined in your method. You either need to write

global $con; at the beginning of the method, or pass it as an argument.

like image 29
OptimusCrime Avatar answered May 26 '26 18:05

OptimusCrime



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!