tags:

views:

76

answers:

5

I didn't want to keep repeating the same select query, so I wrote this function. But it doesn't work:

function select($what, $table) {
    $query = mysql_query("SELECT $what FROM $table");
}
select(*, products);
+2  A: 

you need to return $query

function select($what, $table) {
    return $query = mysql_query("SELECT $what FROM $table");
}
$query = select(*, products);

Then $query will have the result source of your query, which you would then use mysql_fetch_xxx or whatever on.

Crayon Violent
A: 

Your arguments should be strings (ie. select('*', 'products'))

indieinvader
A: 

Perhaps because $query is discarded after the function ends? I don't have much experience with SQL, but this would look better to me:

function select($what, $table) {
    return mysql_query("SELECT $what FROM $table");
}
select("*", "products");

Oh, and "*" and "products" need to be strings.

Fraxtil
+4  A: 
  1. You need to enclose your arguments in quotes.
  2. You should return the query pointer afterwards.
  3. You should quote-escape the values to avoid SQL injection.
function select($what, $table) {
    $what = mysql_real_escape_string($what);
    $table = mysql_real_escape_string($table);
    return mysql_query("SELECT '$what' FROM `$table`;");
}
$query = select('*', 'products');

For debugging:

function select($what, $table) {
    $what = mysql_real_escape_string($what);
    $table = mysql_real_escape_string($table);
    $query = mysql_query("SELECT '$what' FROM `$table`;") or die(mysql_error());
    return $query;
}
$query = select('*', 'products');
Delan Azabani
I copied your code exactly and it still doesn't work, gives this error:Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\shopping_cart\product.php on line 22
Georgy
It's because `mysql_query()` is returning `false`.
Delan Azabani
Please, replace addslashes with mysql_real_escape_string. See also the documentation of addslashes http://php.net/manual/en/function.addslashes.php -1 from me until you fix that...
Peter Smit
Also you can't put a table name in single-quotes.
Bill Karwin
Peter, Bill, done.
Delan Azabani
This works now:function select($what, $table) { return $query = mysql_query("SELECT $what FROM $table");}$query = select("*", "products");
Georgy
Yes, but you didn't escape your input data, which could very easily lead to SQL injection, which leads to password stealing or database destruction.
Delan Azabani
Peter, my `-1` back? :)
Delan Azabani
The `*` doesn't belong inside quotes. And neither would a column name if you passed that.
Bill Karwin
+1  A: 

What you should do is:

function select($what, $table) {
    return mysql_query("SELECT $what FROM `$table`");
}
$query = select('*', 'products');
Tuong Le