我的PHP出了什么问题?

时间:2013-07-01 19:16:53

标签: php sql xampp

我是PHP的新手,我看了一篇关于SQL和PHP的教程,我制作了这些文件:

insert_news.php:         

    require_once __DIR__ .'/db_connect.php';

    $sql = "INSERT INTO news ( descriere, data, autor) VALUES (?, ?, ?)" ;
    $params = array("The description", "12/11/2011", "COsmin");


    $serverName = "my server";
    $connectionInfo = array( "Database"=>"myusername", "UID"=>"myusername", "PWD"=>"mypassword");

    $conn = sqlsrv_connect($serverName, $connectionInfo );
    $stmt = sqlsrv_query( $conn , $sql, $params );

    if( $stmt == false ) {
        echo("NOT");
        die( print_r( sqlsrv_errors(), true));
    }

?>

此代码似乎运行良好。

现在我的问题是我想创建一个类,它将使与数据库的连接更容易。 这就是代码:

db_connect.php

<?php
class DB_CONNECT {
    function __construct(){
        $this->connect();
    }

    function __Destruct(){
        $this->close();
    }

    function connect() {
        $serverName = "my server";
        $connectionInfo = array( "Database"=>"my db", "UID"=>"my user", "PWD"=>"my pass" );

        $con = sqlsrv_connect($serverName, $connectionInfo );
                return $con;
    }
    function close(){
        sqlsrv_close();
    }
}
?>

如果我想从我的insert_new.php文件中调用这个类:

    <?php

    require_once __DIR__ .'/db_connect.php';

    $sql = "INSERT INTO Stiri ( descriere, data, autor) VALUES (?, ?, ?)" ;
    $params = array("ASta e o stvnmbvire aduagata printr-un web service php", "12/11/2011", "COsn");

    $conn = new DB_CONNECT() ;
    $stmt = sqlsrv_query( $conn , $sql, $params );

    if( $stmt == false ) {
        echo("NU");
        die( print_r( sqlsrv_errors(), true));
    }
?>

当我尝试这个时,我的服务器返回给我:

警告:sqlsrv_query()要求参数1为资源,第9行的C:\ xampp \ htdocs \ android_connect \ insert_news.php中给出的对象 NUArray([0] =&gt;数组([0] =&gt; IMSSP [SQLSTATE] =&gt; IMSSP [1] =&gt; -14 [代码] =&gt; -14 [2] =&gt;参数无效传递给sqlsrv_query。[message] =&gt;将无效参数传递给sqlsrv_query。))

我提到我使用XAMPP编译php文件,数据库是SQL Server 2005 ... 对不起,如果我浪费你的时间与我愚蠢的东西......

2 个答案:

答案 0 :(得分:1)

您将自定义对象提供给sqlsrv_query函数而不是数据库实例。在你的课堂上,你应该让$ con变量成为这样的公共属性:

class DB_CONNECT {
    public $con = false;
    function __construct(){
        $this->connect();
    }

    function __Destruct(){
        $this->close();
    }

    function connect() {
        $serverName = "my server";
        $connectionInfo = array( "Database"=>"my db", "UID"=>"my user", "PWD"=>"my pass" );

        $this->con = sqlsrv_connect($serverName, $connectionInfo );
                return $con;
    }
    function close(){
        sqlsrv_close();
    }
}

并将此属性赋予您的查询函数,如下所示:

if($conn->con) {
   $stmt = sqlsrv_query( $conn->con , $sql, $params );
} else {
   // error
}

答案 1 :(得分:1)

好像你没有动手连接数据库。

这是你的问题

$conn = new DB_CONNECT();
$stmt = sqlsrv_query( $conn , $sql, $params );

$conn不是连接,它只是一个DB_CONNECT对象。您需要调用connect()方法来获取连接。所以试试这个:

$conn = new DB_CONNECT();
$stmt = sqlsrv_query( $conn->connect() , $sql, $params );