开发者

using while statement for each individual result of a mysql query

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 t开发者_运维百科hat 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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜