-8

I get an error if I try to publish an article on my CMS.

The error:

Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in /home/investmp/domains/cashcow.nl/public_html/publiceer/functions.php on line 32 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Premiekoopwoning moet terugkomen'', 'eddy', 'publiceren')' at line 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");
}   ?>

Anyone who could help?

MitchellFR
  • 11
  • 1
  • 6
  • [Please, don't use `mysql_*` functions](http://stackoverflow.com/q/12859942/1190388) in new code. They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the red box? Learn about prepared statements instead, and use [tag:PDO] or [tag:MySQLi]. – hjpotter92 May 14 '13 at 12:41
  • -1 for using ext/mysql in 2013. – cHao May 14 '13 at 12:41
  • 3
    1. isolate relevent part of the code where error is(too much code here). 2. print how your complete sql query looks like. – Bojan Kovacevic May 14 '13 at 12:41
  • Which line of code exist in your 32 line number in above code snippet?in /home/investmp/domains/cashcow.nl/public_html/publiceer/functions.php on line 32 – Smile May 14 '13 at 12:44
  • @NullVoid: Unless he's gone and mangled the PHP code, it's the line in `lastId()` that reads `while($lid = mysql_fetch_object($laatsteID)){ $laatsteID = $lid->id; }`. – cHao May 14 '13 at 12:46
  • possible duplicate of [Warning: mysql\_fetch\_object(): supplied argument is not a valid MySQL result resource](http://stackoverflow.com/questions/3923101/warning-mysql-fetch-object-supplied-argument-is-not-a-valid-mysql-result-res) – hakre Jun 06 '13 at 08:44

3 Answers3

0

The Resultset you're passing in mysql_fetch_object() function is not a really result. That's why you're getting that error. You're getting empty result set in ($laatsteID)

Smile
  • 2,770
  • 4
  • 35
  • 57
  • Empty result sets are fine. It's a result with 0 rows, but the code that fetches the next row from it won't mind; it'll return `false`, indicating no more rows, but not an error. You'd only get a complaint if the query failed, which would lead to the query function returning `false` and the code trying to fetch a result from `false`. – cHao May 14 '13 at 12:47
0

edit these two queries in your code:

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

"select * from gebruikers where gebruikersnaam = '".$gebruikersnaam."'"
abdul quadir
  • 24
  • 1
  • 7
  • What exactly do you think this will accomplish? `"a string containing $variable"` and `"a string containing " . $variable` produce exactly the same result. – cHao May 14 '13 at 12:51
  • $username and $gebruikersnaam treated string as this way.you have used single quotes for both which is used for integer value only. – abdul quadir May 14 '13 at 12:54
  • PHP stringifies variable values when it interpolates. The type of `$username` barely matters at all. (Arrays would stringify to the word "Array", and `false` and `null` to empty strings. But integers, strings, and even objects that have a `__toString` method would all work just fine.) `$x = "stuff"; $out = "some '$x'\n"; print $out;` will print out `some 'stuff'`. – cHao May 14 '13 at 14:04
0

Your error actually looks like two entirely separate errors. And that's totally aside from the fact that you're still using mysql_query, which only w3schools dropouts do now.


Error the first:

Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in /home/investmp/domains/cashcow.nl/public_html/publiceer/functions.php on line 32

Let's take a look at the lastID function, which includes line 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;
} 

Let's assume you know what tables and columns you have, and the SQL is valid and the query succeeds. Let's further assume the query will find a row.

This is what you'll end up doing:

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

Now, the first time the interpreter reaches this loop, $laatsteID will be a result set. But in that loop, you overwrite it with an ID. When the condition expression runs again (which it has to, in order to know whether to exit the loop), $laatsteID is now some ID value, not a result set. Hence the warning.

To fix this, quit recycling variables. Name your result set and your return value differently from each other.


Error the second:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Premiekoopwoning moet terugkomen'', 'eddy', 'publiceren')' at line 1

See the two quotes in a row, right after "terugkomen"? It appears that the string "Premiekoopwoning moet terugkomen" somehow already has quotes around it. And since you didn't bother to escape them, they're getting inserted into the query verbatim. You're probably sending a query that looks a little bit like

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

The quote preceding "Premiekoopwoning" ends the string. And MySQL is complaining about the word "Premiekoopwoning", cause it's stopped reading a string now and is expecting a comma and another string (or integer, or the rest of an expression, or what have you).

Now, to fix this, you could use mysql_real_escape_string on each value. That'll escape the quotes so that they go into the DB instead of being parsed as quotes...


But frankly, there's a bigger problem: ext/mysql is deprecated, and you shouldn't be using it.

MySQLi and PDO offer the same functionality, and a lot more. Among the advantages: prepared statements. The SQL and data are kept separate, so neither can mess up the other.

With 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 is not too much different...

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 does offer the old-style "procedural" API as well...which is a lot like mysql's, just with a required $link arg for everything. You can do everything with the database either way. I personally find it hideous, though....and the people who like it, are often enough the same schmucks who just want to straight translate mysql code to mysqli. Straight translation won't fix any of their code's blatant security problems. So i refuse to support doing so.)

Community
  • 1
  • 1
cHao
  • 84,970
  • 20
  • 145
  • 172