PHP error report script - PDO::prepare not working

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
I have a script set up so that if there is an error on any page a PM is sent directly to me. The only problem is, that whenever there is an error I always get the same error:

Fatal error: Call to a member function prepare() on a non-object in home/sikuneh/public_html/inc/SL_modules.php on line 26

The only problem is, everything checks out and looks perfectly fine.

PHP:
PHP:
	$closingString = "Error with script. The webmaster has already been notified.";
	echo $closingString;
	
	$sth = $dbh->prepare("INSERT INTO mail VALUES(0,:T,:F,:S,:M,now(),0)");
		$sth->bindValue(":T",'10');
		$sth->bindValue(":F",'10');
		$sth->bindValue(":S",'Error(s)');
		$sth->bindValue(":M",$logstring);
	$sth->execute();

DB structure:
Id, toUser, from, subject, message, date, read

Please help.
 

lemon-tree

x10 Minion
Community Support
Messages
1,420
Reaction score
46
Points
48
Have you actually created the PDO object called $dbh? This error usually arises from something going awry in the connection phase.
 
Last edited:

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
Yeah, it's working on all my other pages... Wait a second, if I call this page using an AJAXREQUEST can it still use variables defined on an include that was called at the top of the page (the one making the ajax request)?
 
Last edited:

dlukin

New Member
Messages
427
Reaction score
25
Points
0
You mean you have foo.php making an Ajax request to bar.php?

They will be two different instances. bar.php will not be able to access anything from when foo.php ran (except, of course, values passed in the query string or POST data).
 

zapzack

New Member
Messages
606
Reaction score
19
Points
0
I don't think so.. If your saying your using ajax to include a php page that includes variables from the page your including it from..
 

lemon-tree

x10 Minion
Community Support
Messages
1,420
Reaction score
46
Points
48
The variables cannot travel over as the execution of the first page has finished before the second page is being called by the AJAX. You will need to re-specify the PDO connection and then you can transfer data to the browser in the AJAX as either plain text or in XML format.
 

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
No, it still doesn't work. I have no idea what's wrong still. I referenced both my module page and the dbc page on each but it still doesn't work.
 

dlukin

New Member
Messages
427
Reaction score
25
Points
0
No code.
No url.
No information on the AJAX call.
No information if the same error is happening.

How do you expect help?
 

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
Ok, here goes:

Requested page (via ajax):
PHP:
<?php #Admin delete post 
DEFINE("CURPAGE","DELETEPOSTADMIN.php");
session_start();
include("dbc.php");
include("../SL_modules.php");
if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] != 'Admin Sikuneh') {
	echo "You do not have permission to view this page";
} else {
$postID = $_GET['id'];

$sth = $dbh->prepare("SELECT * FROM submissions WHERE id = '$postID'");
$sth->execute();
if($sth->columncount() === 0)
	echo "Error: Cannot find post.";
else {
	try{
	$sth2 = $dbh->prepare("UPDATE submissions SET status = '2' WHERE id = '$postID'");
	$sth2->execute();
	} catch(PDOException $e) {
	writeError($e->getMessage(),CURPAGE);
	}
		try{
		echo "Post $postID has been deleted.";
#Problem here
		$sth3 = $dbh->query("SELECT submitter FROM submissions WHERE id = '$postID'");
		while($row=$sth3->fetch()) 
			$poster = $row['submitter'];
		$sth4 = $dbh->query("SELECT id FROM users WHERE username = '$poster'");
		while($row=$sth4->fetch())
			$posterID = $row['id'];
		$mailMessage = "Your post has been deleted by the administrator.";
		$mailSubject = "Post deleted";
		$sth4 = $dbh->exec("INSERT INTO mail(id,toUser,'from',subject,message,date,read) VALUES(0,'$posterID','10','$mailSubject','$mailMessage',now(),0)");
		} catch(PDOException $e) {
		writeError($e->getMessage(),CURPAGE);
		}

}
}
?>

Page that calls the Ajax:
PHP:
<?php if(!isset($_SESSION['admin_login'])) { ?>
You do not have permission to view this page
<?php } else {?>
include("dbc.php");
<h2 style="margin-top:0; padding-top:5px;">Administration for Submission Lore</h2>
<style type="text/css">
table#admin_entries a:link,
table#admin_entries a:visited
{
color:#FFF;
}
</style>
<script type="text/javascript">
function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (tryMS) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
      }
    }
  }    
  return request;
}

function confirmEntry(id,box){

request = createRequest();
   var url= 'inc/admin/addEntry.php?id='+id+'&&session=Admin Sikuneh&&sid='+Math.random();   
   request.onreadystatechange = function() {
     if (request.readyState == 4) {
        if (request.status == 200) {
           document.getElementById(box).innerHTML = request.responseText;
           setTimeout("updateStatus()",5000);
        }
     }
  }
request.open("GET", url, true);
request.send(null);
}

function deleteEntry(id,box){

request = createRequest();
	var url= 'inc/admin/deletePostAdmin.php?id='+id+'&&session=Admin Sikuneh&&sid='+Math.random();
      request.onreadystatechange = function() {
     if (request.readyState == 4) {
        if (request.status == 200) {
           document.getElementById(box).innerHTML = request.responseText;
           setTimeout("updateStatus()",5000);
        }
     }
  }

request.open("GET", url, true);
request.send(null);
}

function restoreEntry(id,box){

request = createRequest();
   var url = 'inc/admin/restorePostAdmin.php?id='+id+'&&session=Admin Sikuneh&&sid='+Math.random();
      request.onreadystatechange = function() {
     if (request.readyState == 4) {
        if (request.status == 200) {
           document.getElementById(box).innerHTML = request.responseText;
           setTimeout("updateStatus()",5000);
        }
     }
  }

request.open("GET", url, true);
request.send(null);
}

function placeOnHold(id,box) {

request = createRequest();
   var url = 'inc/admin/onHold.php?id='+id+'&&session=Admin Sikuneh&&sid='+Math.random();
      request.onreadystatechange = function() {
     if (request.readyState == 4) {
        if (request.status == 200) {
           document.getElementById(box).innerHTML = request.responseText;
           setTimeout("updateStatus()",5000);
        }
     }
  }
request.open("GET", url, true);
request.send(null);
}

function updateStatus(){

request = createRequest();
	var url= 'inc/admin/admin_checkentries2.php?sid='+Math.random();
      request.onreadystatechange = function() {
     if (request.readyState == 4) {
        if (request.status == 200) {
           document.getElementById("place").innerHTML = request.responseText;
        }
     }
  }
 request.open("GET", url, true);
request.send(null);

}

window.onload=updateStatus;
</script>
<div id="place" style="width:100%"></div>

<h2>Most recent errors:</h2>
<div style="font-size:10px;">
<?php 
include("Logs/errors.log");
?>
</div>
<?php } ?>

Database connection page (dbc.php):
PHP:
<?php
$host = "localhost";
$dbname = dbname;
$username = dbusername;
$password = dbpassword;
   try
   {
     $dbh = new PDO("mysql:host=$host;dbname=$dbname", $username,$password);
     $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   }
   catch (PDOException $e)
   {
     print ("Could not connect to server.\n");
     writeError($e->getMessage());
   }
   ?>

Module which is giving trouble:
PHP:
include("dbc.php");
# Error write script
function writeError($error,$page) {
	if($page == null) 
		$page = "INDEX.PHP";
	# Get the current date
	$date = date('r');
	# Where, when and what
	$logstring = "Error on page $page at line $location on $date ERROR: $error\n";
	# Open the file
	$fp = fopen("http://sikuneh.x10hosting.com/Logs/errors.log",'a');
	# Write to it
	fwrite($fp,$logstring);
	# Close
	fclose($fp);

    $closingString = "Error with script. The webmaster has already been notified."; 
    echo $closingString; 
     
    $sth = $dbh->prepare("INSERT INTO mail VALUES(0,:T,:F,:S,:M,now(),0)"); 
        $sth->bindValue(":T",'10'); 
        $sth->bindValue(":F",'10'); 
        $sth->bindValue(":S",'Error(s)'); 
        $sth->bindValue(":M",$logstring); 
    $sth->execute(); 
}

I would like to give you a live URL but this is on the admin page and it would take me a day or two to recreate an example. Yes it is the same error. GL.
 

dlukin

New Member
Messages
427
Reaction score
25
Points
0
Page that calls the Ajax:
PHP:
<?php if(!isset($_SESSION['admin_login'])) { ?>
You do not have permission to view this page
<?php } else {?>
include("dbc.php");  <<<<<<<<<<<<<< ??????
<h2 style="margin-top:0; padding-top:5px;">Administration for Submission Lore</h2>
<style type="text/css">

That "include" is outside php tags. I have no idea why that is there.
 

misson

Community Paragon
Community Support
Messages
2,572
Reaction score
72
Points
48
Database connection page (dbc.php):
PHP:
...
   try
   {
     $dbh = new PDO("mysql:host=$host;dbname=$dbname", $username,$password);
     $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
   }
   catch (PDOException $e)
   {
     print ("Could not connect to server.\n");
     writeError($e->getMessage());
   }
   ?>
If the DB connection fails, how is writeError (which relies on a DB connection) supposed to succeed? Furthermore, the script that defines writeError() depends on dbc.php, so writeError() cannot be defined when you create the DB connection.

Module which is giving trouble:
PHP:
# Error write script 
function writeError($error,$page) { 
    ...
    # Where, when and what 
    $logstring = "Error on page $page at line $location on $date ERROR: $error\n"; 
    # Open the file 
    $fp = fopen("http://sikuneh.x10hosting.com/Logs/errors.log",'a'); 
    ...
    $sth = $dbh->prepare("INSERT INTO mail VALUES(0,:T,:F,:S,:M,now(),0)");
$location and $dbh are local and undefined. A global $dbh will help with the latter (except when creating the DB connection fails). You need to read up on variable scope.

I'd be quite surprised if you can have write access to an HTTP URL. I suspect you'll need to change the file name in the fopen() call.

The *Entry(), placeOnHold() and updateStatus() functions in the page that makes the AJAX calls are very similar in form and function. Avoid code duplication; refactor them.


Requested page (via ajax):
PHP:
$sth = $dbh->prepare("SELECT * FROM submissions WHERE id = '$postID'");
$sth->execute();
This should be inside a try block

PHP:
...
    try{
    ...
    } catch(PDOException $e) {
        writeError($e->getMessage(),CURPAGE);
    }
    ...
    try{
    } catch(PDOException $e) {
        writeError($e->getMessage(),CURPAGE);
    }
There's no need for separate try/catch blocks. It just makes things harder to read.
 
Last edited:

as4s1n

New Member
Messages
174
Reaction score
4
Points
0
Well, I guess since this is just a test site this is to be expected. I've been practicing on this site and this block of code is older (mostly because I was practicing AJAX). I haven't really updated this since a few months ago I changed to PDO. I guess I might as well recreate it from scratch. Thanks for the help, although, I'm not sure if everything is fixed yet.
 
Top