我一直在php中使用mysql抽象类,现在我想通过使用PDO使类更可用和更可靠。在我的课堂上,我使用了mysql_result()函数,该函数带有三个参数:


结果:正在评估的结果资源。该结果来自调用mysql_query()。
row:要检索的结果中的行号。行号从0开始。
field:要检索的字段的名称或偏移量。


如何使用PDO获得相似的输出?

这是用本地mysql函数编写的代码。

public function SQLtoJSON($query, $indented = false)
    {
        $query = mysql_query($query) or die ('MyJSON - SQLtoJSON - Cannot make query');

        if (!$numFields = mysql_num_fields($query)) {
            $this->errors[] = 'SQLtoJSON - Cannot get number of MySQL fields';
            return false;
        }

        $fields = array();
        for ($i = 0; $i < $numFields; $i++)
            $fields[$i] = mysql_field_name($query, $i);

        if (!$numRows = mysql_num_rows($query)) {
            $this->errors[] = 'SQLtoJSON - Cannot get number of MySQL rows';
            return false;
        }

        $res = array();
        for ($i = 0; $i < $numRows; $i++) {
            $res[$i] = array();
            for ($j = 0; $j < count($fields); $j++)
                $res[$i][$fields[$j]] = mysql_result($query, $i, $j);
        }

        $json = json_encode($res);
        if ($indented == false)
            return $json;


这是使用PDO的代码的更新版本:

class MySql_To_Json
{

    private $connection;
    public $errors = array();

    public function __construct($db_server, $db_username, $db_password, $db_name)
    {
        $this->connection = new PDO("mysql:host=$db_server;dbname=$db_name",   $db_username, $db_password);
    }

    public function MySQLtoJSON($query)
    {
        $query = $this->connection->query($query) or die("Unable to execute the query");
        if (!$numFields = $query->columnCount()) {
            $this->errors[] = "Unable to get the number of fields";
            return false;
        }

        $fields = array();
        $colNames = array();

        for ($i = 0; $i < $numFields; $i++) {
            $fields[$i] = $query->getColumnMeta($i);
            foreach ($fields as $field) {
                $colNames[] = $field['name'];
            }
        }

        if (!$numRows = $query->rowCount()) {
            $this->errors[] = "Unable to get the number of rows";
            return false;
        }

    // return $numRows;
        $result = array();
        for ($i = 0; $i < $numFields; $i++) {
            $result[$i] = array();
            for ($j = 0; $j < count($field); $j++) {
                return $result[$i][$field[$j]] = $query->fetch($i);
            }
        }

        $json = json_encode($result);
        return $json;
    }
}

最佳答案

正如我在评论中所怀疑和暗示的那样,您最初使用mysql_result()是不必要的。您在旧类中拥有的是C样式增量for循环的集合,在PHP中很少使用。相反,使用foreach迭代数组以及处理数据库API时执行以下操作更为常见:

// This is the normal and easy way to get an associative array of results:
while ($row = mysql_fetch_assoc()) {
  $results[] = $row;
}


...您无需担心行数或列数的地方。

无论如何,所有这些现在都完全不需要了,并且可以通过在PDO中对fetchAll()的一次调用来替换,因为它所做的只是将所有行检索到列名索引的数组中。这大约与获取操作一样。

   // ALL of this...
   // $res = array();
   // for ($i = 0; $i < $numRows; $i++) {
   //     $res[$i] = array();
   //     for ($j = 0; $j < count($fields); $j++)
   //         $res[$i][$fields[$j]] = mysql_result($query, $i, $j);
   // }

   // ...may be replaced with simply:
   $res = $query->fetchAll(PDO::FETCH_ASSOC);


这也意味着您实际上并不需要前面的两个块来检索行数和列数。所有这些都隐含在对fetchAll()的调用中。您现在真正需要的唯一部分是查询和获取:

public function MySQLtoJSON($input_query)
{
    // Do your query...
    $query = $this->connection->query($input_query) or die("Unable to execute the query");

    // Fetch the rows as associative arrays
    $result = $query->fetchAll(PDO::FETCH_ASSOC);

    // And encode it as JSON
    $json = json_encode($result);
    return $json;
}


请注意,由于您要在$query参数中执行任意SQL语句,因此,对于在其中传递的内容要小心,以避免SQL注入。如果您接受任何用户输入而不是静态查询,则需要考虑对其进行调整以使用PDO::prepare()并将其作为参数化查询执行。

关于php - PDO中mysql_result()函数的替代方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17839652/

10-12 12:53
查看更多