Trying to output the richest user in my database through php - php

I know this is a bit of a rookie question but I'm trying to output the richest user's name on my website.
So my table is called Users
I have Column 1 ('Name') containing the names of all the users, and Column 2 ('Bank') containing their account balance.
I would like to find the richest user and output them on my website.
This is what I've got so far.
while ($row2 = mysqli_fetch_array($sqldataGang, MYSQLI_ASSOC)) {
$sqlgetGang = 'select name from gangs where bank = (select max(bank) from gangs) order by bank;';
$sqldataGang = mysqli_query($dbcon, $sqlgetGang) or die('Connection could not be established');
$welthiestGang = $row2['name'];
}
I know that there is a connection to the database as I have other statistics from other tables working... I have no idea why this isn't working... Thanks for the help in advance :)

$sql = 'SELECT name FROM gangs ORDER BY bank DESC LIMIT 1';
That should do it.

You need to fetch a row from your $sqldataGang query object.
Add a line something like this to your program to fetch the result right after your call to mysqli_query()
$row2 = mysqli_fetch_array($sqldataGang, MYSQLI_ASSOC);
But, also, beware. A wise programmer always checks queries for errors. You can see how to do that in the examples here.

Use this query
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT name,bank FROM Users order by bank desc limit 1";
$result = mysqli_query($conn, $sql);
This will give you the richest person in your website

Related

MySQL Usernames Listed in ONE Field Inside of a Table To Query Another Table and Return User Results [duplicate]

This question already has answers here:
mysqli_stmt::execute() expects exactly 0 parameters, 1 given
(4 answers)
Closed 1 year ago.
So I am new to PHP and I have been on a roll lately developing a website. My question is this. I have all users listed inside of a field in one table.
This is a list of one of these fields: admin, user1, user2, user3.
Now what I need to do is take them users from that ONE field, I am guessing put them into an array and then search each user inside of another table called users and then list the users info such as their rating and bio.
I reposted this with pictures to help you get an idea of what I am looking to accomplish.
I am looking to get the users from this table listed inside of that cell
jobs Table
and find them in this table and then list them
users table
Hey I have edited the code in the following way and I am getting an error.
$jobID = 1;
$jq = $con-> prepare('SELECT applied_names FROM jobs WHERE jobID=1 LIMIT 1');
$jq-> execute();
$jq-> bind_result($usernames);
$jq-> fetch();
$jq-> close();
$stm = $con->prepare("SELECT username FROM users WHERE username IN (?)");
$stm->execute(array($usernames));
$result = $stm->get_result()->fetch_assoc();
$stm->close();
The warning says:
Warning: mysqli_stmt::execute() expects exactly 0 parameters, 1 given on line 14
You can use a subquery and the keyword IN for this:
SELECT * FROM meta_table WHERE userID IN (SELECT id FROM users)
If you post table & column names, I will be able to give you a more precise query.
EDIT:
after seeing your edited post with the images, this way is not possible. you would still be able to use the IN after you have got the field with the usernames in PHP.
$usernames = $row['applied_names'];
$stm = $pdo->prepare("SELECT * FROM users WHERE username IN (?)");
$stm->execute(array($usernames));
And for mysqli:
$usernames = $row['applied_names'];
$stm = $con->prepare("SELECT * FROM users WHERE username IN (?)");
$stm->bind_param('s', $usernames);
$stm->execute();
In my opinion, you should have a users_jobs table with columns id userID & jobID then you can use queries like this:
SELECT username,email,jobName,jobStatus FROM users_jobs
JOIN users ON users.id = users_jobs.userID
JOIN jobs ON jobs.id = users_jobs.jobID
This will produce one row with all the columns you have specified in the SELECT
Just try that :
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT name, rating, bio FROM Users";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "name: " . $row["name"]. " - rating: " . $row["rating"]. "bio " . $row["bio"]. "....<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>

Display an int value from SQL database using PHP

I'm busy with a school project where I need to register users. I created the database and added the tables and can add users. What I just can't get right is to display the next available user id in the table.
I'm using php to retrieve the highest value but when I use echo the variable won't show. There is no error, there is no output at all, just the rest of the page.
Here is the code:
<?php
$db = mysqli_connect('localhost', 'root', '', 'design');
$query = "SELECT MAX(userid) AS userid FROM users" or
die(mysql_error());
$highest_id = mysqli_query($db, $query);
echo $highest_id;
?>
The code successfully connects to the database, the column is called userid, it contains int values and there are other columns as well.
All other code in the script runs perfectly, it's just this part that I can't get to work.
I have spent the last two days reading and searching for answers and I am at my wits end. Any help would be appreciated.
Thank you.
could be your table is User and not Userid
$query = "SELECT MAX(userid) AS userid FROM users"
Anyway for fetching you should use eg:
$result = mysqli_query($db, $query);
$row=mysqli_fetch_array($result,MYSQLI_NUM);
echo $row[0];
The mysqli_query returns a general object that contains the results array. You have to use the mysqli_fetch_row.
<?php
$db = mysqli_connect('localhost', 'root', '', 'design');
$query = "SELECT MAX(userid) AS userid FROM userid" or die(mysql_error());
$highest_id_query = mysqli_query($db, $query);
var_dump($highest_id_query); // so you could check the object attributes
//loop results from query
while($row=mysqli_fetch_row($highest_id_query)){
$highest_id = $row['userid'];
echo $highest_id;
}
?>
You could also use the sql statement: SELECT COUNT(*) FROM userid
Be sure to name your tables correctly! SELECT COUNT(*) FROM users

Getting last group_id from MySQL in PHP

I want to get last added group_id from MySQL to get new $group_id++ for other group.
I tried
$group_id = ("select max(group_id) from posts");
$group_id++;
But when I check it with echo
echo $group_id;
the result is : "select max(group_id) from posts"
You're assigning a query string to a variable..you're not even running the query...?
You need to run the query and assign it to a result ($group_id_)
There's other ways to do this but this is similar to what you're doing.
$result= mysqli_query($conn, "select max(group_id) as max from posts");
$row = $result->fetch_assoc($result);
$group_id = $row['max'];
$group_id++;
This is because you are not executing an SQL query, you are doing an assignment.
The correct syntax is something like this:
$result = mysqli_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
Search how you can execute SQL queries, and if you have trouble, post again.
Edit: Have a look on the link below
https://secure.php.net/manual/en/mysqli.query.php
This is the easiest way to implement it the latest one will have the highest ID so you order them by their id starting from the highest id to the lowest and you just take the first one.
Read about the http://php.net/manual/en/book.mysqli.php it explains everything about querying data from your database using php.
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
if($result = $mysqli->query("select group_id from posts ORDER BY group_id DESC LIMIT 1")){
// it has returned a result
$group_id = $result->fetch_object();
$group_id++;
}

php Update sql and Query

I want to do a query in php, output the data on the page and then modify it in the database.
How do I do that?
Currently I do it like this but it dose not work:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM pics WHERE id = '$id'";
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
$dir = $row["dir"];
$likes = $row["likes"];
}
$sqlq = "UPDATE pics SET likes='$likes+1' WHERE id='$id'";
$conn->query($sqlq);
$conn->close();
But the like dose not add to the database.
If you echo your $sqlq out using
echo $sqlq;
you'll see that the '$likes+1' isn't doing what you expect.
You could really simplify it by doing
$sqlq = "UPDATE pics SET likes=likes+1 WHERE id='$id'";
which removes any risk of two users updating the database at teh same time overwriting each other.
But you should really check out using "parameterized queries" as that would solve all your problems (and may your queries safer). Check the examples in the manual http://php.net/manual/en/mysqli-stmt.bind-param.php

Issue with JOIN in PHP MySQL

Having a bit of a struggle here with adding JOINs to a query. I am connecting to two separate databases (on the same server). For this reason, I am writing this mysqli simply and will convert to a prepared statement once it's working.
// REMOVED: DB VARIABLES
$conn = new mysqli($servername, $username, $password, $db_connective_data);
if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); }
$conn2 = new mysqli($servername, $username, $password, $db_resources);
if ($conn2->connect_error) { die("Connection failed: " . $conn2->connect_error); }
$sql = "SELECT * FROM downloads LEFT JOIN resource_data ON downloads.resource_id_REF=resource_data.resource_id WHERE downloads.user_basics_id_REF='$user_id'";
$result = $conn->query($sql);
$number_of_download_rows_returned = mysqli_num_rows($result) -1;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resource_id_REF[] = $row['resource_id_REF'];
$download_date[] = date('Y-m-d', strtotime($row['download_date']));
$resource_title[] = $row['resource_title'];
$resource_title_link[] = str_replace(" ", "-", $row['resource_title']);
}
}
$conn->close();
A query without a JOIN works fine (albeit without returning the resource_title):
$sql = "SELECT * FROM downloads WHERE downloads.user_basics_id_REF='$user_id' ORDER BY downloads.download_date DESC";
What am I missing here? The first code sample will return no results. The second one will return three.
Any assistance is greatly appreciated.
Here is a list of the different database names that I reference. As I stated, some data is in the "connective_data" db and some is in the "resources" db.
$db_connective_data = "connective_data";
$db_lists = "lists";
$db_messaging = "messaging";
$db_resources = "resources";
$db_users = "users";
I can't seem to get two of them connected. Am I missing something strikingly obvious here?
There is no need to create 2 connections if the databases are located on the same mysql server. You can simply reference tables from another database as databasename.tablename.
As a result, you can join 2 tables from 2 different databases as:
$sql = "SELECT * FROM yourdatabase1.downloads LEFT JOIN yourdatabase2.resource_data ON yourdatabase1.downloads.resource_id_REF=yourdatabase2.resource_data.resource_id WHERE yourdatabase1.downloads.user_basics_id_REF='$user_id'";
Obviously, you need to substitute your real database names for yourdatabase1 and yourdatabase2 in the above query.
Update: Are you sure you need so many databases? These seem to be tables to me, not databases.

Categories