0

我在不同的页面上一次又一次地使用相同的查询来获取结果。我想为这个查询创建一个函数。

$result = mysql_query(" SELECT name FROM tablename where id= '$row[name_id]'"); 
$row = mysql_fetch_array($result); 
echo $row ['name']; 

如何制作以及如何调用该函数?

4

4 回答 4

0

这是一个好主意,但首先您必须创建一个函数来运行查询(因为您必须比特定查询更频繁地运行各种查询)

function dbget() {
  /*
  easy to use yet SAFE way of handling mysql queries.

  usage: dbget($mode, $query, $param1, $param2,...);
  $mode - "dimension" of result:
  0 - resource
  1 - scalar
  2 - row
  3 - array of rows

  every variable in the query have to be substituted with a placeholder
  while the avtual variable have to be listed in the function params
  in the same order as placeholders have in the query.

  use %d placeholder for the integer values and %s for anything else
  */
  $args = func_get_args();
  if (count($args) < 2) {
    trigger_error("dbget: too few arguments");
    return false;
  }
  $mode  = array_shift($args);
  $query = array_shift($args);
  $query = str_replace("%s","'%s'",$query); 

  foreach ($args as $key => $val) {
    $args[$key] = mysql_real_escape_string($val);
  }

  $query = vsprintf($query, $args);
  if (!$query) return false;

  $res = mysql_query($query);
  if (!$res) {
    trigger_error("dbget: ".mysql_error()." in ".$query);
    return false;
  }

  if ($mode === 0) return $res;

  if ($mode === 1) {
    if ($row = mysql_fetch_row($res)) return $row[0];
    else return NULL;
  }

  $a = array();
  if ($mode === 2) {
    if ($row = mysql_fetch_assoc($res)) return $row;
  }
  if ($mode === 3) {
    while($row = mysql_fetch_assoc($res)) $a[]=$row;
  }
  return $a;
}

那么您可以创建您要求的这个特定功能

function get_name_by_id($id){
    return dbget("SELECT name FROM tablename where id=%d",$id); 
}
于 2012-04-23T07:41:08.547 回答
0

示例类存储 sample.php

class sample
{

    function getName(id)
    {
         $result = mysql_query("SELECT name FROM tablename where id='$id'"); 
         $row = mysql_fetch_array($result); 
         return $row ['name']; 
    }
}

使用页面包含 sample.php,然后创建对象,然后调用 getName() 函数。

<?php
 include "db.class.php";
 include "sample.php";
 $ob=new sample();         //create object for smaple class
 $id=12;
 $name=$ob->getName($id);  //call function..
?>
于 2012-04-23T07:17:44.120 回答
-1

您可能还应该解析数据库连接

$database_connection = mysql_connect('localhost', 'mysql_user', 'mysql_password');

function get_row_by_id($id, $database_link){
    $result = mysql_query("SELECT name FROM tablename where id= '{$id}"); 
    return mysql_fetch_array($result);
}

用法

$row = get_row_by_id(5, $database_connection);

[编辑] 此外,将函数包装在一个类中可能会有所帮助。

于 2012-04-23T07:18:51.657 回答
-1
function getName($id){
    $result = mysql_query("SELECT name FROM tablename where id= '$row[name_id]'"); 
    $row = mysql_fetch_array($result); 
    return $row ['name']; 
}

通过调用函数

$id = 1; //id number
$name = getName($id);
echo $name; //display name
于 2012-04-23T07:40:33.053 回答