0

I want to select row by row and set to array in MYSQL

I have this code:

  public function getWinnerBonus($email){
    $result = mysql_query("SELECT * FROM winers WHERE `email` = '$email'") or die(mysql_error());
    // return user details
    if ($result){
        $respons               = mysql_fetch_array($result);
        $response["error"] = FALSE;
        $response["WinnerInfo"]["price"] = $respons["price"];
        $response["WinnerInfo"]["level"] = $respons["level"];
        $response["WinnerInfo"]["win_date"] = $respons["win_date"];
        $response["WinnerInfo"]["payed"] = $respons["payed"];
        $response["WinnerInfo"]["pay_date"] = $respons["pay_date"];

    }else{
        $response["error"] = TRUE;
    }
    return $response;
}

but this code return just first founded row

How to select row by row and set to array in MYSQL?

2
  • Sidenote: GROUP BY comes after a WHERE clause in a SELECT. dev.mysql.com/doc/refman/5.0/en/select.html - Your mysql_error() should have thrown you a syntax error, but you didn't share that with us. Commented Oct 30, 2015 at 12:02
  • "but this code return just first founded row" - I sincerely doubt that. Commented Oct 30, 2015 at 12:07

2 Answers 2

1

You need to loop over the result set not just one time.

$respons = array();
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
  $respons[$i]["error"] = FALSE;
  $respons[$i]["WinnerInfo"]["price"] = $row["price"];
  $respons[$i]["WinnerInfo"]["level"] = $row["level"];
  $respons[$i]["WinnerInfo"]["win_date"] = $row["win_date"];
  $respons[$i]["WinnerInfo"]["payed"] = $row["payed"];
  $respons[$i]["WinnerInfo"]["pay_date"] = $row["pay_date"];
  ++$i;
}

Note: Never use mysql_ functions, they are deprecated. Use mysqli_ or PDO instead, along with a prepared statement.

References:

Also make sure that you have successfully connected to your database using the same API as your query.

Different MySQL APIs do not intermix.

Consult the following:

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

3 Comments

while ($row = mysql_fetch_assoc($result)) I think that should read as while ($respons= mysql_fetch_assoc($result))
GROUP BY comes after a WHERE clause. That I know for sure. dev.mysql.com/doc/refman/5.0/en/select.html
Tank you @Fred-ii- , but I got error: Notice: Undefined index: win_date in
0

Yes, because you have to loop over the result set. Here is how you could do it:

$resultArray = array();
while($response = mysql_fetch_array($result, MYSQL_NUM) {
    $resultArray[] = $response; //This adds one result set to the array
}

I hope I could help you.

1 Comment

Undefined variable 'response'

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.