PHP parse error (beginner)?
I keep getting this error: "Parse error: syntax error, unexpected ‘}’ …etc"
It is giving this error wherever I have an IF statement that skips out of php to display HTML then goes back into php to close the IF statement. The closing bracket is causing the problem.
Example:
if (mysqli_num_rows($result) == 0) {
?>
<p>Image not found.</p>
<?php
} else { //bunch more code here
There are numerous instances where that closing bracket is causing problems. What do I do? Is it somehow assuming the function is already closed when I exit php, so when I start php again the closing bracket is redundant??
I’m using apache on windows home computer. I have not tried this hosted live.
Odd… I got this code straight from a tutorial site.
A lot of coders use that kind of syntax, which I call "Bad coding": it make the code difficult to read.
Your code IS correct, even if I don’t like it.
The answer above may show a parse error, but will not "run", as "true" will always be "true", so the second branch will never be tested.
Re-write your code in a clearer manner:
<?php
if (condition) {
echo ("<p>Image not found</p>");
}
else
{
echo ("<p><img src=xxx></p>");
}
?>
Only mix languages when you CAN’T do otherwise: you will soon find yourself reading a piece of code and ask: "Is this Php, Javascript or HTML???", or having a javascript embedded in a php code and wonder why it does not work!
You’re breaking out of your php code before closing your if statement. You can’t do that. Try this:
if (mysqli_num_rows($result) == 0) {
echo "<p>image not found</p>";
}
that will have the same effect.
References :
I use that syntax all the time and it works fine. I’ve never heard of something like this, but it’s possible that it’s a weird PHP configuration.
Try a simple program to see if something is wrong with your PHP configuration.
<?php
if(true) {
?>
<p>True</p>
<?php
}
else {
?>
<p>False</p>
<?php
}
?>
If that gives an error, I would recommend reinstalling PHP and using the default configuration file.
If it works fine, then you have a problem somewhere else in your code. It’s most likely an extra closing bracket.
Hope this helps.
References :
A lot of coders use that kind of syntax, which I call "Bad coding": it make the code difficult to read.
Your code IS correct, even if I don’t like it.
The answer above may show a parse error, but will not "run", as "true" will always be "true", so the second branch will never be tested.
Re-write your code in a clearer manner:
<?php
if (condition) {
echo ("<p>Image not found</p>");
}
else
{
echo ("<p><img src=xxx></p>");
}
?>
Only mix languages when you CAN’T do otherwise: you will soon find yourself reading a piece of code and ask: "Is this Php, Javascript or HTML???", or having a javascript embedded in a php code and wonder why it does not work!
References :