2

How to get value from select query without using while loop while we know that output is defiantly only one record

$sql = "SELECT id FROM MyGuests";
$result = $conn->query($sql);
  while($row = $result->fetch_assoc()) 
    {
echo $row["id"];
    } 

Here if i know that there is only one record comes as a output then how to avoid while loop and directly get our id

1
  • 1
    Just remove the whole loop Commented Sep 29, 2016 at 9:37

3 Answers 3

1

just delete the while loop!

$sql = "SELECT id FROM MyGuests";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row["id"];

are you using mysql_* functions by any chance? please switch to PDO as soon as possible.

Sign up to request clarification or add additional context in comments.

1 Comment

Answer in last by @AddWeb Solution Pvt Ltd is in PDO format?
1

You can use MYSQl bind result if its a single row output

if( isset($con) && !empty($con) && $con!="" ) {
    $knownStmt=mysqli_prepare($con, "SELECT id FROM MyGuests");
    if( $knownStmt ) { 
        mysqli_stmt_execute($knownStmt);
        mysqli_stmt_bind_result($knownStmt,$id);
        mysqli_stmt_fetch($knownStmt);
        mysqli_stmt_close($knownStmt);
    }  
}

Please try this. This is one of the best way. You can also pass the where condition also and bind the value this query. Please see below is the example for the same.

if( isset($con) && !empty($con) && $con!="" ) {
    $knownStmt=mysqli_prepare($con, "SELECT name FROM MyGuests WHERE id=?");
    if( $knownStmt ) { 
        mysqli_stmt_bind_param($knownStmt,"d",$UID);
        mysqli_stmt_execute($knownStmt);
        mysqli_stmt_bind_result($knownStmt,$Name);
        mysqli_stmt_fetch($knownStmt);
        mysqli_stmt_close($knownStmt);
    }  
}

I'm sure this will definitely help you. Please note this works only for single row result.

Comments

0

You can use this code for your purpose.

  $result = mysql_query("SELECT id FROM MyGuests");
  $row=mysql_fetch_array($result);
  echo $row["id"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.