开发者

Why isn't this simple function working?

开发者 https://www.devze.com 2023-01-08 23:22 出处:网络
I didn\'t want to keep repeating 开发者_运维百科the same select query, so I wrote this function. But it doesn\'t work:

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);


  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');


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消