Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Example of use IF in PHP

Tags:

html

php

I created this simple Php example to begin my study.

This is Index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Prova</title>
</head>
<body>
<form action="script.php" method="get"/>
<table>
    <tr>
        <td>Cognome</td>
        <td><input type="text" name="cognome" id="cognome"/></td>
    </tr>
</table>
<table>
    <tr>
        <td><input type="submit" value="Invia"/></td>
    </tr>
</table>
</form>
</body>
</html>

This is script.php:

<?php
    $cognome = $_REQUEST['cognome'];
    if ($cognome = "Giacomo" )
        {
        echo "<p><img src='Giacomo.jpg'<p>/>";
        }
    else 
        {
        echo "<img src='IMG.jpg'<p>/>";
        }
?>

Its run, but if i write Giacomo show Giacomo.jpg and image.jpg. I want only Giacomo.jpg.

Thanks

like image 967
Francesco Irrera Avatar asked May 02 '15 15:05

Francesco Irrera


2 Answers

You have at least two options:

1) Use the === or == operator

<?php
  $cognome = $_REQUEST['cognome'];
  if ($cognome === "Giacomo")
  {
    echo "<p><img src='Giacomo.jpg'<p>/>";
  } else {
    echo "<img src='IMG.jpg'<p>/>";
  }
?>

2) Use the strcmp function:

<?php
  $cognome = $_REQUEST['cognome'];
  if (strcmp($cognome,"Giacomo") === 0)
  {
    echo "<p><img src='Giacomo.jpg'<p>/>";
  } else {
    echo "<img src='IMG.jpg'<p>/>";
  }
?>

I hope I have helped you in it.

like image 21
Caio Ladislau Avatar answered Oct 01 '22 14:10

Caio Ladislau


You are assigning $cognome = "Giacomo" in the if statement (which is evaluated to true after that), you should compare with == or === instead:

if ($cognome === "Giacomo")
   echo "<p><img src='Giacomo.jpg'></p>";
else
   echo "<p><img src='IMG.jpg'></p>";

P.S. It should be <p></p> and <img >.

like image 125
potashin Avatar answered Oct 01 '22 13:10

potashin