SQL错误:警告:mysql_fetch_object():提供的参数不是有效的MySQL结果资源

时间:2013-05-14 12:39:41

标签: php sql database

如果我尝试在CMS上发布文章,则会收到错误消息。

错误:

  

警告:mysql_fetch_object():提供的参数不是有效的MySQL   结果资源   /home/investmp/domains/cashcow.nl/public_html/publiceer/functions.php   第32行您的SQL语法中有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'Premiekoopwoning moet terugkomen'','eddy','publiceren')'at   第1行

的functions.php:

<?php
//## Function list: News Manager ##//
//## Content News:  Lead - Header - Chapeaux - Flat text (text) - Quote - Frame - Image - Chart ##// 

//Upload images to folder (resize = 1|0 - $dir (default = /images as stated in admin)
function uploadFile($fileinput ,$resize, $dir, $id)
{
global $_FILES; 
    $file = $_FILES[$fileinput]['name']; 

    if (is_uploaded_file($_FILES[$fileinput]['tmp_name'])) { 
        copy($_FILES[$fileinput]['tmp_name'], $dir.$id."_".$file);

        if($resize == 1){ 
            imageResize($file); 
        }

        chmod($dir.$id."_".$file, 0775); 
        return $_FILES[$fileinput]['name']; 
    }

}

function lastID()
{

    $laatsteID = mysql_query("select id from artikelen order by ID DESC limit 1"); 

    $check = mysql_num_rows($laatsteID); 

        if($check !== 0){ 
            while($lid = mysql_fetch_object($laatsteID)){ $laatsteID = $lid->id; } 
        } else{ 
            $laatsteID = 0; 
        }

    return $laatsteID;

} 

function lastBannerID()
{ 

    include("db_connect.inc.php"); 

    $laatsteID = mysql_query("select id from banners order by id DESC limit 1"); 
    $check = mysql_num_rows($laatsteID); 

        if($check !== 0){ 
            while($lid = mysql_fetch_object($laatsteID)){ $laatsteID = $lid->id; }
        } else { 
            $laatsteID = 0; 
        } 

    return $laatsteID; 

} 

//Function to change the size of images automatically by default sizes
function imageResize($image, $width)
{
    $filename = $image;

//Max height for images (will be downscaled proportionally untill it fits BOTH sizes!)
    $height = 200; 

        header('Content-type: image/jpeg'); 
        list($org_width, $org_height) = getimagesize($filename);

            $org_ratio = $org_width/$orig_height; 


        if($width/$height > $org_ratio){
            $width = $height*$org_ratio; 
        } else {
            $height = $width/$org_ratio; 
        } 

    $image_p = imagecreatetruecolor($width, $height); 
    $image = imagecreatefromjpeg($filename); 

    imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $org_width, $org_height);
}

//Function to add Twitter messages to the Twitter website (through the Newsmanager)
function twitterApi($username,$message)
{
    $getUserData = "select twUsername, twPassword from gebruikers where gebruikersnaam = '$username'";
    $checkData = mysql_query($getUserData) or die (mysql_error()); 

        while($tweet = mysql_fetch_object($checkData)){ 

        $twusername = $tweet->username; 
        $twpassword = $tweet->password;
        $status = $message;

            if ($status) {
            $tweetUrl = 'http://www.twitter.com/statuses/update.xml';

                $curl = curl_init();
                curl_setopt($curl, CURLOPT_URL, "$tweetUrl");
                curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 2);
                curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($curl, CURLOPT_POST, 1);
                curl_setopt($curl, CURLOPT_POSTFIELDS, "status=$status");
                curl_setopt($curl, CURLOPT_USERPWD, "$twusername:$twpassword");

                    $result = curl_exec($curl);
                    $resultArray = curl_getinfo($curl);

                if ($resultArray['http_code'] == 200)
                    header("location: ?succes=tweetPosted");
                else
                    header("location: ?error=tweetFailed"); 

                curl_close($curl);

            }

        }

}

//## User functions ##// 



function newUser($gebruikersnaam,$voornaam,$achternaam,$wachtwoord,$gebruikersniveau){ 

    if($wachtwoord !== "" | " " AND $gebruikersnaam !== "" | " "){ 

        $md5wachtwoord = md5($wachtwoord); 

        require("db_connect.inc.php"); 

        $dubbelegebruiker = mysql_query("select * from gebruikers where gebruikersnaam = '$gebruikersnaam'"); 
        $checkdubbel = mysql_num_rows($dubbelegebruiker); 

            if($checkdubbel == 0){ 

                    $nieuwegebruiker = "insert into gebruikers (gebruikersnaam, voornaam, achternaam, wachtwoord, gebruikersniveau) values ('$gebruikersnaam','$voornaam','$achternaam','$md5wachtwoord','$gebruikersniveau')";
                    $checkgebruiker = mysql_query($nieuwegebruiker) or die (mysql_error());

                header("location: ../index.php?page=gebruikers&succes=userCreated"); 

            } else { 

                header("location: ../index.php?page=gebruikers&error=failedCreateUser"); 

            }

    } else { 

            header("location: ../index.php?page=gebruikers&error=noUsernamePassword"); 

        }

}

//## Magazine functions ##//



//## Database functions ##//
function eventLog($username, $action)
{
    $eventlogger = "insert into systemevents (username, action, date) values ('$username','$action', NOW())"; 
    $checklog = mysql_query($eventlogger) or die (mysql_error());  
}

//## Database functions ##//
function insertLog($action, $type, $type_id, $username)
{
    if($type == 'banner'){
        $selectBanner = mysql_query("select soortbanner, titel from banners where id = '$type_id' limit 1");

        while($data = mysql_fetch_object($selectBanner)){
            $details = $data->soortbanner;
            $titel = $data->titel;
        }
    } elseif($type == 'bericht') {
        $selectBanner = mysql_query("select soortbericht, kop, pubStatus from artikelen where id = '$type_id' limit 1");

        while($data = mysql_fetch_object($selectBanner)){
            $details = $data->soortbericht;
            $titel = $data->kop;
            $pubStatus = $data->pubStatus;
        }
    }

    if($type == 'banner' || $type == 'bericht'){

        $username = $_SESSION['gebruikersnaam'];

        $eventlogger = "insert into systemevents (action, type, type_id, details, titel, username, pubStatus) values ('$action', '$type', '$type_id', '$details', '$titel', '$username', '$pubStatus')"; 

        $checklog = mysql_query($eventlogger) or die (mysql_error());
    }
}


function backupDatabase($name,$tables = '*')
{   
    require("db_connect.inc.php"); 

    //get all of the tables
        if($tables == '*')
        {
            $tables = array();
            $result = mysql_query('SHOW TABLES');
            while($row = mysql_fetch_row($result))
            {
                $tables[] = $row[0];
            }
        }
        else
        {
            $tables = is_array($tables) ? $tables : explode(',',$tables);
        }

  //cycle through
  foreach($tables as $table)
 {
    $result = mysql_query('SELECT * FROM '.$table);
    $num_fields = mysql_num_fields($result);

    $return.= 'DROP TABLE '.$table.';';
        $row2 = mysql_fetch_row(mysql_query('SHOW CREATE TABLE '.$table));
    $return.= "\n\n".$row2[1].";\n\n";

    for ($i = 0; $i < $num_fields; $i++) 
    {
        while($row = mysql_fetch_row($result))
        {   
            $return.= 'INSERT INTO '.$table.' VALUES(';
            for($j=0; $j<$num_fields; $j++) 
            {
                $row[$j] = addslashes($row[$j]);
                $row[$j] = ereg_replace("\n","\\n",$row[$j]);
                if (isset($row[$j])) { $return.= '"'.$row[$j].'"' ; } else { $return.= '""'; }
                if ($j<($num_fields-1)) { $return.= ','; }
            }
            $return.= ");\n";
        }
   }
        $return.="\n\n\n";
    }

  //save file
    $handle = fopen('db-backup-'.time().'-'.(md5(implode(',',$tables))).'.sql','w+');
    fwrite($handle,$return);
    fclose($handle);

    header("location: ?succes=backupSucces");
}   ?>

任何可以提供帮助的人?

3 个答案:

答案 0 :(得分:0)

您传入Resultset函数的mysql_fetch_object()不是真正的结果。这就是你得到这个错误的原因。您在($laatsteID

中获得了空结果集

答案 1 :(得分:0)

在您的代码中编辑这两个查询:

"select twUsername, twPassword from gebruikers where gebruikersnaam = '".$username."'"

"select * from gebruikers where gebruikersnaam = '".$gebruikersnaam."'"

答案 2 :(得分:0)

您的错误实际上看起来像是两个完全不同的错误。这完全不同于你仍在使用mysql_query这一事实,现在只有w3schools辍学者。


第一个错误:

  

警告:mysql_fetch_object():提供的参数不是第32行/home/investmp/domains/cashcow.nl/public_html/publiceer/functions.php中有效的MySQL结果资源

让我们看一下lastID函数,其中包含第32行。

function lastID()
{
    $laatsteID = mysql_query("select id from artikelen order by ID DESC limit 1"); 
    $check = mysql_num_rows($laatsteID); 
        if($check !== 0){ 
/*32*/      while($lid = mysql_fetch_object($laatsteID)){ $laatsteID = $lid->id; } 
        } else{ 
            $laatsteID = 0; 
        }
    return $laatsteID;
} 

假设您知道自己拥有哪些表和列,并且SQL有效且查询成功。让我们进一步假设查询将找到一行。

这就是你最终要做的事情:

while ($lid = mysql_fetch_object($laatsteID)) {
    $laatsteID = $lid->id;
}

现在,解释器第一次到达此循环时,$laatsteID将成为结果集。但是在那个循环中,用一个ID覆盖它。当条件表达式再次运行时(为了知道是否退出循环),$laatsteID现在是一些ID值,而不是结果集。因此警告。

要解决此问题,退出回收变量。将结果集和返回值命名为彼此不同。


第二个错误:

  

您的SQL语法有错误;查看与MySQL服务器版本对应的手册,以便在第1行“Premiekoopwoning moet terugkomen”,“eddy”,“publiceren”)附近使用正确的语法

在“terugkomen”之后看到连续两个引号?似乎字符串“Premiekoopwoning moet terugkomen”已经在某种程度上引用了它。因为你没有费心去逃避它们,所以它们会逐字插入查询中。您可能正在发送一个看起来有点像

的查询
insert into systemevents
    (action, type, type_id, details, titel, username, pubStatus)
values (
    'blah', 'blah', 'blah', 'blah',
    ''Premiekoopwoning moet terugkomen'',
    'eddy',
    'publiceren'
)

“Premiekoopwoning”之前的引用结束了字符串。 MySQL正在抱怨“Premiekoopwoning”这个词,因为它现在停止读取一个字符串,并期待一个逗号和另一个字符串(或整数,或表达式的其余部分,或者你有什么)。

现在,要解决此问题,您可以对每个值使用mysql_real_escape_string。这将逃脱引号,以便它们进入数据库而不是被解析为引号......


但坦率地说,存在一个更大的问题: ext/mysql 已弃用,您不应该使用它。

MySQLi PDO 提供相同的功能,还有更多功能。其中的优点:准备好的陈述。 SQL和数据是分开的,所以两者都不会搞砸另一个。

使用mysqli:

if($type == 'banner' || $type == 'bericht'){
    $stmt = $db->prepare("
        INSERT INTO systemevents
            (action, type, type_id, details, titel, username, pubStatus)
        VALUES (?,?,?,?,?,?,?)
    ");
    $stmt->bind_param('sssssss', $action, $type, $type_id, $details, $titel,
             $_SESSION['gebruikersnaam'], $pubStatus);
    $stmt->execute() or die ($stmt->error);
}

PDO没有太大的不同......

if($type == 'banner' || $type == 'bericht'){
    $stmt = $db->prepare("
        INSERT INTO systemevents
             (action, type, type_id, details, titel, username, pubStatus)
        VALUES (?,?,?,?,?,?,?)
    ");
    $stmt->execute(array($action, $type, $type_id, $details, $titel,
             $_SESSION['gebruikersnaam'], $pubStatus))
        or die ($stmt->error);
}

(Mysqli确实提供了旧式的“程序”API ...这很像mysql,只需要一个必需的$link arg。你可以用数据库做任何事情。我个人觉得它很可怕,但是喜欢它的人,通常都是同样想要直接将mysql代码翻译成mysqli的笨蛋。直接翻译不会修复任何代码明显的安全问题。所以我拒绝支持这样做。)