I just had some basic php questions to further my understanding as I learn, that I could not find easy answers to
-
I have a php ajax application that generates a table of mysql rows. I would like to know if there is a way to get php to generate neat html, as it seems neat enough as I echo it out, but when ‘viewing source’ the html is a huge jumbled block with no line breaks or anything. Is there a trick to doing this?
-
What is the best way to limit table output for a mysql database, so only the first 10 records or so are displayed, and there are automatically generated next and previous links to go between records?
-
When outputting information with php from a mysql database, what is the best way to handle booleans? What is the easiest way to display the words ‘yes’ or ‘no’ or a tick or a cross? edit: I do not mean should I use words or pictures, but rather how to show either in response to a boolean
Question 1
You need to separate the PHP code and the HTML output. The easiest thing to do, as a newbie, is :
Fill a var named $tab with your entries.
Create a file called "
my_tab_template.php" including your xHTML code, using very few PHP to unpack $tab and only with the PHP alternative syntax.my_tab_template.phpright after you have filled $tab.Don’t worry about optimization and performances, this will certainly not be your website bottleneck as you starting to code and you will make some things far more troublesome 😉
Then, in your next project, when you will feel fine doing this, try to learn about the MVC pattern (a little search on SO may help). Don’t listen to people talking about templating systems, and else. Don’t try to start running a 150 cc before passing your driving licence.
Question 2
This is not a PHP question. What you want to do is to limit the output from your database. You can do that using the "LIMIT" SQL keyword.
You can use :
LIMIT 10 : this will limit your query to the 10 first row (= LIMIT 0,10)
LIMIT X, Y : this will limit your query to Y rows, starting from the row X
Remember to sort your query result with "ORDER BY" before using LIMIT to avoid nasty surprises.
And there is no automatic pagination in PHP. There are some PHP libraries that does the dirty job for you, but before you use them, I recommand to hack your own solution first to understand the mechanism. It’s just about checking vars and using "LIMIT", really.
Then you may have a look to PEAR where a standard way to do it exists. But don’t try too hard to find it, you’d better code it yourself first.
Question 3
If your database store a boolean, therefore it will output "0" for false, anything else (most probably "1") for true. Just test it :
In PHP, there is a shortcut to say that, but you have no obligation to use it. Anyway, it’s good to know it exists. Meet the boolean operator :