Fatal error: Call to a member function bind_param() on a non-object in

Not sure about using PDO, so I tried this (I think this is correct):

[php]$compagnie = “ggfgfgdfgfgdf”;
$stmt = $con->prepare(“SELECT form_corpo_testID from form_corpo_test WHERE ggfgfgdfgfgdf = :company”);
$stmt->bindParam(’:company’, $compagnie);
$stmt->execute();[/php]

I got the same error as before. But, what is interesting, is that right now, I still have this line of coding which, if removed, screws up the whole code. Right now, the original connection was commented and replaced by yours with the word ‘defined’ (the 4 code line with that same word):
[php]
try {
$con = new PDO(“mysql:host=$hostname;dbname=$db”, $username, $password);
/*** echo a message saying we have connected ***/
echo ‘Connected to database
’;
[/php]

I’m pretty confused right now. Would you like to see the integral code for that page? Maybe I have some coding that shouldn’t be there. But since I’m not really proficient with PDO, the coding might mean more to you than me.

You can try posting the code you have now. It should be really easy to use this, but I haven’t tried the code I posted in PHP 5.2 so there may be something that isn’t compatible, somewhere.

It’s possible.

Btw, I changed $con to $pdoConn when I would do the tests (as I didn’t know if it would have had any actual impact in relation to db.php). But, I revert it back to $con afterwards. Lemme know is if I should change it permanently (assuming it has an actual impact with your code. I was unsure)

I also deleted all the coding that was related to my picture uploads (which shouldn’t in any way affect the rest of the code).

[php]<?php
include (‘config.php’);
// The following checks to see whether PDO is enabled or not.

/*if (!defined(‘PDO::ATTR_DRIVER_NAME’)) {
echo ‘PDO unavailable’;
}
elseif (defined(‘PDO::ATTR_DRIVER_NAME’)) {
echo ‘PDO available’;
}
*/

/*** hostname ***/
//$hostname = ‘127.0.0.1’;
//$hostname = ‘localhost’;

/*** username /
//$username = '
****’;

/*** password /
//$password = '
****’;

/*** database name /
//$db = '
****’;

// verifies there is actually a pass
//var_dump(DB_PASS);

define(‘DB_HOST’, ‘127.0.0.1’);
define(‘DB_USER’, ‘’);
define(‘DB_PASS’, '
’);
define(‘DB_NAME’, ‘*******’);

require_once (‘db.php’);

//This gets all the other information from the form
// mysql_real_escape_string to escape sepcial character, a.k.a. some forms of sql injections
$compagnie=mysql_real_escape_string($_POST[‘company’]);
$telephone=mysql_real_escape_string($_POST[‘phone’]);
$site_web=mysql_real_escape_string($_POST[‘website’]);
$texte_fr=mysql_real_escape_string($_POST[‘messagefr’]);
$texte_en=mysql_real_escape_string($_POST[‘messageen’]);
$categories=mysql_real_escape_string($_POST[‘categories’]);
$profil_exposant=mysql_real_escape_string($_POST[‘profession’]);
$stands_du_manufacturier=mysql_real_escape_string($_POST[‘manufacturiers_stand’]);
$pourcentage_quebec=mysql_real_escape_string($_POST[‘percent_quebec’]);
$pourcentage_canada=mysql_real_escape_string($_POST[‘percent_canada’]);
$pourcentage_usa=mysql_real_escape_string($_POST[‘percent_usa’]);
$pourcentage_autre=mysql_real_escape_string($_POST[‘percent_autre’]);
$exporte=mysql_real_escape_string($_POST[‘bt_export’]);
$exporte_souhaite=mysql_real_escape_string($_POST[‘bt_export_souhaite’]);
$produits_vert=mysql_real_escape_string($_POST[‘bt_prod_verts’]);
$nouveau_produits=mysql_real_escape_string($_POST[‘bt_new_prod’]);
$nom=mysql_real_escape_string($_POST[‘name’]);
$courriel=mysql_real_escape_string($_POST[‘email’]);
$telephone_ressource=mysql_real_escape_string($_POST[‘resource_phone’]);
$personne_ressource_c_toi=mysql_real_escape_string($_POST[‘personne_ressource’]);
$autre_personne_ressource=mysql_real_escape_string($_POST[‘backup_name’]);
$autre_courriel=mysql_real_escape_string($_POST[‘backup_email’]);
$autre_telephone=mysql_real_escape_string($_POST[‘backup_phone’]);

if(count($cats) > 0)
{
$str = implode(",", $cats);
}

// implodes makes the values as a string!
// in the values part when inserting it, you will have to use ‘$str’ instead of $_POST[$cats];
$cats = array();
if($_SERVER[‘REQUEST_METHOD’] == ‘POST’) {
if(isset($_POST[‘cats’])) {
$cats = implode(",", $_POST[‘cats’] );
}
$categories= $_POST[‘categories’];

$str = $categories . ": " . $cats;
//echo $str;

}

try {
$con = new PDO(“mysql:host=$hostname;dbname=$db”, $username, $password);
/*** echo a message saying we have connected ***/
//echo ‘Connected to database
’;

$stmt = $con->prepare(“INSERT INTO form_corpo_test VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)”);

if (!$stmt) {
$error = $stmt->errorInfo();
echo 'PDO error: ’ . $error[2] . ‘(’ . $stmt->errorCode() . ‘)’;

} else {
$stmt->execute(array(
$_POST[‘company’], $_POST[‘phone’], $_POST[‘website’], $_POST[‘messagefr’], $_POST[‘messageen’], $str, $_POST[‘profession’], $_POST[‘manufacturiers_stand’], $_POST[‘percent_quebec’], $_POST[‘percent_canada’], $_POST[‘percent_usa’], $_POST[‘percent_autre’], $_POST[‘bt_export’], $_POST[‘bt_export_souhaite’], $_POST[‘bt_prod_verts’], $_POST[‘bt_new_prod’], $_POST[‘name’], $_POST[‘email’], $_POST[‘resource_phone’], $_POST[‘personne_ressource’], $_POST[‘backup_name’], $_POST[‘backup_email’], $_POST[‘backup_phone’]
));

if (!$stmt) {
   $error = $stmt->errorInfo();
   echo 'PDO error: ' . $error[2] . '(' . $stmt->errorCode() . ')';
} else {
   
   echo 'Insert OK';
}

}

/*** close the database connection ***/

$con = null;
}

catch(PDOException $e)
{
echo $e->getMessage();
}

?>[/php]

What is in config.php?

One (unrelated) problem here:
[php] // verifies there is actually a pass
//var_dump(DB_PASS);

define('DB_HOST', '127.0.0.1');
define('DB_USER', '*******');
define('DB_PASS', '*******');
define('DB_NAME', '*******');[/php]

You can’t var_dump/print/echo/use a variable/constant before setting it :slight_smile:

[hr]

mysql_real_escape_string is actually not bullet proof against sql injection. And when using PDO/Mysqli you don’t need to do it.

[hr]

[php]$con = new PDO(“mysql:host=$hostname;dbname=$db”, $username, $password);[/php]

In the code you provided the variables here are not set. Guessing they are in the config file.

Yes, you mean the loooooong bunch of text? lol, yeah, I never bothered removing that as it didn’t cause any interference.

Right, -_- should have placed that AFTER. I don’t know why I placed the var_dump before the 4 defined parameters.

You know, I made the config file long ago and never really looked back. Although, I wasn’t looking at that files concerning what you asked. Actually, I had set them at the very top of the coding prior to what is below. Except that I commented it, as I believed that I was calling them using the word ‘define’.

[php]<?php
ob_start();
session_start();

// host, db username, db pass, db name - these are the same as in the functions.php
define(‘DBHOST’,‘localhost’);
define(‘DBUSER’,’******’);
define(‘DBPASS’,’******’);
define(‘DBNAME’,’******’);

// make a connection to mysql here
$conn = @mysql_connect (DBHOST, DBUSER, DBPASS);
$conn = @mysql_select_db (DBNAME);
if(!$conn){
die( “Sorry! There seems to be a problem connecting to our database.”);
}

// define site path
define(‘DIR’,‘http://*****/formulaires/’);

// define admin site path - KEEP the slash admin path portion!!!
//define(‘DIRADMIN’,‘http://*****/formulaires/’);

// define site title for top of the browser
define(‘SITETITLE’,‘Programming’);

//define include checker
define(‘included’, 1);

?>[/php]

Ok, there are some errors here.

You are including the db file but you are never instantiating the object
The DB class will actually handle all the connection stuff, all the exception handling, etc.

It would be way easier to sit down at the same computer and show you this stuff, because I think we’re talking past eachother from time to time.

I’m gonna throw together a (hopefully) working copy of how this code should look.

I haven’t been taught everything I should know about PHP, that’s for sure. I’ve mostly tried teaching myself, as well as learning from others. We were taught to be Web Designers (Design + Front end mostly). But, I am keen in grasping more about PHP.

Unfortunately for me, I tend to have a narrow view (as in, having difficulty looking outside the box). So, any help is always appreciated. I tend to comment a lot (I mean code wise), so that I can understand it better (and others who may need similar code).

Code code should in most cases speak for itself, so commenting is actually not really necessary in the extent you describe.

anyway

db.php, remember to change line 32 to reflect your login details. Just try to write them in / hard code it for now
[php]<?php

class db {

/**
*
* PDO connection
* @var PDO
*/
private $pdoConn = null;

/**
* Class constructor
*/
public function __construct() {
$this->_initDb();
}

/**
* Get PDO database connection
*
* @return
*/
public function getPDOConn() {
return $this->pdoConn;
}

/**
* Init db connection based on config
*/
private function _initDb() {
$this->pdoConn = new PDO(‘mysql:dbname=database_name;host=localhost;charset=utf8’, ‘database_name’, ‘database_password’);
$this->pdoConn->exec(“set names utf8”);
$this->pdoConn->setAttribute(PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
$this->pdoConn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}

/**
* Executes parametarized query
* @param string $query
* @param array $params
* @param string $fetch_method
*/
public function query($query, $params = [], $fetch_method = ‘OBJ’) {
$stmt = $this->pdoConn->prepare($query);

  $result = $stmt->execute($params);
  
  if ($result) {
     $querybit = explode(" ", $query);
     if (trim($querybit[0]) == 'SELECT') {
        $ret = $stmt->fetchAll(constant('PDO::FETCH_' . strtoupper($fetch_method)));
     } else {
        return array(TRUE);
     }
  }      
  
  return !empty($ret) ? $ret : null;

}

/**
* Get last inserted id
*
* @return integer
*/
public function getLastInsertedId() {
return $this->pdoConn->lastInsertId();
}

/**
* Wrapper for mysql_real_escape_string
*
* @param string $string
* @return string
*/
protected function _escape($string) {
return mysql_real_escape_string($string);
}

}[/php]

the php file
[php]<?php
ini_set(‘error_reporting’, E_ALL);
ini_set(‘display_errors’, ‘1’);

require_once (‘db.php’);

$db = new db();

//This gets all the other information from the form and adds them to an array
$data = array();
$data[‘compagnie’] = !empty($_POST[‘company’]) ? $_POST[‘company’] : ‘’;
$data[‘telephone’] = !empty($_POST[‘phone’]) ? $_POST[‘phone’] : ‘’;
$data[‘site_web’] = !empty($_POST[‘website’]) ? $_POST[‘website’] : ‘’;
$data[‘texte_fr’] = !empty($_POST[‘messagefr’]) ? $_POST[‘messagefr’] : ‘’;
$data[‘texte_en’] = !empty($_POST[‘messageen’]) ? $_POST[‘messageen’] : ‘’;
$data[‘categories’] = !empty($_POST[‘categories’]) ? $_POST[‘categories’] : ‘’;
$data[‘profil_exposant’] = !empty($_POST[‘profession’]) ? $_POST[‘profession’] : ‘’;
$data[‘stands_du_manufacturier’] = !empty($_POST[‘manufacturiers_stand’]) ? $_POST[‘manufacturiers_stand’] : ‘’;
$data[‘pourcentage_quebec’] = !empty($_POST[‘percent_quebec’]) ? $_POST[‘percent_quebec’] : ‘’;
$data[‘pourcentage_canada’] = !empty($_POST[‘percent_canada’]) ? $_POST[‘percent_canada’] : ‘’;
$data[‘pourcentage_usa’] = !empty($_POST[‘percent_usa’]) ? $_POST[‘percent_usa’] : ‘’;
$data[‘pourcentage_autre’] = !empty($_POST[‘percent_autre’]) ? $_POST[‘percent_autre’] : ‘’;
$data[‘exporte’] = !empty($_POST[‘bt_export’]) ? $_POST[‘bt_export’] : ‘’;
$data[‘export_souhaite’] = !empty($_POST[‘bt_export_souhaite’]) ? $_POST[‘bt_export_souhaite’] : ‘’;
$data[‘produits_vert’] = !empty($_POST[‘bt_prod_verts’]) ? $_POST[‘bt_prod_verts’] : ‘’;
$data[‘nouveau_produits’] = !empty($_POST[‘bt_new_prod’]) ? $_POST[‘bt_new_prod’] : ‘’;
$data[‘nom’] = !empty($_POST[‘name’]) ? $_POST[‘name’] : ‘’;
$data[‘courriel’] = !empty($_POST[‘email’]) ? $_POST[‘email’] : ‘’;
$data[‘telephone_ressource’] = !empty($_POST[‘resource_phone’]) ? $_POST[‘resource_phone’] : ‘’;
$data[‘personne_ressource_c_toi’] = !empty($_POST[‘personne_ressource’]) ? $_POST[‘personne_ressource’] : ‘’;
$data[‘autre_personne_ressource’] = !empty($_POST[‘backup_name’]) ? $_POST[‘backup_name’] : ‘’;
$data[‘autre_courriel’] = !empty($_POST[‘backup_email’]) ? $_POST[‘backup_email’] : ‘’;
$data[‘autre_telephone’] = !empty($_POST[‘backup_phone’]) ? $_POST[‘backup_phone’] : ‘’;

// run db query and enter the entire data array at once. Note that you could/should
// write a function that automatically generates the ?,?,? string based on the parameters (count($array))
$result = $db->query("INSERT INTO form_corpo_test (company,
phone,
website,
messagefr,
messageen,
categories,
profession,
manufacturiers_stand,
percent_quebec,
percent_canada,
percent_usa,
percent_autre,
bt_export,
bt_export_souhaite,
bt_prod_verts,
bt_new_prod,
name,
email,
resource_phone,
personne_ressource,
backup_name,
backup_email,
backup_phone)

                                               VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", $data);

if (!$result) {
echo ‘aww, something bad happened, it should have been catched by the try/catch inside the DB class…’;
}

// … the rest of your code[/php]

That should actually be all you need to do to run a query, the DB class should handle creating a connection object and handling exceptions.

I fixed one mistake (in the insert into), it was actually compagnie and so on. Or else it was trying to insert into columns that didn’t exist.

Although for now, upon further testing, it found two errors.
The first one is your text, which I assume has to do with the fact that it couldn’t actually insert the data? The above seemed correct though o_O

The second which doesn’t make any sense, as it was working before. So, I will muffle it! For now anyhow.

[php]
aww, something bad happened, it should have been catched by the try/catch inside the DB class…
Notice: Use of undefined constant dirExists - assumed ‘dirExists’ in /home/product/public_html///processForm-test.php on line 129[/php]

were you successful in running the insert? :slight_smile:

I need some sleep lol. :stuck_out_tongue:

Not at all. I didn’t have time to look at it thoroughly yesterday. I will now recheck the coding more in depth.

… Ok, so I’ve been playing with it, confirming that the column ‘company’ does not exist (meaning that I am right concerning the word ‘compagnie’. Yet, it refuses to place the data inside the column. Why would it do that. Unless lack of sleep has the better of me (in which case what I tried didn’t make sense), I have tried using your line of code:

[php] if (!$result) {
echo ‘aww, something bad happened, it should have been catched by the try/catch inside the DB class…’;
}[/php]

I duplicated it and removed the exclamation mark. In the hopes that it would tell me that is has received the results inside the db. The initial message appeared, stating that it hadn’t. But nothing more.

It can’t be a connection issue, so then it has to be the data not being sent.

Before you do anything else, try to do simpler select / insert queries, just to check that it works.

Do you mean to know whether or not I can actually insert something in? I’ve done that with MySQLi (and it worked flawlessly), that is before I wanted to secure the code. If you mean using PDO, I am failing spectacularly at it, as I’m brand new to PDO.

I tried this, among different things:

[php]try {
$con = new PDO(“mysql:host=$hostname;dbname=$db”, $username, $password);

$count = $db->exec(“SELECT FROM form_corpo_test WHERE compagnie = ‘ggfgfgdfgfgdf’”);

return $count->result();
print $count->show_message(“Success”);

/*** close the database connection ***/

$con = null;
}

catch(PDOException $e)
{
echo $e->getMessage();
}[/php]

And it gives me an error (I was checking it online, and everything is all about codeIgniter or other things which doesn’t help).

[php]

Catchable fatal error: Object of class db could not be converted to string in /home/product/public_html/*****/formulaires/processForm-test.php on line 43[/php]

I mean using the DB class. Instead of running the complex query we set up there just try to run a simple select query to see if the db connection and querying is actually working.

then you can figure out a query which works (seems like you already have)

at this point you know it’s the data you are inserting there is something fishy with.

This should be enough to run a query
[php]<?php
ini_set(‘error_reporting’, E_ALL);
ini_set(‘display_errors’, ‘1’);

require_once (‘db.php’);

$db = new db();

$result = $db->query(‘SELECT FROM form_corpo_test WHERE compagnie = ?’, array(‘ggfgfgdfgfgdf’));

var_dump($result);[/php]

I have tried playing around with it, I get this particular error every single time. I checked on Google, but all the errors of the same nature are too localized.

[php]
Fatal error: Uncaught exception ‘PDOException’ with message ‘SQLSTATE[42000]: Syntax error or access violation: 1064 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 ‘FROM form_corpo_test WHERE compagnie = ?’ at line 1’ in /home/product/public_html///db.php:51 Stack trace: #0 /home/product/public_html//formulaires/db.php(51): PDO->prepare(‘SELECT FROM for…’) #1 /home/product/public_html//formulaires/processForm-test.php(41): db->query(‘SELECT FROM for…’, Array) #2 {main} thrown in /home/product/public_html///db.php on line 51[/php]

Line 41 refers to
[php]$result = $db->query(‘SELECT FROM form_corpo_test WHERE compagnie = ?’, array(‘ggfgfgdfgfgdf’));[/php]

And db.php line 51 refers to
[php]$stmt = $this->pdoConn->prepare($query);[/php]

Alright, I also tried using this as well (I figured I would dig deeper in PDO):

[php] foreach ($db->query(‘SELECT * FROM form_corpo_test’) as $row) {
echo $row[‘compagnie’];
}[/php]

It gave me this error. Had no luck figuring out what it meant
[php]Fatal error: Cannot use object of type stdClass as array in /home/product/public_html/*****/formulaires/processForm-test.php on line 45
[/php]

I then proceeded to try this:
[php]
foreach ($db->query(‘SELECT * FROM form_corpo_test’) as $row) {
echo $row->compagnie;
}
[/php]
Which gave me this error (WTF?):
[php]
Company Name company nameggfgfgdfgfgdfaww, something bad happened, it should have been catched by the try/catch inside the DB class…[/php]

Ok, the company names appearing twice and the nonsensical ‘word’ ggfgfgdfgfgdf are in the db, under the colum ‘compagnie’

You aren’t supposed to fetch it in a loop. Can you please just try to do what I wrote? The last post I made will give you a variable ($result) with an array of all rows returned from the DB…

I did. It’s in the post right above. I posted twice. It wouldn’t let me edit the first one :confused:

Did you fix the query? The query I posted didn’t contain any columns to select so it would’ve had to be modified with

select column1, column2, etc from…
or
select * from

Sponsor our Newsletter | Privacy Policy | Terms of Service