0

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!

2
Contributors
3
Replies
23
Views
2 Years
Discussion Span
Last Post by madmax9922
1

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();
1

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;
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.