tags:

views:

74

answers:

4

I started working with php and mysql today. Basically, what I have, is an empty page with pieces that I fill in from looking up an id in a database. So on my home page I have an url that looks like this:

<a href="content/display.php?id=id1">

And then in my display.php I have this:

<?php
    include '../includes/header.php';
    $id = $_GET['id'];
    $mysqli = new mysqli('localhost','username','password','dbname');
    if($result = $mysqli->query("SELECT * FROM portfolio WHERE id='".$id."'"))
    {
        while($row = $result->fetch_object())
        {
            $head = $row->head;
            $img1 = $row->img1;
            $img2 = $row->img2;
            $img_url = $row->imgurl;
            $img_thumb = $row->imgthumb;
            $vid = $row->vid;
            $swf = $row->swf;
            $url = $row->url;
            $url_text = $row->urltext;
            $text = $row->text;
        }
    }
    else echo $mysqli->error;
?>

It's a sparse table in that not all of those fields will have information (many might be null). Basically they contains file names and then in the html I have code that looks like this:

if(isset($img1))
                    {
                        echo '<img src="images/'.$img1.'" />';
                    }

A couple of questions,

  1. Is this the best way to do this?
  2. Everytime I visit display.php, I am reopening a database connection right? That can't be good...
  3. I chose to put the names of the files in the database, rather than entire path names, or even the actual files themselves, figuring that, if I change the name of the file I can go into the database and update it for the file I want to change. If I change the path, I can just change it once in the html. Is that the best idea?

Thanks!

+4  A: 

You are vulnerable to SQL injection, properly type cast your variables:

$id = (int) $_GET['id'];

Use functions such as mysql_real_escape_string or even better use:

Sarfraz
+1 for prepared statements
Wrikken
I've used prepared statements for jdbc but not for php so I'm somewhat familiar. I'll check that out. Since my id is not an int, is that what mysql_real_escape_string is for? Thanks
JPC
@JPC: Yes you can use `what mysql_real_escape_string`.
Sarfraz
+1 didn't know about prepared statements
russjman
+3  A: 

1) No, although that's the easiest way for beginning. After you feel comfortable with basics, you should spend some time considering different approaches to application structure. Most important rule is to separate concerns. Don't mix database code with business logic code with presentation code. But like I said, it's not something you should worry about on your first day. For now just learn basics.

2) There's no other way actually. For a web application each request from browser is like an individual run of application. There is a possibility to use so called persistent database connections, but just like in previous point, that's something you should not deal with on your first day, as they require specific configuration of your web server. For the time being just use normal connections.

3) That's pretty sensible idea. You could also define your image path as a PHP constant, so that in case a change is needed, you only change this one constant.

4) What sAc says in his answer is very important. Read about SQL injections and how to prevent them.

Mchl
1) I'm familiar with the MVC approach. However, I'm fairly new to PHP. I've used Struts 2 and the framework is put together to facilitate separating business, data, and presentation. For future reference, I'd like to learn more about how to do this in php. Any tips of a good guide to start with?Thanks!
JPC
Oh in that case it's entirely different talk :)There are several MVC frameworks for PHP available differing greatly in details of implementation. One very popular is Zend Framework, many say it's actually a collection of loosely coupled classes. On the other hand there are frameworks like Symfony implementing 'configuration by convention' model. You'll most certainly find something that fits your needs.
Mchl
@Col. Shrapnel I'm still kinda new to this site and answering protocol. I didn't realize I could only pick one answer.
JPC
@Mchl do these take a lot of time to set up? Whenever I want to set up a struts 2 project, I have a bunch of things I need to configure and so for a relatively small project like a personal website, I didn't think it was worth my time. Plus I wanted to practice my php! When I develop in struts 2 I can just deploy a .war to the tomcat server and it just works. For a server with php, does the server you're using have to have the framework already installed on it?Thanks!
JPC
PHP world is a bit different from Java world. In PHP 5.3 a phar file format was used, that can in theory offer same benefits as .war. I've never seen it in use. To install PHP application on server you usually upload all files that the app consists of. This can be a tedious and tricky task, so version control and continuous integration tools are of great help.Zend Framework (and possibly others too) has a command line tool, that does a lot of 'setting up a new project' job for you. You have a functional application in seconds. Although it just displays one static page ;)
Mchl
Thanks! Everyone here seems to know a lot more about php than about struts haha. It's been so much easier to answer my php questions.
JPC
That's we get paid less for PHP jobs than for Java jobs ;)
Mchl
+1  A: 

SQL injection & prepared statements are already mentioned. An addition to that would be:

else echo $mysqli->error;

Change that to:

else trigger_error($mysqli->error,E_USER_ERROR);

Why you ask? Because visitors should have no idea about your database, and cannot fix the error, so they plain shouldn't see it. This way, you can safely develop with display_errors on, and on the live site display_errors is off, and you log_errors in an error log.

Wrikken
where do the errors get logged? do I have to configure display_errors and log_errors somewhere?
JPC
I would argue that in fact the best way is to transform all errors to ErrorExceptions as described here http://php.net/manual/en/class.errorexception.php , but again it's a bit more advanced topic.
Mchl
@Mchl exceptions is more of error *handling* while Wrikken is talking of error *tracking*. that's different worlds, that do not interfere. Actually you can use both in the same script.
Col. Shrapnel
I find using exceptions facilitate error tracking too. :)
Mchl
Wrikken
A: 

Looks like you have good handle on what you want to do. I don't know how much development background you have, but it would be a good idea to start learning about MVC's in php like CakePHP, Fuse, or even Zend Framework(bleh!!!). I'll save you time on more robust applications by pre defining all your basic db interface, template handling, session handling, and let you worry about higher level problems, like what's for lunch! :)

russjman