du1913 2012-08-28 21:49
浏览 41
已采纳

MySQL函数返回很难在PHP中使用结果

I have a MySQL function that looks like this:

delimiter #
create function activate_user
(
    p_activation_hash char(32)
)
returns int
deterministic
begin
    declare v_ret int unsigned default 0;

    if (char_length(p_activation_hash) != 32) then
        return 0;
    end if;

    insert ignore into users (email, password_hash, first_name, last_name, company_name)
        select email, password_hash, first_name, last_name, company_name
        from user_activation
        where activation_hash = p_activation_hash
        and expiry_date > now();

    return last_insert_id();
end #
delimiter ;

And if I call it like this using CodeIgniter:

$query = $this->db->query("select activate_user(?);", array($this->input->get('key')));

var_dump($query->result_object());

var_dump($query->result_array());

I can get either an array or object of results that looks like this:

array
  0 => 
    object(stdClass)[16]
      public 'activate_user('5c9835e8dee7e1b43691708f503cb7f5')' => string '0' (length=1)

array
  0 => 
    array
      'activate_user('5c9835e8dee7e1b43691708f503cb7f5')' => string '0' (length=1)

Obviously due to the key it isn't very useable and I don't really want to do a foreach it seems like there should be a better way?

I thought one of the point big advantages of mysql functions was to return things like integers, but reading these intergers seems messy in php, am I missing something?


For your information this is the most concise I got it:

$query = $this->db->query("select activate_user(?) as user_result;", array($this->input->get('key')));
$result = current($query->result_array());

echo "function result: " . $result['user_result'];
  • 写回答

2条回答 默认 最新

  • donglianjiang9321 2012-08-28 21:58
    关注

    The result is showing you that the function returned zero. If you alias your function call you might have a more sensible time reading the result:

    $query = $this->db->query("select activate_user(?) AS user_result;", array($this->input->get('key')));
    

    Now the function call is aliased to a column name of user_result which is easier to read without needing the key. Then you can read the result as:

    $result = $query->result_array();
    echo "function result = " . $result['user_result'];
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记