Say I’ve got a mySQL database table with 4 fields:
- link_id (primary key)
- page_id
- anchor_text
- url
My data looks like this:
link_id | page_id | anchor_text | url
1 | 1 | Link One | http://www.one.com
2 | 1 | Link Two | http://www.two.com
3 | 2 | Link Three | http://www.three.com
How would I best write a function to get the links for a given page and then use that function to display them?
Function:
function get_page_links($page_id) {
$db = new mysqli("localhost", "root", "root", "my_db");
//what's next?
}
Usage:
$my_links = get_page_links(1);
//do something to parse $my_links
Display:
<a href="http://www.one.com">Link One</a>
<a href="http://www.two.com">Link Two</a>
The backticks might not be necessary, but I’m throwing them in there since you have hyphens in your field names.
Note that there is very basic validation going on here. By casting
$page_idto an int before appending it, you ensure it won’t be some sort of injection attack. This isn’t a great way to do it, but it will work.Something like
mysqli_real_escape_string()is an alternative that should be considered, especially for more general sanitization.Alternatively:
Which I like better.
Edit re: now what?
First off, lets not use mysqli, lets use PDO.
Second, we don’t want to connect to the database on each call of the function, we want to do this once. So move this out of the function.