-1

I am trying to echo the data once in one field. However it is looping and i'm not sure what to change to make it echo once. Does anyone know how? Here is the code:

<?php

$email = $_POST['email'];

$servername = "localhost";
$username =  "root";
$password = "";
$dbName = "users";

//Make Connection
$conn = new mysqli($servername, $username, $password, $dbName);
//Check Connection
if(!$conn){
    die("Connection Failed. ". mysqli_connect_error());
}

$sql = "SELECT `profilepicurl` FROM users WHERE `email`='".$email."'";
$result = mysqli_query($conn ,$sql);


if(mysqli_num_rows($result) > 0){
    //show data for each row
    while($row = mysqli_fetch_assoc($result)){
        echo $row['profilepicurl'];
    }
}

?>

Thanks!

zigg76
  • 55
  • 1
  • 7
  • 1
    Add `break;` after `$row['profilepicurl'];` – Keeleon Apr 29 '16 at 20:42
  • 5
    You're using a **while loop**! Why use it if you don't want to loop? – AbraCadaver Apr 29 '16 at 20:42
  • 2
    [Little Bobby](http://bobby-tables.com/) says [your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Apr 29 '16 at 20:48

3 Answers3

1

This is quite simple!

Change while($row = mysqli_fetch_assoc($result)){ to $row = mysqli_fetch_assoc($result){

The Codesee
  • 3,714
  • 5
  • 38
  • 78
0

Remove the while() loop and the braces:

if ( mysqli_num_rows($result) > 0 ) {

    //show data for each row
    $row = mysqli_fetch_assoc($result);

    echo $row['profilepicurl'];
}
mferly
  • 1,646
  • 1
  • 13
  • 19
0

The correct way to stop a loop is using break:

if(mysqli_num_rows($result) > 0){
    //show data for each row
    while($row = mysqli_fetch_assoc($result)){
        echo $row['profilepicurl'];
        break;
    }
}

Although, if you just need 1 value, you can remove the while loop and use only:

$row = mysqli_fetch_assoc($result);
echo $row['profilepicurl'];

Notes:

Your script is unsafe due to the possibility of sql injection, make sure you read how can i prevent sql injection in php.

Community
  • 1
  • 1
Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268