user2547925
user2547925

Reputation: 105

Running a prepared statement (MySQL/PHP)

this is my first time working with prepared statements and I'm running into a problem. When I run the following code, I get an error message that reads:

Warning: mysqli_stmt_bind_param() [function.mysqli-stmt-bind-param]: Number of elements in type definition string doesn't match number of bind variables in ... on line 49

Line 49 is the mysqli_stmt_bind_param statement below. It seems like the number of strings ("ssssss") matches up with correct number of strings in that statement, so I'm kind of at a loss.

<?php

$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$var3 = $_POST['var3'];
$var4 = $_POST['var4'];
$var5 = $_POST['var5'];
$var6 = $_POST['var6'];

      if (!empty($var1)&&!empty($var2)&&!empty($var3)
      &&isset($var4, $var5, $var6));

      require_once 'connect.inc.php';

      $query = "INSERT INTO tablename (var1, var2, var3, var4, var5, var6)
      VALUES ('$var1','$var2','$var3','$var4','$var5', '$var6')";

      $stmt = mysqli_prepare($link, $query);

      mysqli_stmt_bind_param($stmt, "ssssss", $var1, $var2, $var3, $var4, $var5, 
      $var6);

      mysqli_stmt_execute($stmt);

      if (mysqli_stmt_affected_rows($stmt)==1);

      mysqli_stmt_close($stmt);

      $result = mysqli_query($link, $query);

      if ($result) {
        echo 'Thank you for your submission.';
        }    
      else {
          echo 'We were unable to process your information.'.mysqli_error($link).'
          Please ensure all required fields were filled out.;
          }

      mysqli_close($link);
?>

Any help is much appreciated! Thank you! By the way, I DO get the 'Thank you for your submission.' message.

Upvotes: 1

Views: 150

Answers (2)

Joachim Isaksson
Joachim Isaksson

Reputation: 180917

The problem is not matching up with the format, it's that you have no parameters to bind. Parameters should use ? as a place holder in the query;

$query = "INSERT INTO tablename (var1, var2, var3, var4, var5, var6)
          VALUES ('$var1','$var2','$var3','$var4','$var5', '$var6')";

should be

$query = "INSERT INTO tablename (var1, var2, var3, var4, var5, var6)
      VALUES (?, ?, ?, ?, ?, ?)";   // <-- six place holders for the parameters

Upvotes: 2

user1646111
user1646111

Reputation:

Change your query to:

$query = "INSERT INTO tablename (var1, var2, var3, var4, var5, var6)
      VALUES (?,?,?,?,?, ?)";

To tell that you set parameters for binding.

Upvotes: 3

Related Questions