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);
- You need to enclose your arguments in quotes.
- You should return the query pointer afterwards.
- 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');
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.
What you should do is:
function select($what, $table) {
return mysql_query("SELECT $what FROM `$table`");
}
$query = select('*', 'products');
Your arguments should be strings (ie. select('*', 'products')
)
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.
精彩评论