Basically I have a MySQL database and a table named users
in which there is a column named credits
. How do I get that integer value for the currently logged in user?
My columns are:
- user_id
- username
- password
- role
- credits
Basically I have a MySQL database and a table named users
in which there is a column named credits
. How do I get that integer value for the currently logged in user?
My columns are:
I assume you'll first want to authenticate your user. You can use any number of available libraries for that or roll your own. Here are a few places to start:
Once you have the user_id of the user who is authenticated you can build a very simple MySQL query to extract the credits:
// Connect to the database
$connection = new mysqli("localhost", "mysql_user", "mysql_password", "database");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if ($statement = $mysqli->prepare("SELECT credits FROM user WHERE user_id=?"))
{
// $user_id is the stored value
$statement->bind_param("i", $user_id);
$statement->execute();
$statement->bind_result($credits);
$statement->fetch();
echo "User has " . $credits . "credits<br/>";
$statement->close();
}
/* close connection */
$connection ->close();
Code mostly copy/pasted from http://www.php.net/manual/en/mysqli.prepare.php
if you know user_id, username or email of currently logged in user your SQL-queries would be:
"SELECT `credits` FROM `users` WHERE `user_id` = '$user_id'"
"SELECT `credits` FROM `users` WHERE `username` = '$username'"
"SELECT `credits` FROM `users` WHERE `email` = '$email'"
I assumed your users-table named "users"
Not quite sure about this, since I usually work with PDO, but I guess it should be fine for the beginning
<?php
$db = mysql_connect("localhost", "user", "password");
$sql = "SELECT credits FROM users WHERE user_id = " . mysql_real_escape_string($_SESSION['userid']);
$result = mysql_query($sql);
$row = mysql_fetch_object($result);
$credits = $row->credits;
echo $credits;