PHP and MySQL Select a Single Value
The mysql_* functions are deprecated and unsafe. The code in your question in vulnerable to injection attacks. It is highly recommended that you use the PDO extension instead, like so:
session_start();
$query = "SELECT 'id' FROM Users WHERE username = :name LIMIT 1";
$statement = $PDO->prepare($query);
$params = array(
'name' => $_GET["username"]
);
$statement->execute($params);
$user_data = $statement->fetch();
$_SESSION['myid'] = $user_data['id'];
Where $PDO
is your PDO object variable. See https://www.php.net/pdo_mysql for more information about PHP and PDO.
For extra help:
Here's a jumpstart on how to connect to your database using PDO:
$database_username = "YOUR_USERNAME";
$database_password = "YOUR_PASSWORD";
$database_info = "mysql:host=localhost;dbname=YOUR_DATABASE_NAME";
try
{
$PDO = new PDO($database_info, $database_username, $database_password);
}
catch(PDOException $e)
{
// Handle error here
}
Don't use quotation in a field name or table name inside the query.
After fetching an object you need to access object attributes/properties (in your case id) by attributes/properties name.
One note: please use mysqli_* or PDO since mysql_* deprecated. Here it is using mysqli:
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'username', 'password', 'db_name');
$link->set_charset('utf8mb4'); // always set the charset
$name = $_GET["username"];
$stmt = $link->prepare("SELECT id FROM Users WHERE username=? limit 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_object();
$_SESSION['myid'] = $value->id;
Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)