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
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 >
.
You need to use ==
for comparison, not =
and you should fix your HTML
tags like so:
<?php
$cognome = $_REQUEST['cognome'];
if ($cognome == "Giacomo" )
{
echo "<p><img src='Giacomo.jpg'></p>";
}
else
{
echo "<p><img src='IMG.jpg'></p>";
}
?>
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 notulysses mentioned, using $cognome = "Giacomo"
will set the variable (even in an if statement) because of the single =
Using ==
is an evaluation, used to question and compare values of the two objects on either side of the ==
but it only compares the value, not the type.
Comparing the value and type is done with ===
So for example;
$number1 = 5;
$number2 = "5"; //notice the quotes
if ($number1 == $number2) { echo "true"; } else { echo "false"; }
// this will echo true
However
$number1 = 5;
$number2 = "5";
if ($number1 === $number2) { echo "true"; } else { echo "false"; }
// this will echo false`
The reason for this is $number1
is evaluated as a number, while $number2
is a string because of the quotes.
Another thing I see in your code is
echo "<img src='IMG.jpg'<p>/>";
should be
echo "<p><img src='IMG.jpg' /></p>";
And the same goes for your other image.