Martin Martin - 2 months ago 12
SQL Question

PHP function returns wrong values

I have this function

function getNick($uid)
{
$sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
mysqli_real_escape_string($con,$sqli);
$resulti = mysqli_query($con,$sqli);
$rowi = mysqli_fetch_assoc($resulti);
if($resulti->num_rows > 0) return $rowi["nick"];
else return "(none)";
}


Basically it should return me nick based on user's id. Problem is that I only keep getting '(none)'. What is interesting I printed actual $sqli and copied it into phpMyAdmin and it worked as expected. I even tried to just print nick without IFs but I ended up with empty string. What might be the issue? Am I overlooking something? Thanks

Answer
<?php

$con = mysqli_connect("localhost","root","","test");

function getNick($uid,$con)
{

    $sqli = "SELECT nick FROM users WHERE userid='".$uid."'";
    mysqli_real_escape_string($con,$sqli);
    $resulti = mysqli_query($con,$sqli);
    $rowi = mysqli_fetch_assoc($resulti);   
    if($resulti->num_rows > 0) return $rowi["nick"];
    else return "(none)";
}

echo getNick(1,$con);
?>

it works

variable scope problem

use above method to pass connection in method or

use $GLOBALS['con'] to access connection in method getNick