Jump to content

Prepare statement produces the following error: Call to a member function prepare() on string in


rocky48

Recommended Posts

I'm new to PDO and am not yet familiar with the language. I am designing a form and am having problems with the prepare statement. The error is on this line: 

Quote

$stmt = $conn->prepare($sql); 

The $conn is my connection code and $sql is an INSERT query. The data for the query is obtained from a form within this file using $_POST. Here is the complete file:

<?php
session_start();
error_reporting (E_ALL);
ini_set('display_errors','1');
$errors = array();
$conn='';
require_once "conn/connect_seniorform.php";
// MORE PHP CODE IF ANY

if($_SERVER["REQUEST_METHOD"] == "POST")
{    // read the inputs
    if (isset ($_POST['fname'])){
        $fname = htmlentities($_POST['fname'],ENT_QUOTES);}
        if (isset ($_POST['sname'])){
    $sname = htmlentities($_POST['sname'],ENT_QUOTES);}
        if (isset ($_POST['email'])){
    $email = htmlentities($_POST['email'],ENT_QUOTES);}
        if (isset ($_POST['addr'])){
        $addr = htmlentities($_POST['addr'],ENT_QUOTES);}
        if (isset ($_POST['phone'])){
        $phone = htmlentities($_POST['phone'],ENT_QUOTES);}
        if (isset ($_POST['mob'])){
        $mob = htmlentities($_POST['mob'],ENT_QUOTES); }
        if (isset($_POST['bmfa_no'])){
        $bmfa_no = htmlentities($_POST['bmfa_no'],ENT_QUOTES);}
        if (isset($_POST['caa_no'])){
        $caa_no = htmlentities($_POST['caa_no'],ENT_QUOTES);}
        if (isset ($_POST['rewd'])){
        $rewd = htmlentities($_POST['rewd'],ENT_QUOTES);}
        if (isset ($_POST['fam'])){
        $fam = htmlentities($_POST['fam'],ENT_QUOTES);}
        if (isset($_POST['ctry'])){
        $ctry = htmlentities($_POST['ctry'],ENT_QUOTES);}
        if (isset($_POST['ctry_bmfa'])){
        $ctry_bmfa = htmlentities($_POST['ctry_bmfa'],ENT_QUOTES);}
        if (isset ($_POST['bdf'])){
        $bdf = htmlentities($_POST['bdf'],ENT_QUOTES);}
        if (isset($_POST['payopt'])){
        $payopt = htmlentities($_POST['payopt'],ENT_QUOTES);}
        if (isset ($_POST['payopt'])){
        $pay = htmlentities($_POST['pay'],ENT_QUOTES);}
        if (isset ($_POST['date'])){
        $date = htmlentities($_POST['date'],ENT_QUOTES);}
        if (isset ($_POST['sign'])){
        $sign = htmlentities($_POST['sign'],ENT_QUOTES);}
        
//  process the data now
    if (count($errors) == 0)
    {
        $sql = "INSERT INTO senior_dat(fname,sname,email,dob,addr,phone,mob,bmfa_no,caa_no,rewd,fam,ctry,ctry_bmfa,bdf,payopt,pay,date,sign)
                VALUES (:fname, :sname, :email,:dob, :addr, :phone, :mob, :bmfa_no, :caa_no, :rewd, :fam, :ctry, :ctry_bmfa, :bdf, :payopt, :pay, :date, :sign)";
        $stmt = $conn->prepare($sql);    //<<< error here
        $parms = array(
            'fname'=>$fname,
            'sname'=>$sname,
            'email'=>$email,
            'addr'=>$addr,
            'phone'=>$phone,
            'mob'=>$mob,
            'bmfa_no'=>$bmfa_no,
            'caa_no'=>$caa_no,
            'rewd'=>$rewd,
            'fam'=>$fam,
            'ctry'=>$ctry,
            'ctry_bmfa'=>$ctry_bmfa,
            'bdf'=>$bdf,
            'payopt'=>$payopt,
            'pay'=>$pay,
            'date'=>$date,
            'sign'>$sign
            );
        if (!$stmt->execute($parms))
            $errors[] = "Insert query did not run";
        else
            $errors[] =  "Your entries have been accepted";
    }
}
else    // no inputs yet
{
        $fname = '';
        $sname = '';
        $email = '';
        $addr = '';
        $phone = '';
        $mob = '';
        $bmfa_no = '';
        $caa_no = '';
        $rewd = '';
        $fam = '';
        $ctry = '';
        $ctry_bmfa = '';
        $bdf = '';
        $pay_opt = '';
        $pay = '';
        $date = '';
        $sign = '';
}

//   Done with the inputs - redisplay the form screen with the messages we produced.
//
//  implode the errrors array to show the result message or the errors
$errmsg = implode('<br>', $errors);

echo "
    <!DOCTYPE html>
    <html lang='en'>
    <head>
    <style type='text/css'>
    #form_box
    {
        position:relative;
        float:left;
        margin:3% 1%;
        padding:5px;
        border:2px solid black;
    }
    .red{color:red;}
    </style>
    </head>
    <body>
    ";
echo "
    <div id='form_box'>
    <center>
    <h1>SENIOR RENEWAL FORM</h1>
    </center>
    ";
 if(!empty($errmsg))
    echo "<p class='red'>$errmsg</p>";
echo "
    <form method='POST'>
    <label><b>First Name: </b>
    <br>
    <input type='text' name='fname' size='20' maxlength='40' value='$fname' required>
    </label>
    <br>
    <label><b>Surname: </b>
    <br>
    <input type='text' name='sname' size='20' maxlength='40' value='$sname' required>
    </label>
    <br>
    <label><b>Email: </b>
    <br>
    <input type='text' name='email' size='20' maxlength='40' value='$email' required>
    </label>
    <br><br>    
        <label><b>Address: </b>
        <br>
        <input type='textarea' name='addr' rows='4' cols='50 value='$addr' required>
        </label>
        <br>
        <label><b>Phone number:</br>
        <input type='tel' name='phone' 'min=12' max=16' value='$phone' required>
       </label>
        <br>
        <label> <b>Mobile number:</br>
        <input type='tel' name='mob' 'min=12' 'max=16' value'$mob' required>
       </label>
        <br>
<label BMFA No:
<input type='number' name='bmfa_no' value='$bmfa_no' required>
    </label>
    <br>
<label CAA Operator No:
<input type='text' name='caa_no' value='$caa_no' required><br>
</label>
<label Do you wish that the club obtains your BMFA membership, Insurance & CAA renewal:
  <select name='club_membership' id='club_membership'>
    <option value='Select Yes or No'> </option>
    <option value='NO'>NO</option>
    <option value='YES'>YES</option>
  </select>
  </label>
  <br>
  <label for='Ctry'>Are you a Country Member:</label>
  <select name='Ctry' id='Ctry'>
    <option value='blank'>  </option>
    <option value='NO'>NO</option>
    <option value='YES'>YES</option>
  </select>
<br>
   <label for='caa'>If you answered YES to the previous question,. have you a current BMFA and CAA membership:</label>
  <select name='caa' id='caa'>
    <option value='blank'>  </option>
    <option value='NO'>NO</option>
    <option value='YES'>YES</option>
    <option value='na'>N/A</option>
  </select>
  <br>
<label for='rewd'>Do you wish to purchase a BMFA Membership/Reward Card:</label>
  <select name='rewd' id='rewd'>
    <option value='blank'>  </option>
    <option value='NO'>NO</option>
    <option value='YES'>YES</option>
  </select>
 <br> 
  <label for='fam'>Are you a family member:</label>
  <select name='fam' id='fam'>
    <option value='blank'>  </option>
    <option value='NO'>NO</option>
    <option value='YES'>YES</option>
  </select>
  <br>
  <label for='bdf'>Do you wish to join the British Drone flyers Association, instead of the BMFA:</label>
  <select name='bdf' id='bdf'>
    <option value='blank'>  </option>
    <option value='NO'>NO</option>
    <option value='YES'>YES</option>
  </select>
  <p>Please note that if you join the BDF you can also fly fixed wing/ helicopters as well!</p>
  
  <br>
  <label for='pay_opt'>Ho do you wish to pay:</label>
  <select name='pay_opt' id='pay_opt'>
    <option value='blank'>  </option>
    <option value='chq'>CHEQUE</option>
    <option value='csh'>CASH</option>
    <option value='bacs'>BACS</option>    
  </select>
  <br>
    <p><b>Payment required: &#163;</b><input type='text' name='pay' size='20' maxlength='40'/></p>
    <br>
    <p style='background-color:tomato;'>I apply for membership of the 1066 Model Flying Club and agree to abide by the rules. 
By doing so agree to allow the club to use your details in respect of the GDPR regulations for the processing of your renewal, a copy of which can be found on the club website members page.
</p>
    <br>
  <label for='date'>Date:</label>
<input type='text' id='date' name='date'
       pattern='[0-9]{2}/[0-9]{2}/[0-9]{4}'
       required>
 <br>   
 <label for='sign'>Sign here:</label>
 <input type='text' id='sign' name='sign'
             required>
    <br>
    <input type='submit' value='Submit'>    
        
    </form>
    </div>
    ";

I hope someone can help me?

Link to comment
Share on other sites

No, I was getting tired of the same questions over and over too.  And - I didn't see his previous ending message until I read the beginning of what looks like another 5-pager.

Let's start our own question here.   If one is using prepared statements do you really have to use htmlentities on the incoming POST values before putting them to use in a query?  Seems to me like the prepare takes care of that but since I don't ever use it I don't know.

Link to comment
Share on other sites

Sorry Guys I have been unavailable the last few days, that's why I haven't answered!  I done live and die for the need to code every minute of the day like you two do!

I think I have seen the light!!  My connection code is not a new PDO, its msqli.

Changed that but still got an error: 

Quote

Fatal error: Uncaught Error: Call to a member function prepare() on string in /homepages/30/d593365489/htdocs/MFC1066/senior_data6.php:52 Stack trace: #0 {main} thrown in /homepages/30/d593365489/htdocs/MFC1066/senior_data6.php on line 52

I understand that this normally means that you have not created a new PDO, in the connection code, but I have, so what's causing the error now!

  $conn = new PDO($host_name, $username, $password, $database);

The code in the connection file had a mysqli error statement, so obviously it was the wrong statement for PDO so I tried this:

Quote

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

That is obviously wrong

Link to comment
Share on other sites

18 hours ago, rocky48 said:
$conn='';

the variable in question contains a string, because that's what you wrote a line of code to cause that variable to contain. that line of code was not in the most recent previous code. why are you making random changes for no reason? why are you even changing the name of the database connection variable, which should be named as to what type of database connection it contains, so that you can easily see or search which code is using a connection type that's different from what you were previously using in your code?

the example code I posted some time ago was error free, secure in both an sql and html context (the htmlentities() call was in the proper location, where a dynamic value was being output as a form field value), provided a good User eXperience (UX), was as SIMPLE and straightforward as possible, without a bunch of unnecessary typing, variables, and logic, and through the suggested php error related settings, validation logic, and error handling, would have either worked or told you when and why it didn't work. now you have a bunch of assembly line repetitive typing crap that took over a month to come up with and still doesn't work.

 

Link to comment
Share on other sites

Sorry Guys I have been unavailable the last few days, that's why I haven't answered!  I don't live and die for the need to code every minute of the day like you two do!

I thougt I had seen the light!!  My connection code is not a new PDO, its msqli.

Changed that but still got an error: 

Quote

Fatal error: Uncaught Error: Call to a member function prepare() on string in /homepages/30/d593365489/htdocs/MFC1066/senior_data6.php:52 Stack trace: #0 {main} thrown in /homepages/30/d593365489/htdocs/MFC1066/senior_data6.php on line 52

I understand that this normally means that you have not created a new PDO, in the connection code, but I have, so what's causing the error now!

This is the connection file I am now using

<?php
//set up a couple of functions for use by database
function get_db_conn_verse() {
	$host_name = "xxxxxxxxxxxx.hosting-data.io";
	$database = "dbsxxxxxxx";	// Change your database name
	$username = "dbuxxxxxxx";  	// Your database user id 
	$password = "xxxxxxxx";	// Your password
    
    //connect to server and select database; you may need it
    $conn = new PDO($host_name, $username, $password, $database);
printf("Connected");
    //if connection fails, stop script execution
   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
?>

I know you are all getting fed-up with my posts, but every time a suggestion is made I do try to implement the suggested changes. I am getting as fed up as you are and want to finish this project as it is taking far too long.  I know I am not the best at understanding OOP & PDO as most of my programming was done over 10 years ago and my age and my memory is not very good now.

If you would bear with me for a little longer I think I must be close to sorting this out!

Edited by rocky48
Link to comment
Share on other sites

10 minutes ago, rocky48 said:
$conn = new PDO($host_name, $username, $password, $database);

I pointed you at a thread containing a good PDO connection code example. In addition you had the RTFM option. Yet you still managed to come up with that rubbish - which is just a mysqli connection with the name changed.

  • Haha 1
Link to comment
Share on other sites

Ok - let's walk thru the code you just posted. 

It is a function so there should be something returned from that function.  You are not.

You make a call to have the connection established with the proper arguments.  That is good.

You then print out a result.  That is not good.   HOW do you know that the connection was successful?  You have not turned on error checking nor do you test the result of the call to PDO for success or failure.  You simply say you had success and THEN you turn on the errormode attributes.

I have to wonder how much programming you did 10 years ago.  You don't seem to have the mind of a programmer  since all of the things I have pointed out are perfectly normal ways of doing things for a programmer.

Where did you get this code?

You should be 

- setting the values (you did)

- setting the attributes

- make the call to create the connection USING AN IF 

- handle the if result by returning a value to the calling code.  Let it decide what to do.

I'm no expert but I do think your setting of $host is not right at all.  For one thing that is where the database is selected, not as a separate argument to the PDO call. So once again I ask - Where did you get this code?

 

 

Link to comment
Share on other sites

I can’t remember where I got it I think it was from my research on the internet. My memory is getting bad so I’m going to park this for a week or so as I have other commitments I need to concentrate on.

Thanks for the help, ‘I will be back’!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.