Amit Singh
Amit Singh

Reputation: 2275

PHP PDOException: SQLSTATE[HY093]

My Query:

$query = 'INSERT INTO ptd_users (username,contact,email,longitude,latitude,state,city,address) values (?,?,?,?,?,?,?,?)';
$q = $conn->prepare($query);
$q->execute($_POST['user']);

Result of print_r($_POST[user]) :

Array ( [name] => marc [contact] => 123456789 [email] => [email protected] [longitude] => 12.3786085 [latitude] => 96.6126145 [state_select] => Arizona [city_select] => sussex [address] => address details ) 

I'm getting the following error while executing the query:

PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Upvotes: 1

Views: 197

Answers (1)

Rizier123
Rizier123

Reputation: 59681

You only bind 1 parameter to 8 placeholders, so that is not going to work. Now you have 3 ways to solve this:

1. Access the single array elements and bind them like this:

$q->execute($_POST['user']['name'], $_POST['user']['contact'], $_POST['user']['email'], $_POST['user']['longitude'], $_POST['user']['latitude'], $_POST['user']['state_select'], $_POST['user']['city_select'], $_POST['user']['address'] );

2. Use placeholders with names like this:

$query = "INSERT INTO ptd_users (username,contact,email,longitude,latitude,state,city,address) values (:name, :contact, :email, :longitude, :latitude, :state_select, :city_select, :address)";

And then you can use your associative array like this:

$q->execute($_POST['user']);

3. Use Positional placeholders like this:

$query = 'INSERT INTO ptd_users (username,contact,email,longitude,latitude,state,city,address) values (?,?,?,?,?,?,?,?)';

And then you can change your associative array to numeric array like this:

$q->execute(array_values($_POST['user']));

Upvotes: 2

Related Questions