PHP fetch MAX values from MySQL table for each different user - php

I have a table with many different users on my website. They upload the picture. How can I display the last uploaded picture with the highest ID number?
If I do this query:
SELECT user_name, MAX(pictid) FROM `pictures` GROUP BY user_name;
It works in PHP My Admin, but it returns empty result on the website.
Username is written correctly, just ID part is empty. Why is that? That is my code:
include('connection.php');
$sql = "SELECT user_name, MAX(pictid) FROM `pictures` GROUP BY user_name;";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>". $row["user_name"] . "</td><td>". $row["pictid"] . "</td><td><img style='width:90px;' src='../uploads/".$row["picture"]."'</td><tr>";
}
}

When using functions like MAX(), SUM(), COUNT() etc, MySQL will return those values with a different name (so it won't collide with other column names you have in the query).
So in your case, instead of $row["pictid"], it should be $row["MAX(pictid)"].
However, since you're not selecting the pictid "as is", you can alias that function:
SELECT user_name, MAX(pictid) as pictid FROM `pictures` GROUP BY user_name
(note the as pictid in the query above)
Now you can fetch the value using:
$row['pictid']
Side note:
I would recommend that you display all errors and warnings while developing in your local environment. In this case, you should have gotten a warning about undefined index/array key pictid, which would have helped you debugging the problem.
And don't forget the fix the broken <img> tag as #brombeer pointed out in the comments to your question.

Related

How to store a selected value from a MySQL stored procedure into a variable in PHP?

Basically, I want to take a value from running a stored procedure that randomly generates a number, and use it later on in the website. Eventually, I'm going to need to pass that randomly generated number back to the MySQL database depending upon the actions that the user takes.
Stored Procedure:
BEGIN
SET #leftplayerone = 0;
SET #rightplayerone = 0;
SET #leftplayerone = (SELECT FLOOR(RAND()*((SELECT COUNT(*) FROM
Players)-1+1))+1);
WHILE #rightplayerone = 0 OR #rightplayerone = #leftplayerone
DO
SET #rightplayerone = (SELECT FLOOR(RAND()*((SELECT COUNT(*) FROM
Players)-1+1))+1);
END WHILE;
SELECT #leftplayerone;
SELECT #rightplayerone;
END
I have a separate table that includes a number of players. I want to randomly pull 1 player from that table and then display that player on my website. Then, I want to randomly display a different player from that same table. The user should then be presented with these two randomly generated players and then choose an option presented to them with 5 different buttons. I want to then send that response, along with the two players that were randomly generated back to the database to store that information.
I'm just looking for some help on how to pull the two randomly generated players from the stored proc and display that on the site - I just put the rest of the details for context.
Update:
My PHP code is:
<?php
$sql = "CALL FantasyUnited.GetRandomPlayersForTradeProposal();";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>". $row["PlayerOne"] ."</td><td>". $row["PlayerTwo"] ."
</td></tr>";
}
echo "</table>";
}
else {
echo "0 result";
}
$conn-> close();
?>
I am now able to display the random Player IDs - now I need to figure out how to display the player's name that correlates to the player ID instead of just displaying the ID number. Then save that information and pass it back to the database when a user clicks on a button regarding those two players.
http://pr0digy.me/trades.php
The user will select one of the options (buttons) below the names of the players. I want the button they pushed and the names of the players stored and sent back to the database.
Change the last line of the procedure to:
SELECT #leftplayerone AS leftplayer, #rightplayerone AS rightplayer;
so that you can fetch both results at once in PHP.
Then in PHP you can do:
$result = $pdo->query("CALL yourProcedure");
$row = $result->fetch(PDO::FETCH_ASSOC);
$leftplayer = $row['leftplayer'];
$rightplayer = $row['rightplayer'];
This is PDO syntax, the corresponding mysqli syntax is not very different.

How can I select all id's from a sql table in descending order and then echo them (in php)?

I have several id's in a table called "leaderboards" that belong to different users. They're named as:"id_user" and they're not in order. What I want to do is printing divs in a leaderbord which should contain some info that I get from those id_user's.
The only problem I have about it is that after a research on stackoverflow and other websites, I still couldn't find how to select those id_user's in descending order AND be able to take one by one to get the info from that user and then continue with the next id_user, and so on.
I don't know how to select the specific row of each id_user in descending order to do the other codes that I already know how to do.
I hope it's not a duplicate of any other previosly asked question on this website (I really did a research and I couldn't find any specific answer to this question, for the sql part and the php part all together).
Thank you so so much beforehand.
An INNER JOIN between your tables will achieve what you intend.
SELECT *
FROM users
JOIN leaderboards WHERE users.id = leaderboards.id_user
ORDER BY users.id DESC
In each returned row, you will get the columns from both your users and leaderboards tables, so loop over the result and echo the information from the user you need.
$query = 'SELECT...';
$res = mysqli_query($query);
while ($row = mysqli_fetch_assoc($res)) {
echo '<div>'.$row['id'].' - '.$row['username'].' - '.$row['image'].'</div>';
}
You could do with a good read up on both PHP and MySql but I'll give you a clue.
EDIT
$query = "SELECT * FROM `the_name_of_your_table` ORDER BY `user_id` DESC;";
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
print $row["user_id"] . " - " . $row["username"] . "<BR>";
}
/* free result set */
mysqli_free_result($result);
}

Double mysql_fetch_array (get information from the other table to get data) / nest

I tried searching for this question, but theirs is a different error. I'm using PHP 5.2 for some reason.
What I'm trying to do is, get the mysql_fetch_array from one table, then use a column of that table to get a row from another table.
Here is my code (Advanced apologies for the horrible format)
$sql = mysql_query("SELECT * FROM testimonies WHERE visibility != 'Hide' ORDER BY date_submitted DESC");
$testimonyCount = mysql_num_rows($sql); // count the output amount
if ($testimonyCount > 0) {
//get data 'testimonies' table
while($info = mysql_fetch_array($sql)){
$username = $info['username'];
//Get id (in admin table) where username = username (in testimonies table)
$userid = mysql_query("SELECT * FROM admin WHERE username = $username LIMIT 1");
while($user = mysql_fetch_array($userid)){ $id = $user['id'];}
$testimonies .= "<div class='row'><div class='col-lg-2'><center>
<img src='Pictures/Profile_Pictures/".$userid['id'].".jpg' width='160' height='160'>
<br>".$info['username']."</center></div><div class='col-lg-2'><center>
<img src='back/inventory_images/34.jpg' width='160' height='160'><br>"
.$info['product_used']."</center></div><div class='col-lg-8'><center><u>(Date: "
.$info['date_submitted']." - Ordered from our branch in <strong>"
.$info['branch_ordered']."</strong>, City)</u></center>".$info['testimony']."
</div></div><br>";
}
}
else {
$testimonies = "No one has submitted their testimonies yet.";
}
So you see, my table "testimonies" have a column of 'username' and so is the "admin" table.
What' I'm trying to do is get the row of the username (in admin table) where the username is the
same as the one in the "testimonies" table. I used the information from the 2nd table in line 14 for the image src.
Unfortunately it gives me this error:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/_____/public_html/Testimonies.php on line xx
Notice: Undefined variable: id in /home/_____/public_html/Testimonies.php on line xx
Other's from what I've searched get their data on the first loop, but I don't get anything at all. The 2nd loop is certainly a problem. Help.
Thanks.
First I'll mention that it's a really bad idea to build queries in a such a way that they can be looped. As is for each of your testimonies you're executing another query to get the admin info. So for 10 testimonies you're hitting MySQL 10 times [ +1 for the original query ]. You generally want to get in, get your data, and get out.
So the better way to handle this is to let MySQL do it for you, with a join :
SELECT *
FROM testimonies inner join admin on testimonies.username = admin.username
WHERE visibility != 'Hide'
ORDER BY date_submitted DESC
The above will only return you testimonies with a matching admin. If you wanted to return testimonies even if they don't have an admin you'd want an outer join. You'd replace inner join admin with left outer join admin
So remove your second while loop and try that.
Also, the mysql_ functions are deprecated .. so you shouldn't be developing new code using them. Try and get my change to work as-is but you should consider looking at PDO [ Why shouldn't I use mysql_* functions in PHP? ].

Why is this PHP-MySQL code not working properly?

It was working before and maybe someone made changes to the code and I cant detect the problem after much debugging so hopefully someone can help.
I have an html form that lets a user choose a set of option and then on form submit, POSTS these options in an array which works perfectly fine. Then I am writing the elements of an array to a MySQL table and this is where the problem occurs. My code was working fine before but now its all weird. The outputs mix up for some reason.
Below is the array values passed and then the output below the arrays.
Here is my code that writes the array values to MySQL:
error_reporting(-1);
$arr=$_POST["itemsToAdd"];
$cal=$_POST["calendar"];
print_r($arr);
// Make a MySQL Connection
//empty table first to remove any previous old on-calls stored.
$query = "truncate table ProdOnCallSetup";
if(mysql_query($query)){
}
else{
}
foreach ($arr as &$value) {
// Insert a row of information into the table "ProdOnCallSetup"
mysql_query("INSERT INTO ProdOnCallSetup
(Email) VALUES('$value') ")
or die(mysql_error());
}
Here is the code giving the output or displaying the rows in MySQL:
<ol class=”list_style”>
<?php
//make MySQL connection
$query = "SELECT * FROM ProdOnCallSetup";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
echo "<li>".$row['Email']."</li>";
echo "<br />";
}
?>
</ol>
See the problem here? Even though I write them in the correct order in MySQL when I display them the order mixes up. Order is Justin, Achau, Chellatamby but when I echo is out from the DB its Achau, Chellatamby, Justin
Unless you specifically use an ORDER BY clause in your SELECT statement, the order in which rows are returned is indeterminate and may change.... it doesn't matter what order you added the records in, this is irrelevant... use ORDER BY...
SELECT * FROM ProdOnCallSetup ORDER BY Email
(or whatever column id you want to order them on)
If you want to order them in the order you added them to the database, you'll need an autoincrement column on the table, and order by that column

mySQL fetch column based on another column in PHP

I'm trying to write my first PHP script with mySQL and I desperately need some help. I'm sure this is relatively simple, but if I have one field in my table (username, for example), and I want to fetch another field (name, for example), that is in the same row as the given username, how do I do that?
Again, I'm sure this is easy, but I'm lost, so I'd really appreciate any help. Thanks!
$sql = "SELECT username, name FROM table";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
echo "This {$row['username']} has the name {$row['name']}\n";
}
halfdan's answer sort of works, but it fetches all rows and displays them. What you want is a WHERE clause, which lets you filter the contents of the table so the query only returns the row(s) you want:
SELECT username, name
FROM sometable
WHERE (username = 'johndoe');
This will return only the rows where the username field is equal to 'johndoe'. Conceptually, it's equivalent to:
$results = mysql_query("SELECT username, name FROM table");
while($row = mysql_fetch_assoc($results)) {
if ($row['username'] == 'johndoe') {
// do something, this is a row you want
} else {
// not a row you want. ignore it, or deal with it some other way
}
}
the main difference is that for large data sets in the database, doing client-side filtering like this is expensive, as the entire contents of the table has to be transferred over. Using a WHERE clause to limit things to just what you want is far more efficient in the long run.

Categories