c++ - PHP-CPP 新扩展适用于 cli 'php' 命令,但不适用于浏览器

标签 c++ mysql php-extension php-cpp

我正在使用 PHP-CPP 创建一个 PHP 扩展,其中包含一个将从 mysql 解析表的函数。

扩展.cpp

#include <phpcpp.h>
#include <iostream>
#include <mysql.h>

Php::Value  ss_parse_table(Php::Parameters &params)
{ 
MYSQL *conn;
MYSQL_RES *res;
MYSQL_ROW row;
MYSQL_FIELD *field;

/* INITIALIZE CONNECTION HANDLER, DO NOT CHANGE */
conn = mysql_init (NULL);


// @param orders: host,username,password,database,
mysql_real_connect (conn, params[0], params[1], params[2], params[3], 3306, NULL, 0);
/* show tables in the database (test for errors also) */


mysql_query(conn,("SELECT * FROM table");
res = mysql_store_result(conn);


// get the number of the columns
int num_fields = mysql_num_fields(res);

Php::Value array;
Php::Value rows;
int i = 0;

while((field = mysql_fetch_field(res))){
    array[i] = field->name;
    i++;
}

int x = 0;
while ((row = mysql_fetch_row(res)))
{

    for (int z=0;z<num_fields;z++) 
    {
        std::string fieldname = array[z];
        rows[x][fieldname] = row[z];
    }

    x++;
}

// DON'T FORGET TO CLEAN RESULT AFTER YOU DON'T NEED IT 
// ANYMORE
if(res != NULL)
   mysql_free_result(res);

/* disconnect from server */
mysql_close (conn);

return rows;

}

extern "C" {


  PHPCPP_EXPORT void *get_module() 
  {
    \
    static Php::Extension extension("extension", "1.0");
    extension.add("ss_parse_table",ss_parse_table);
    // @todo    add your own functions, classes, namespaces to the extension

    // return the extension
    return extension;
  }
}

在编译过程中,我编辑了 MakeFile 并在编译器命令中附加了 mysql_config --cflags --libs 以加载 mysql,因此它看起来像 g++ -shared -o 扩展。所以 extension.o -lphpcpp mysql_config --cflags --libs 编译工作正常。

我尝试使用扩展中定义的函数(ss_parse_table)来测试编译是否真的有效。所以我创建了一个 php 文件:

测试.php

<?php
  print_r(ss_parse_table( "localhost", "dbuser","dbpassword","database"));
 ?>

当我从 CLI 运行命令“php/mnt/test/index.php”时,它工作正常。 该命令将输出由定义的扩展函数(ss_parse_table)返回的数组,如下所示

Array
(
  [0] => Array
  (
    [id] => 'erd'
  )
)

但是当我从浏览器浏览它时,http 失败

“未收到数据”(chrome 错误)或“连接已重置”(firefox 错误)

最佳答案

我遇到了完全相同的问题。我通过将 libmysqlclient.so 文件所在的目录添加到系统路径来解决这个问题:

PATH=$PATH:/usr/lib64

然后,重新启动httpd服务:

systemctl restart httpd.service

之后,一切正常。

希望对你有帮助

关于c++ - PHP-CPP 新扩展适用于 cli 'php' 命令,但不适用于浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25327543/

相关文章:

c++ - 使用 C++ 在 Sqlite 数据库中运行 sqlite 脚本

PHP 查询不起作用

php - 无法从 mysql 表中获取所有值

php Zeromq 扩展 : Unable to load dynamic library php_zmq. dll

php - 在PHP扩展中,推荐的方法从and std::string返回值

c++ - 为什么 C++ 允许将指向基对象的指针转换为派生类的指针

c++ - 是否可以知道整数类型有多少位?

c++ - 你能全局设置 qDebug() 浮点精度和数字格式吗?

mysql - 为什么这个查询需要一整天才能在 mysql 上运行?

c++ - 为什么用 C++ 编写的 phpcpp 扩展函数比用 php 编写的函数慢