0

I'm unsure whether to use 'while' or 'for each' for this code.

I have a mysql query that will bring back more then one result.

I then, for each result, want to do a certain thing if $row[number] is empty or not

I have this:

$sql = "SELECT * FROM $tbl_name WHERE username=\"$myusername\"";
$result=mysql_query($sql);
$numResults = mysql_num_rows($result);
if ($numResults = 0) {
header ("Location: /sms_error.php?error=no_adders");
}
while($row = mysql_fetch_array($result)) {
$number1=$row["number"];
if (!empty($number1)) {


}

if (empty($number1)) {


}

This is coming up with completely blank for $number1 (even though there is data on the db).

Everything up to that is correct, $myusername and the mysql query doesn't return empty.

So should it be mysql-fetch-assoc or -array and should it be while or for each??

thanks, Niall

2 Answers 2

1

First, you have problem in this line of code:

if ($numResults = 0) {
    header ("Location: /sms_error.php?error=no_adders");
}

This is always false - you are not comparing, you are assigning 0 to $numResults. Change that to == and see if you are having any rows pulled out with your query.

while($row = mysql_fetch_array($result)) {
$number1=$row["number"];
//...
}

This is a valid syntax, as I can see. Try to call var_dump($row) to see contents of $row array.

Edit:

Oh, yeah - instead of this:

$result=mysql_query($sql);

do this:

$result=mysql_query($sql) or die(mysql_error());

One more suggestion - you should always call exit(); after header("Location: ..."); to prevent executing code after redirect line in your script, because header only asks user browser to redirect.

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

1 Comment

:) == I am not awake, cheers, there's a problem with my db, it's not the code. Thanks anyway thoug
0

Everything up to that is correct, $myusername and the mysql query doesn't return empty

I'm hoping that you've trimmed down the code to demonstrate what it is intended to do; i.e. that the real code contains sensible comments and error handling. If not, then how do you know if you are getting any data back from the server? Also, you've got an assignment instead of a comparison when checking the number of rows in the result set:

if ($numResults = 0) {

You need a loop based on the availability / number of rows returned by the query to fetch the data from the result set - you cannot use foreach() for this.

As to whether you should use _fetch_array() or _fetch_assoc() the answer should be obvious.

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.