php
  • mysql
  • variables
  • if-statement
  • condition
  • 2013-05-04 12 views 5 likes 
    5

    Sto provando a fare un controllo prima che i dati vengano inseriti nella query MySQL. Ecco il codice;Se la variabile è uguale al valore php

    $userid = ($vbulletin->userinfo['userid']); 
    $sql3 = mysql_query("SELECT * FROM table WHERE ID='$_POST[hiddenID]'"); 
    
    while ($row = mysql_fetch_array($sql3)){ 
    
    $toon = $row['toonname']; 
    $laff = $row['tlaff']; 
    $type = $row['ttype']; 
    
    if ($type == 1){ 
    $type == "Bear"; 
    } elseif ($type == 2){ 
    $type == "Cat"; 
    } elseif ($type == 3){ 
    $type == "Dog"; 
    }    
    
    } 
    

    Tuttavia, questo non funziona. Fondamentalmente, ci sono diversi valori nella 'tabella' per ogni tipo. 1 significa Orso, 2 significa Gatto e 3 significa Cane.

    Grazie a chiunque possa aiutare a vedere un problema nel mio script!

    +2

    avete bisogno di imparare di più tra assigment '=', 'uguaglianza ==' e '' === operatori di identità – samayo

    +0

    utilizzare un array invece di 'if' . – hakre

    risposta

    14

    si confrontano, non assegnare:

    if ($type == 1){ 
        $type = "Bear"; 
    } 
    

    si confrontano i valori con == o ===.

    Assegnare valori con =.

    È possibile scrivere meno codice per ottenere lo stesso risultato, con una dichiarazione switch o solo un gruppo di if s senza lo elseif s.

    if ($type == 1) $type = "Bear"; 
    if ($type == 2) $type = "Cat"; 
    if ($type == 3) $type = "Dog"; 
    

    vorrei fare una funzione per esso, come questo:

    function get_species($type) { 
        switch ($type): 
         case 1: return 'Bear'; 
         case 2: return 'Cat'; 
         case 3: return 'Dog'; 
         default: return 'Jeff Atwood'; 
        endswitch; 
    } 
    
    $type = get_species($row['ttype']); 
    
    3

    Si utilizza == invece di =. Confronta la variabile con il nuovo valore. Utilizzare = per impostare il valore.

    if ($type == 1){ 
    $type = "Bear"; 
    } elseif ($type == 2){ 
    $type = "Cat"; 
    } elseif ($type == 3){ 
    $type = "Dog"; 
    } 
    
    1

    Stai usando == per assegnare valori:

    $type == bear;

    dovrebbe essere:

    $type = bear;

    0
    if ($type == 1) {$displayVar = "Bear";} 
    

    Esempio:

    <form method="post" action="results.php"> 
    How many horns does a unicorn have? <br /> 
    <input type="text" name="inputField" id="inputField" /> <br /> 
    <input type="submit" value="Submit" /> <br /> 
    </form> 
    

    Risultati:

    <?php 
    $inputVar = $_POST["inputField"]; 
    if ($inputVar == 1) {$answerVar = "correct";} 
    else $answerVar = "<strong>not correct</strong>"; 
    ?> 
    <?php 
    echo "Your answer is " . $answerVar . "<br />"; 
    ?> 
    
    Problemi correlati