hi im attempting to update a script and i have come across the following error PHP Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in so here was the orginal

$sql = "select * from chat where (chat.to = '".mysqli_real_escape_string($_SESSION['usernamechat'])."' AND recd = 0) order by id ASC";

of which i changed to

$sql = "select * from chat where (chat.to = '".mysqli_real_escape_string($conn, $_SESSION['usernamechat'])."' AND recd = 0) order by id ASC"; 

and still getting the same error any ideas anyone

ty in advance jan x

Recommended Answers

All 3 Replies

Hi,

right before this code, set a check:

/* check connection */
if(mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

Too see why the connection returns null.

$conn was undefined so added global $conn; into function and it solved it ty very much hun x

Member Avatar for diafol

An alternative to making $conn global would be to pass the $conn as a parameter for your function. Globals are not always the best idea - see this v. old article: http://stackoverflow.com/a/5166527

$conn = ...(whatever)... ;
$usernameChat = $_SESSION['usernamechat'];

$chatLines = getChat( $conn, $usernameChat );

function getChat( $connection, $username ){
    $user = mysqli_real_escape_string( $connection, $username );
    $sql = "SELECT *  FROM `chat` WHERE `to` = '$user' AND `recd` = 0 ORDER BY `id`"; 
    //run and extract and modify and generally fiddle about
    return $data;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.