• Welcome to Overclockers Forums! Join us to reply in threads, receive reduced ads, and to customize your site experience!

PHP/MySQL question

Overclockers is supported by our readers. When you click a link to make a purchase, we may earn a commission. Learn More.

Special7

Member
Joined
Apr 10, 2004
Ok so I know you can run queries in a function, I'm working on making my own message board system in PHP/MySQL and it's nearly in usable form, but I want to clean up my code and figured functions would work great.

For example this is what I'm trying right now and it's giving me an error:
Warning: Missing argument 1 for simple() in

function simple($table) {
$sql = “SELECT * FROM “.$table;
$result = mysql_query($sql);
return $result;
}

What am I doing wrong? table i'm trying to pull information from is users and I want to pull the Username filed.
 
Last edited:
If you mean how am I pulling the function? I simply use simple();
Well, there's the problem :)
Your function is written to require an arguement.

So do as jdf_warrior.
Something you can also do is to define a default value for the argument - this way, if you don't supply one, it takes the default value instead.
Code:
function simple($table = "aTable") {
    $sql = “SELECT * FROM “.$table;
    $result = mysql_query($sql);
    return $result;
}
 
function simple($table) {
$sql = “SELECT * FROM “.$table;
$result = mysql_query($sql);
return $result;
}

What am I doing wrong? table i'm trying to pull information from is users and I want to pull the Username filed.

Well, first of all, if you want just the username, you need to
SELECT username
or whatever the username field is, rather than
SELECT *

Second, ALWAYS clean your input. You may later make use of this function with user-entered options, and forget that you aren't cleaning the input. You would be quite unhappy if your database got wiped because of that :)

You could make this function more versatile with the following:
Code:
function simple($field = "*", $where = 0, $table = "users") {
$field = mysql_real_escape_string($field);
$table = mysql_real_escape_string($table);
$sql = 'SELECT '.$field.' FROM '.$table;
if ($where) {
$where = mysql_real_escape_string($where);
$sql .= ' WHERE '.$where;
}
$result = mysql_query($sql);
return $result;
}

You can then call:

1. simple("username");
2. simple("username","userid = 3");
3. simple("content","postid = 25", "posts");
4. simple();

to get:

1. All usernames. Note that with the function as written above, you'll still need to get the usernames out of $result and into an array.
2. Just the username for userid 3.
3. The content field of postid 25 in the posts table.
4. The entire users table. As with #1, this will need further code to move the MySQL result into an array.

If you want to select a different table without a WHERE clause, you'll have to stick a 0 in the call: simple("field",0,"table");
 
Last edited:
Back