Hi, i have a " Deprecated: mysql_real_escape_string()" and a "Deprecated: mysql_query" error while running my webpage in function.php and users.php. I would like to know how to change this following code to be uptodate
connect.php

<?php 

$db  = new mysqli('localhost','root','','madmax');

if ($db->connect_errno){
    die('Sorry, we are having connection problems.');
}

?>

function.php

function sanitize($data){
    $db  = new mysqli('localhost','root','','madmax');

    return htmlentities(strip_tags(mysql_real_escape_string($data)));

users.php

function user_id_from_username($username){
    $username = sanitize ($username);
    return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username`='$username'"), 0, 'user_id');
}

Thank you in advance!

Member Avatar for diafol

I would stop worrying about sanitizing and just create a prepared statement.

$db  = new mysqli('localhost','root','','madmax');

function user_id_from_username( $db, $username ){
    if($stmt = $db->prepare("SELECT `user_id` FROM `users` WHERE `username`=?"))
    {
        $stmt->bind_param("s", $username);
        $stmt->execute();
        $stmt->bind_result($user_id);
        $stmt->fetch();
        return $user_id;
    }
    return 'Username not found';
}

echo user_id_from_username( $db, $_GET['username'] );

$db->close();
Member Avatar for diafol

Or PDO:

$db  = new pdo('mysql:host=localhost;dbname=madmax','root','');

function user_id_from_username( $db, $username ){
    if($stmt = $db->prepare("SELECT `user_id` FROM `users` WHERE `username`=?"))
    {
        $stmt->execute([$username]);
        return $stmt->fetchColumn();
    }
    return 'Username not found';
}

echo user_id_from_username( $db, $_GET['username'] );

$db = null;

Thanks a lot! it's work fine.

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.