Changed connection page to PDO and got mysql_error()

自古美人都是妖i 提交于 2020-01-03 19:38:13

问题


Was going over my code to turn all my queries into prepared queries (PDO). I changed my connection page accordingly. As I was cleaning up my functions page I came across the error mysql_error() expects parameter 1 to be resource, integer given which referred to my email function

email_exists($email){
    $query1 = mysql_query("SELECT COUNT(user_id) FROM tempusers WHERE 
    `email` = '$email'") OR die(mysql_error(0));
    $email = sanitize($email);

    return (mysql_result($query1,0)==1)? true : false;
}

Because it is a function page meaning I can't call on the variables in my connection page coupled with the fact I'm still stuck in the old query ways I'm having a hard time fixing this query. I'd appreciate any ideas on the process of making this query work as well as any tips in general.


回答1:


You should handle errors in your function the same way you handle them everywhere else.

However, as this is inside a function, you need to make the connection available in the scope of the function.

There are several ways to do that, some examples (from not that good to better...):

  1. declare your PDO connection variable global in your function. I would not recommend this as a final solution, but it would work while you improve on things;
  2. add the PDO connection as an additional parameter to your function. Although better than 1., you would need to change all function calls to include the new parameter(s);
  3. refactor to OOP and use dependency injection to add your PDO connection to your email class / object.


来源:https://stackoverflow.com/questions/13215466/changed-connection-page-to-pdo-and-got-mysql-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!