-4

When I try to do it it fetches the entire column, not just one field.

$connection = mysqli_query($db, "SELECT * FROM users");




<?php
while($row = mysqli_fetch_array($connection)) {
?>
<p>Your balance is: <?php echo $row['balance']; ?></p>
<?php
}
?>

That was outputting Your balance is: 5 Your balance is: 0 Your balance is:

So I tried

$query_for_selecting = mysqli_query($db, "SELECT balance FROM users");


<?php if (mysqli_num_rows($query_for_selecting) > 0) { ?>
<?php while($row = mysqli_fetch_assoc($query_for_selecting)) { ?>
<p>Your balance is <?php $row['balance']; ?></p>
<?php } ?>
<?php }  ?>

And that wasn't outputting anything so eventually, I tried using a WHERE clause and a limit of 1

$query_for_selecting = mysqli_query($db, "SELECT * FROM users WHERE balance = '3' DESC LIMIT 1");
<?php if (mysqli_num_rows($query_for_selecting) > 0) { ?>
<?php while($row = mysqli_fetch_assoc($query_for_selecting)) { ?>
<p>Your balance is <?php $row['balance']; ?></p>
<?php } ?>
<?php }  ?>

All I got was a white screen

mark
  • 53
  • 5
  • To clarify: you only want to output the `balance` for a single user, rather than for all users returned by your query? – rickdenhaan Mar 12 '20 at 23:03
  • @rickdenhaan yeah! – mark Mar 12 '20 at 23:37
  • Ok so, if you just want to fetch the balance for a single user, how is your program going to know which user to select? it's unclear, from what you've written. Do you want to get the ID of the currently logged in user, perhaps? Or an ID submitted from a form, or in the querystring, maybe? – ADyson Mar 12 '20 at 23:56
  • *"it fetches the entire column"* - What do you mean by that exactly? What you posted as a looping method only contains the 1 column. What are we not understanding? Could even be the `$i++;` adding to this. Something's missing here. – Funk Forty Niner Mar 12 '20 at 23:56
  • @ADyson I initially wanted to display the balance of the user that's logged in, but that didn't work out. – mark Mar 13 '20 at 00:06
  • 1
    *"I initially wanted to display the balance of the user that's logged in, but that didn't work out."* - About that. So I was right. That's what I posted in my answer below. If it didn't work, then maybe your query was wrong, or there were errors. @markthedark – Funk Forty Niner Mar 13 '20 at 00:07
  • 1
    @markthedark _"that didn't work out."_ .... ok. So help us out...in your application, how do you know a user is logged in? Is it from the Session? And what did you try in order to fetch a single user's data? It's hard to fix your code or pinpoint the problem if we don't know what you wrote, or what went wrong exactly. – ADyson Mar 13 '20 at 00:12
  • @ADyson Lord as my witness, we are trying but have yet to have gotten a response to [my first comment](https://stackoverflow.com/questions/60662866/cant-fetch-a-single-field-from-database#comment107327580_60662866), where I even had time submitting an answer while waiting, go figure *lol!* I think I'm going to go watch a bit of TV; I won't be too far. – Funk Forty Niner Mar 13 '20 at 00:17
  • 1
    _"All I got was a white screen"_ ok, so firstly are there any rows in the database where someone's balance is exactly 3? Also since it's a number, did you try with `balance = 3` instead of `balance = '3'` (the quote marks make it a string)? Lastly, a white screen _can_ be a symptom of a crash, if you don't have error reporting switched on. As per my comment on the answer below, please confirm you have switched on reporting and/or logging successfully, and whether you get any errors reported (either on screen or in the nominated log file) once you've done that. – ADyson Mar 13 '20 at 10:33
  • ... See https://stackify.com/php-error-logs-guide (php error logging/reporting) and https://stackoverflow.com/a/14578644/5947043 (mysqli exception handling) for guidance on setting up error handling correctly. – ADyson Mar 13 '20 at 10:33
  • BTW as a general code quality point, if you have several lines of PHP next to each other, you don't have to start a new `` at the start and end of each _group_ of lines. – ADyson Mar 13 '20 at 10:35
  • Oh I just noticed too, another, simpler reason it might not show anything is because you aren't echoing anything! You've written ``, but in your original version you wrote ``. Spot the difference? It's unclear why you changed that. – ADyson Mar 13 '20 at 10:36
  • @ADyson No there aren't, but I changed it to 5, and I didn't realize it was a string, thank you for pointing that out. Also, I didn't actually realize that I didn't echo it, so I echoed it and it was outputting the entire column – mark Mar 13 '20 at 11:09
  • Ok. So it's a bit unclear what the end goal is though. Do you still want to output the data for a specific user? If so we need to go back to my original question about how you are going to decide which user that is. You never clarified that, as far as I can see. (I'm not sure if there's any value in restricting it to users with a specific balance, unless that's useful to you somehow?). – ADyson Mar 13 '20 at 11:56
  • Yeah, I want to output the balance for a specific user/the user that is logged in – mark Mar 13 '20 at 12:03
  • 1
    Ok so again I'll repeat my earlier question: in your application, how do you know a user is logged in? Is it from the Session, perhaps? That's quite common. But we don't actually know how your application is set up. And also, is there a specific column within your `users` table which contains the user ID? Basically you'll need to write a `WHERE` clause in your SQL which tries to match the logged-in user ID from the application with a user ID value in that column. I can't be more specific than that without more detailed info from you. – ADyson Mar 13 '20 at 13:45
  • It is from the session. Yeah there is a column that contains the user id – mark Mar 13 '20 at 14:30
  • @markthedark Seeing the new comments after revisiting the question, you appear to be relying on sessions and assigning them somewhere for a particular user. [See this Q&A](https://stackoverflow.com/q/5489365/1415724) here on Stack on using sessions. The balance column should be a type where math can be performed, such as `int` (integer) and removing the quotes around the integer in the query as previously stated. If something failed, again; please use the links I left in my answer to check for errors. There isn't much else that I can do for you, not without creating something. – Funk Forty Niner Mar 13 '20 at 14:57
  • Right so you're going to want a query along the lines of `SELECT balance FROM users WHERE userid = ?` . And then use prepared statements and parameters to add the value of `$_SESSION["userid"]` (or whatever you've called it) as a parameter to the query (so it gets inserted by the DB server instead of the ? when the query executes). See https://phpdelusions.net/mysqli to know how to use prepared statements properly - this is important when you're not just hard-coding the query, you need to move away from using mysqli_query at that point. – ADyson Mar 13 '20 at 15:50

2 Answers2

2

I have a feeling as to what's going on. You're fetching the entire database without either using a LIMIT of 1 and/or use a WHERE clause, given that you have unique ID's somewhere for columns. I am sure that you have more than the one record in your database table.

I was going to post this in a comment but decided not to. Stack doesn't really want us to do that, (edit) and at this point, it is way too long for a comment.

@ADyson "I initially wanted to display the balance of the user that's logged in, but that didn't work out." – markthedark

About that. It seems that what you are looking for is to get the balance for a user/record in particular. For that, you definitely need to use a WHERE clause.

If your query failed, enable error reporting and checking for errors on the query.

References:

Plus, the $i = 0; and $i++; may not be helping. It's hard to say what that is supposed to do. I know the syntax, I just don't know why you're wanting to increase it.

Side note: I would avoid in using $connection as a query variable assignment. It could be confusing. Try to use something clear like $query_for_selecting.

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • Whenever I try to use a LIMIT of 1 or a ```WHERE``` clause it ends up just not even outputting anything. – mark Mar 13 '20 at 09:31
  • 1
    @markthedark that's not really enough info for anyone to help you. Please [edit your question](https://stackoverflow.com/posts/60662866/edit) to show an example (or examples) of **exactly** what you tried, and exactly what the result was. (If it doesn't output **anything**, it's possible that PHP has crashed for some reason. Ensure you've got error logging switched on to avoid that, and so you can see what might be going wrong. See https://stackify.com/php-error-logs-guide/ (php error logging/reporting) and https://stackoverflow.com/a/14578644/5947043 (mysqli exception handling) for guidance – ADyson Mar 13 '20 at 09:48
2

I think a basic little tutorial might be in order here.

First off: SELECT * FROM users means: "give me everything in the users table". You will get the full table, every row and every column.

while($row = mysqli_fetch_array($connection)) will loop through every row your query returns. It will call mysqli_fetch_array() and put the result in $row until there are no more rows in your query's result.

If you only want to output a single row of data, you have three options:

  • Add a WHERE condition so that your query will only fetch a specific row
  • Add a LIMIT clause so that your query will only fetch a single row
  • Call mysqli_fetch_array() only once instead of in a while loop

From the comments in the discussion thread, it looks like you want to retrieve only the balance for the currently logged in user, and you have a session variable somewhere that tells you who that user is. That means you'll want to use a WHERE condition so that your query will only fetch the row for that specific user.

You haven't told us what that session variables is called or what the name is of the column in the users table that you can compare that session variable with, so I'll assume that your users table has an id column and your session variable is called user_id and should match the id value from your users table.

So let's say the user with id 123 is currently logged in. You'll want to end up with the query SELECT balance FROM users WHERE id = 123.

The quick solution is to change your code to:

$connection = mysqli_query($db, "SELECT balance FROM users WHERE id = " . $_SESSION['user_id']);.

This is bad code. We'll make it better, but try this first and see if it gets you the result you actually want. If it doesn't, let me know.

The reason this is bad code is because adding variables to a query string like this dramatically increases the risk of SQL injections. If there's any possibility at all that the value of the variable comes from user input, then at some point a user will figure that out and make sure it contains something that will break your application.

  • Best case scenario: the page simply won't render for that one user.
  • Bad case scenario: the user will be able to read out your entire database and will sell sensitive user data to the highest bidder.
  • Worst case scenario: the user will be able to inject some of their own Javascript code into your database in a column you're not sanitizing before rendering, letting them capture and intercept passwords and/or financial information your users are entering on your site and they will then use that information to make life miserable for all of your users.

So you don't want to just drop $_SESSION['user_id'] into your query like that. Instead, you'll want to use a prepared statement and let the database handle the problem of dropping the variable into the query.

First, you'll need to prepare your query:

$statement = mysqli_prepare($db, "SELECT balance FROM users WHERE id = ?");

The ? symbol is a placeholder where you can bind a parameter. Let's do that:

$statement->bind_param("i", $_SESSION['user_id']);

The "i" tells MySQL that you're binding an integer value. If you're not matching against a user id but a username, for example, you'll want to instead use "s" to tell MySQL you're binding a string value.

Now you can execute the query and get the result. Putting it all together:

$statement = mysqli_prepare($db, "SELECT balance FROM users WHERE id = ?");
$statement->bind_param("i", $_SESSION['user_id']);
$statement->execute();
$connection = $statement->get_result();

Let us know if that works. Some tweaking might be required.

rickdenhaan
  • 10,857
  • 28
  • 37