doushifang4382 2011-11-01 06:32
浏览 69
已采纳

在类中调用数据库连接

I have a problem regarding my mysql connection. I need to access the connection inside a class. How do I do it? Even if I try to include the connection file, or the connection variable $con0 inside the class, it has no value so I get an error.

Connection.php

<?php
$username = " ";
$password = "";
$hostname = " ";    
$con = mysql_connect()
?>

model.php

<?php

include(connection.php);
class model{

function needTheConnection($uid){
$q = "SELECT x from  DB.table WHERE id = '" . $uid . "'";
$res  = mysql_query($q);
}

}
?>

This gives me the "mysql_query(): supplied argument is not a valid MySQL-Link resource".

What is wrong?

Thanks, tinks

  • 写回答

2条回答 默认 最新

  • doudouwen2763 2011-11-01 06:57
    关注

    You're missing part of your code. We know this based on the error message. This line:

    $res  = mysql_query($q);
    

    Probably actually looks like this in your code:

    $res  = mysql_query($q, $con);
    

    Am I right? If that's the case, the issue is that $con isn't accessible from within that function or class instance. The easy way to fix this in your case is to simply remove it. The MySQL client will automagically use the last connection made from your script.

    Really though, you should consider a different design pattern. For what its worth, I often just stick my DB resource in $GLOBALS['db']. This is not considered a pure OOP way to do things, but for many applications, it is suitable.

    Finally, $5 says you are wide open to SQL injections. Learn how to do prepared queries with PDO, or at least escape your data before someone steals your entire database and brings havok to your site.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog