-4

I have 3 meals in the database. When I display my query it shows 3 prices. How do I only show one result instead?

$result = mysqli_query($con, "SELECT meal, price FROM Meals");

while  ($row = $result->fetch_assoc())  {
    echo '<input name="price" type="text" value="'.$row['price'].'" />';
}
Tim S.
  • 13,597
  • 7
  • 46
  • 72
  • 1
    don't use `while` **OR** use `limit` – Sumit Bijvani Apr 04 '13 at 11:46
  • 2
    @SumitBijvani Why would you even suggest just not using while? If his data scales and selects 50,000 rows, now he's wasting time and resources selecting those rows when he only needs one. – Luke Shaheen Apr 04 '13 at 11:48
  • 2
    I've edited this question to make it a *genuine* question. There's no need to vote it down or try to close it. It's nice to see some people following SO's rules, but there's no need to instantly judge a question if a very small edit can make it a valid question. – Tim S. Apr 04 '13 at 11:54
  • Have any of these answers worked for you? If so, please mark the question as answered. If not, can you please tell us why they aren't working and how we can help? – Luke Shaheen Apr 05 '13 at 11:52

4 Answers4

3

You'll want to use the MySQL LIMIT clause.

$result = mysqli_query($con, "SELECT meal, price FROM Meals LIMIT 1");

From the MySQL manual:

With one argument, the value specifies the number of rows to return from the beginning of the result set.

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return.

Community
  • 1
  • 1
Luke Shaheen
  • 4,262
  • 12
  • 52
  • 82
1

The proper query would be

$result = mysqli_query($con, "SELECT meal, price FROM Meals GROUP BY meal HAVING meal = "mealname" ");
Patrick Aleman
  • 612
  • 6
  • 19
-1

if you want to show any one out three then use

$result = mysqli_query($con, "SELECT meal, price FROM Meals LIMIT 1");
 if  ($row = $result->fetch_assoc())  {
        echo '<input name="price" type="text" value="'.$row['price'].'" />';
       }

if you want to show a specific one then use id or any primary key in your query. like

$result = mysqli_query($con, "SELECT meal, price FROM Meals WHERE id='your id or primary key value' LIMIT 1");
 if  ($row = $result->fetch_assoc())  {
        echo '<input name="price" type="text" value="'.$row['price'].'" />';
       }

in short use your query according to what kind of result do you want.

Tashen Jazbi
  • 1,068
  • 1
  • 16
  • 41
-1

Use this query to show one price for one meal. $result = mysqli_query($con, "SELECT meal, price FROM Meals WHERE meal = "mealname" "); while ($row = $result->fetch_assoc()) { echo '<input name="price" type="text" value="'.$row['price'].'" />'; }

Monomita
  • 27
  • 2
  • 7