Jump to content

Call to a member function prepare() on null [Solved]


Silence~

Recommended Posts

I'm receiving this error 'Call to a member function prepare() on null' if I were to put this search code into the page. It works fine if i were to put at other pages(for inserting to database).Here's my search code that I've put before the html tags:

<?php//echo '<pre>';//echo $_POST;//echo '</pre>';//declare the form name//$searchForm = htmlentities($_SERVER['PHP_SELF']);try {	//inserts database connections	require('Connections/database.php'); if (($_SERVER['REQUEST_METHOD'] == 'POST') &&  isset($_POST['search']))  {	// array to hold errors	$errorsSearch = array(); 	//create a bad word array	$badwords = array('######','damn','mother######er','###### you');	//Declare variables	$search = $_POST['search'];		//Validations for the $_POST	//check if it's blank	if (trim($search) == "" || !isset($search)) {		$errorsSearch[] = ("Search is blank!");	}	//Check if the text to search is too long	if (isset($search) && strlen(trim($search)) > 50) {	    $errorsSearch[] = ("The text to search is too long!");	}	//Check for any vulgarities	if (isset($search) && in_array($search,$badwords)) {		$errorsSearch[] = ("No vulgarities!");	}	if (empty($errorsSearch)) {	//Declare the sql query	$query = "SELECT * FROM portfolio WHERE nameOfPortfolio LIKE '%$search%'";	//var_dump($query);	$stmt = $database->query($query);	$number_of_rows = $stmt->fetchColumn();	if ($number_of_rows == 0) {		$errorsSearch[]= ("No results! Sorry, please try again!");	}	if ($number_of_rows > 0) {	 //$errors[] = "There is an existing record. You cannot insert another profile! Either update the old one, or delete to insert again.";	  header("Location:searchResults.php");	  exit;	}}	if (isset($errorsSearch) == true)	//foreach($errors as $error){	echo "<div id=search_errors>" .implode("<br>", $errorsSearch) . "</div>";	//printf("%s",$error);}} //end of form processing} //end of try methodcatch(PDOException $e){ // end of database dependent code, handle any errors    $status = empty($query) ? 'Connection failed':" Query failed: $query";    // application message    trigger_error("$status, Error: {$e->getMessage()}, File: {$e->getFile()}, Line: {$e->getLine()}");    // user message    $errorsSearch[] = 'Sorry, this page is not working at this time.';}// done with the database, destroy any pdostatment resource and close connection$stmt = null;$database = null; //the html document that uses any data from the above code starts here -?>

This is my code for getting the data:

         <table width="379" border="0" cellspacing="0" cellpadding="0" style=" border-style: solid" >           <?php           try {          //connect to database          require_once('Connections/database.php');           //Selecting a single row!          $sql = "SELECT * FROM userProfile WHERE user_id in  (                  select id from users where id = ".($_SESSION['user_id']).")";                 //Prepare our SELECT statement.          $statement = $database->prepare($sql);                     //Execute our SELECT statement.          $statement->execute();		             if (!$row  = $statement->fetch(PDO::FETCH_ASSOC)) {               print_r ("No Data to show. Please add in your profile. Navigate your way through the left side of the page where the navigations are.");           }		  if (isset($errors) == true) {			echo "<div id=add_port_errors>" .implode("<br>", $errors) . "</div>";		  }// get method/display code (if any) - get/produce data that's needed to display the page// to edit existing data, if the $data array is empty at this point, retrieve any existing data from the database table?>           <tr>             <th width="auto" scope="row"><div align="left">Profile Picture:</div></th>             <td width="auto"><img src="<?php print htmlspecialchars($row['picPath']); ?>" width="82" height="72">             </td>             <td width="auto"><form name="editProfile" method="post" action="editProfile.php">               <input type="submit" name="edit" id="edit" value="Edit">               </form></td>             </tr>           <tr>             <th scope="row"><div align="left">Username:</div></th>             <td><label><?php print htmlspecialchars($row['username']); ?></label></td>             <td><form name="editProfile" method="post" action="editProfile.php">               <input type="submit" name="edit" id="edit" value="Edit">               </form></td>             </tr>           <tr>             <th scope="row"><div align="left">Name:</div></th>             <td><label><?php print htmlspecialchars($row['Name']); ?></label></td>             <td><form name="editProfile" method="post" action="editProfile.php">               <input type="submit" name="edit" id="edit" value="Edit">               </form></td>             </tr>           <tr>             <th scope="row"><div align="left">Email:</div></th>             <td><label><?php print htmlspecialchars($row['Email']); ?></label></td>             <td><form name="editProfile" method="post" action="editProfile.php">               <input type="submit" name="edit" id="edit" value="Edit">               </form></td>             </tr>           <tr>             <th scope="row"><div align="left">ContactNo:</div></th>             <td><label><?php print htmlspecialchars($row['ContactNo']); ?></label></td>             <td><form name="editProfile" method="post" action="editProfile.php">               <input type="submit" name="edit" id="edit" value="Edit">               </form></td>             </tr>           <tr>             <th scope="row"><div align="left">Skillset:</div></th>             <td><label><?php print htmlspecialchars($row['skillset']); ?></label></td>             <td><form name="editProfile" method="post" action="editProfile.php">               <input type="submit" name="edit" id="edit" value="Edit">               </form></td>             </tr>           <tr>             <th scope="row"><div align="left">Specialization:</div></th>             <td><label><?php print htmlspecialchars($row['Specialization']); ?></label></td>             <td><form name="editProfile" method="post" action="editProfile.php">               <input type="submit" name="edit" id="edit" value="Edit">               </form></td>             </tr>           <tr>             <th scope="row"><div align="left">Introduction:</div></th>             <td><label><?php print htmlspecialchars($row['introduction']); ?></label></td>             <td><form name="editProfile" method="post" action="editProfile.php">               <input type="submit" name="edit" id="edit" value="Edit">               </form></td><?php           } //catch(PDOException $e){ // end of database dependent code, handle any errors$status = empty($query) ? 'Connection failed':" Query failed: $query";// application messagetrigger_error("$status, Error: {$e->getMessage()}, File: {$e->getFile()}, Line: {$e->getLine()}");// user message$errors[] = 'Sorry, this page is not working at this time.';}// done with the database, destroy any pdostatment resource and close connection$stmt = null;$database = null;				                 ?>             </tr>         </table>

My database is correct though, I'm using $database for all the connections, i didn't change the variable name. I'm not sure why it wouldn't initialized. Is my select query wrong? ;-;

Edited by Silence~
Link to comment
Share on other sites

Check to see if $database has what you think it does by checking its value

//Prepare our SELECT statement.var_dump($database);$statement = $database->prepare($sql);
Link to comment
Share on other sites

 

Check to see if $database has what you think it does by checking its value

//Prepare our SELECT statement.var_dump($database);$statement = $database->prepare($sql);

Tried it and it says null. Does that mean my database connection being null or my query being null? It works though if i didn't put the search code in.. o.o

Link to comment
Share on other sites

It means the database connection is null.

 

It seems you're setting it to null right on this line:

// done with the database, destroy any pdostatment resource and close connection$stmt = null;$database = null;
  • Like 1
Link to comment
Share on other sites

 

It means the database connection is null.

 

It seems you're setting it to null right on this line:

// done with the database, destroy any pdostatment resource and close connection$stmt = null;$database = null;

Ah yes, thank you! This was one of the cause >< But why would that affect though? I thought by requiring the database connection again, it should be okay?Anyways, it gives this: object(PDO)#1 (0) { } for the vardump. I have data inside though?

Link to comment
Share on other sites

It should work that way, yes, but I'm not sure what your database.php file looks like. There might be something in there causing the problem.

 

Ideally, you should open the connection just once for the entire page. There's no need to manually close the connection, it closes automatically when the script stops running.

Link to comment
Share on other sites

It should work that way, yes, but I'm not sure what your database.php file looks like. There might be something in there causing the problem.

 

Ideally, you should open the connection just once for the entire page. There's no need to manually close the connection, it closes automatically when the script stops running.

My database file looks like this:

try {$user = ""; //taken out just in case$pass = "";$database = new PDO('mysql:host=localhost;dbname=final_year_project_1;charset=utf8', $user, $pass, array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));}catch (PDOException $ex) {	echo 'Connection failed: ' . $ex->getMessage();}																						  

When you mean open the connection, i just have to require the file right? Must I put it in the try catch?(because I already put it in the database file?) or like put the search code and the select code together? I close it because i thought that it can be sql inject(or something like that) ? ;-;

Link to comment
Share on other sites

Are you getting a "Connection failed" message on your page? That would explain $database being null.

 

SQL injection happens when you put user data in a query, it doesn't have to do with how long you keep a connection open.

Link to comment
Share on other sites

Are you getting a "Connection failed" message on your page? That would explain $database being null.

 

SQL injection happens when you put user data in a query, it doesn't have to do with how long you keep a connection open.

Nope I didn't. I get the error message beside the one I stated above:

if (!$row  = $statement->fetch(PDO::FETCH_ASSOC)) {   print_r ("No Data to show. Please add in your profile. Navigate your way through the left side of the page where the navigations are.");}

Oh okay, thanks for the explanation :)

Link to comment
Share on other sites

Well, it's not null anymore, what happens when you call prepare() on it?

I'm not sure what you mean by this, I put var_dump($database) and var_dump($statement) and this is the results:

object(PDOStatement)#2 (1) { ["queryString"]=> string(99) "SELECT * FROM userProfile WHERE user_id in ( select id from users where id = 1)" }

Link to comment
Share on other sites

What I'm asking is if you're still getting errors and what errors you are getting.

...There's no errors, it works fine now. Somehow my data got deleted away in my database.. :| So, it was actually my data that is not there in the first place? But it was there when i tried yesterday ><

Link to comment
Share on other sites

You used require_once. Like the name implies, if you use that to include the same file multiple times it's only going to include it once. If you want to include a file multiple times then use include or require instead of require_once.

  • Like 1
Link to comment
Share on other sites

You used require_once. Like the name implies, if you use that to include the same file multiple times it's only going to include it once. If you want to include a file multiple times then use include or require instead of require_once.

Thanks, I think this is the case ^^

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...