3

When using MySQLi, do I have to perform a kind of while loop where the actual data from the query is put into a variable array?

$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);

// Check if able to connect to database
if ($conn->connect_error) {
  trigger_error("Database connection failed: "  . $conn->connect_error, E_USER_ERROR);
}

$sql = "SELECT name FROM users WHERE email = '$email'";

$rs = $conn->query($sql);
$numRows = $rs->num_rows();

I always do the following:

$rs->data_seek(0);
while($row = $rs->fetch_assoc()) {
    $name = $row['name'];
}

echo $name;

Isn't there a much more convenient way to echo the data form the query when there is only one row?

1 Answer 1

9

If there is only one row, you don't need the loop. Just do:

$row = $rs->fetch_assoc();
$name = $row['name'];
Sign up to request clarification or add additional context in comments.

3 Comments

Is it possible to just pick one out the fetch or do one have to fetch all? Example: $name = $rs->fetch_assoc('name');
One fetch fetches one complete row, not only just one column. But then you can grab only the required columns from its result.
@Andreas: Nope, it isn't. If you're trying to shorten the code, you can just do echo $rs->fetch_assoc()['name'] (works on PHP 5.4+). Unrelated: $numRows = $rs->num_rows(); in your code needs to be $numRows = $rs->num_rows;.

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.