在mysql查询中使用if else

时间:2012-03-27 09:44:57

标签: php mysql if-statement

我会简短地说:有谁能告诉我为什么这不起作用? “else”部分工作,if位不起作用。

<?php

$sql2 = mysql_query("SELECT * FROM products_new WHERE id='" . $result['id_kit'] . "'");

    while($row = mysql_fetch_assoc($sql2)){

    if ($result['id_kit'] == 0) {

            ?>

            //DO THIS BIT IF $result['id_kit'] IS "0". 

            <?php
            }

    else {
            ?>

            //DO THIS BIT IF $result['id_kit'] IS ANYTHING OTHER THAN "0".  THIS BIT WORKS FINE

    <?php
    }
?>
<?php
    }
    ?>

2 个答案:

答案 0 :(得分:2)

你最好使用:

<?php while($row = mysql_fetch_assoc($sql2)): ?>
    <?php if (statement): ?>
        some html here.
    <?php else: ?>
        some html.
    <?php endif; ?>
<?php endwhile; ?>

阅读和理解更容易。

它不起作用,因为$result['id_kit'] != 0

答案 1 :(得分:1)

更改以下内容

更改

                    $sql2 = mysql_query ( "SELECT * FROM products_new WHERE id='" . $result ['id_kit'] . "'" );

                <?php 
                    while ( $row = mysql_fetch_assoc ( $sql2 ) ) {

                    $sql2 = mysql_query ( "SELECT * FROM products_new WHERE id='" . mysql_real_escape_string($result['id_kit']) . "'" );
                    while ( $row = mysql_fetch_assoc ( $sql2 ) ) {

更改

if ($result['id_kit'] == 0) {

if (empty($row)) {

你应该有一个有效的代码

由于 :)