Here below you can see my code.
I re-read my code many times and I can't see the error.
The error is
SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
My code below (the error occurs at the execution of the query inside the variable $sqlUpUser).
<?php
require '../shared/geolocation.php';
$user="db686186_adm";
$pass="#+-7en!Z";
try{
$coordinates = getCoordinates($adress);
if($coordinates["geolocationSuccessful"]){
$dbh = new PDO('mysql:host=nhl-mysqlw01;dbname=db686186', $user, $pass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlUpUser = "UPDATE users SET "
. "country=:country, "
. "adress=:adress, "
. "email=:email, "
. "phone=:phone, "
. "skype=:skype, "
. "lat=:lat, "
. "`long`=:long "
. "WHERE id=".$_SESSION['id'];
$stmt = $dbh->prepare($sqlUpUser);
$stmt->bindParam(':country', $country, PDO::PARAM_STR);
$stmt->bindParam(':adress', $adress, PDO::PARAM_STR);
$stmt->bindParam(':email', $email,PDO::PARAM_STR);
$stmt->bindParam(':phone', $phone,PDO::PARAM_STR);
$stmt->bindParam(':skype', $skype,PDO::PARAM_STR);
$stmt->bindParam(':lat', $coordinates["latitude"], PDO::PARAM_STR);
$stmt->bindParam(':long', $coordinates["longitude"], PDO::PARAM_STR);
$stmt->execute();
$stmt->closeCursor();
}else{
$_SESSION["emailExist"] = constant($coordinates["errorMessage"]);
header("Location:/profile/");
return;
}
}catch(Exception $e){
printf($e->getMessage());
}
$dbh = null;
Instead of creating a variable that you don't really need, $sqlUpUser and manually binding things let PHP and PDO take care things.
$stmt = $dbh->prepare('UPDATE users SET
country=:country,
adress=:adress,
email=:email,
phone=:phone,
skype=:skype,
lat=:lat,
`long`=:long
WHERE id=' . $_SESSION['id']
);
$stmt->execute([':country' => $country ,
':adress' => $adress ,
':email' => $email ,
':phone' => $phone ,
':skype' => $skype ,
':lat' => $coordinates["latitude"] ,
':long' => $coordinates["longitude"]
]
);
try
{
$stmt = $conn->prepare(" Update site_users SET users_first_name = :users_first_name, users_last_name = users_last_name
,users_email_verified = :users_email_verified , users_password = :users_password, users_dob_day = :users_dob_day, users_dob_month = :users_dob_month
,users_dob_year = :users_dob_year, users_password_1 = :users_password_1, users_registration_time= :users_registration_time
WHERE users_email = :users_email");
$stmt->bindParam(':users_first_name', $_POST["firstname"] , PDO::PARAM_STR);
$stmt->bindParam(':users_last_name', $_POST["lastname"] , PDO::PARAM_STR);
$stmt->bindParam(':users_email', $_POST["email"] , PDO::PARAM_STR);
$stmt->bindParam(':users_password', $hashed_password , PDO::PARAM_STR);
$stmt->bindParam(':users_password_1', $_POST["password"] , PDO::PARAM_STR);
$stmt->bindParam(':users_email_verified', $users_email_verified , PDO::PARAM_STR);
$stmt->bindParam(':users_dob_day', $_POST["day"], PDO::PARAM_STR);
$stmt->bindParam(':users_dob_month', $_POST["month"], PDO::PARAM_STR);
$stmt->bindParam(':users_dob_year', $_POST["year"], PDO::PARAM_STR);
$stmt->bindParam(':users_registration_time',$date, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
This is the error, the code echo
Error: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
Where is the problem in this code?
i think you are missing the : in your users_last_name = users_last_name query
probably it has to be users_last_name = :users_last_name
I'm trying to insert into a table, I have managed this using the same syntax for another query but this fails, the only difference is that this contains date information. Can anyone spot the problem?
The date is in this format: 2016-07-07.
try {
$sql2 = "INSERT INTO excavation.contexts_spatial
(area_easting,
area_northing,
context_number,
open_date,
close_date,
excavation_method,
contamination,
zooarchaeology_comments,
ceramic_comments) VALUES (
:area_easting,
:area_northing,
:context_number,
:open_date,
:close_date,
:excavation_method,
:contamination,
:zooarchaeology_comments,
:ceramic_comments)";
$stmt2 = $conn->prepare($sql2);
// prepare sql and bind parameters
$stmt2->bindParam(':area_easting', $area_easting, PDO::PARAM_INT);
$stmt2->bindParam(':area_northing', $area_northing, PDO::PARAM_INT);
$stmt2->bindParam(':context_number', $nextContext, PDO::PARAM_INT);
$stmt2->bindParam(':open_date', $open_date, PDO::PARAM_STR);
$stmt2->bindParam(':close_date', $close_date, PDO::PARAM_STR);
$stmt2->bindParam(':excavation_method', $excavation_method, PDO::PARAM_STR);
$stmt2->bindParam(':contamination', $contamination, PDO::PARAM_STR);
$stmt2->bindParam(':zooarchaeology_comments', $excavation_method, PDO::PARAM_STR);
$stmt2->bindParam(':ceramic_comments', $excavation_method, PDO::PARAM_STR);
//$stmt2->execute();
// insert a row
$area_easting = $_SESSION['area_easting'];
$area_northing = $_SESSION['area_northing'];
$nextContext = $_SESSION['nextContext'];
$open_date = $_SESSION['dateOpen'];
$close_date = $_SESSION['dateClose'];
$excavation_method = $_SESSION['excavationMethod'];
$contamination = $_SESSION['contamination'];
$zooarchaeology_comments = $_SESSION['zooarchaeologyComments'];
$ceramic_comments = $_SESSION['ceramicComments'];
$stmt2->execute();
echo "New records created successfully in contexts spatial<br />";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
You are executing your statement before setting the variables. Remove $stmt2->execute();
from below
$stmt2->bindParam(':ceramic_comments', $excavation_method, PDO::PARAM_STR);
$stmt2->execute(); // REMOVE THIS LINE
// insert a row
$area_easting = $_SESSION['area_easting'];
EDITED CODEI have a mysqli line of code: $stmt->bind_param("ss", $_POST['skills'], $_POST['city']); in a working query.
I've found the need to change to PDO and have used:$stmt->bindValue(':skill', $skills, PDO::PARAM_STR);
$stmt->bindValue(':city', $city, PDO::PARAM_STR);
I get no results except the echoed "No result found. Did you enter a city?" nor error messages although there is a connection to the db as evidenced in the search form in which the select list of 'city' is loaded. The full query:
try {
global $pdo;
if(isset($_POST['search'])) {
$skills = htmlspecialchars($_POST['skills']);
$city = htmlspecialchars($_POST['city']);
$stmt = $pdo->prepare('SELECT skill.skill_name, team.city FROM skill JOIN team ON skill.skill_id=team.skill WHERE skill.skill_name LIKE :skills AND team.city LIKE :city');
$skills = "%".$skills."%";
$city = "%".$city."%";
$stmt->bindParam(':skills', $skills, PDO::PARAM_STR);
$stmt->bindParam(':city', $city, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() > 0){
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
echo $row['skill'] . " is available in " . $row['city'];
}
}
else {
echo "No result found. Did you enter a city?";
}
}
}//try
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
Thanks.
If you really need to use LIKE then you need a wildcard somewhere in the string. As a placeholder has to represent a complete data literal, and if you want to use LIKE you have to create the parameter with the wildcards included like this.
try {
global $pdo;
if(isset($_POST['search'])) {
$skills = '%' . htmlspecialchars($_POST['skills']) . '%';
$city = '%' . htmlspecialchars($_POST['city']) . '%';
$stmt = $pdo->prepare('SELECT skill.skill_name, team.city
FROM skill
JOIN team ON skill.skill_id=team.skill
WHERE skill.skill_name LIKE :skill
AND team.city LIKE :city');
$stmt->bindValue(':skill', $skills, PDO::PARAM_STR);
$stmt->bindValue(':city', $city, PDO::PARAM_STR);
$stmt->execute();
if ($stmt->rowCount() > 0){
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo $row['skill_name'] . " is available in " . $row['city'];
}
}else{
echo "No result found. Did you enter a city?";
}
}
}
catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
A minor edit by ML: Corrected $row['skill'] to $row['skill_name']
I'm newbie with pdo. Here i'm trying to insert the datas into database using this below coding. But, i cannot able to insert the datas into database. I'm getting this following error
Fatal error: Call to a member function prepare() on a non-object
I searched on SO and internet about this error. Some people says add global $conn; at the top of your code. I added these code but i'm getting same error. Anyone tell me what should i do if i want to clear this error?
Config.php
<?php
$user = "root";
$password = "password";
try
{
$conn = new PDO('mysql:host=localhost;dbname=evouchers', $user, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
'DATABASE CONNECTION ERROR' .$e->getMessage();
}
?>
**Database.php**
<?php
session_start();
include('config.php');
if(isset($_POST['submit_val']))
{
$cmeal = $_POST['meal'];
try
{
$stmt = $conn->prepare("INSERT INTO ebmealplans ( MealPlanName, CreatedOn ) VALUES ( :cmeal, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':cmeal', $cmeal, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database ' .$e->getMessage();
}
$croom = $_POST['room'];
$ref_key = $conn->lastInsertId();
try
{
$stmt = $conn->prepare("INSERT INTO ebroomtypes ( RoomTypeName, CreatedOn ) VALUES ( :croom, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':croom', $croom, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database ' .$e->getMessage();
}
<*************** UPDATED CODES ***************>
$creference = $_POST['reference'];
$crefdate = $_POST['refdate'];
$ccin = $_POST['cin'];
$cout = $_POST['out'];
$cgname = $_POST['gname'];
$ctotaladults = $_POST['totaladults'];
$cchildrens = $_POST['childrens'];
$cinfants = $_POST['infants'];
$cgphone = $_POST['gphone'];
$cgemail = $_POST['gemail'];
$cgfax = $_POST['gfax'];
$cgaddress1 = $_POST['gaddress1'];
$cgaddress2 = $_POST['gaddress2'];
$cregion = $_POST['region'];
$ccity = $_POST['city'];
$cstate = $_POST['city_state'];
$ccountry = $_POST['country'];
$ccurrency = $_POST['currency'];
$ccurrencyto = $_POST['tocurrency'];
$camount = $_POST['camount'];
$ccurrencyvalue = $_POST['currencyvalue'];
$voucher_fk = $conn->lastInsertId();
try
{
$stmt = $conn->prepare("INSERT INTO ebvouchers ( VoucherReference, BookingDate, CheckIndate, CheckOutDate, MealPlanID_Fk, RoomTypeID_Fk, GuestName, TotalAdults, Childrens, Infants, GuestPhone, GuestEmail, GuestFax, GuestAddressLine1, GuestAddressLine2, GuestRegion, GuestCity, GuestState, GuestCountry, GuestCurrency, GuestCurrencyTo, CurrencyAmount, GuestCurrencyValue, VoucherCreatedOn ) VALUES ( :reference, :refdate, :ccin, :cout, :r_key, :r_key, :gname, :totaladults, :childrens, :infants, :gphone, :gemail, :gfax, :gaddress1, :gaddress2, :gregion, :city, :state, :country, :currency, :currencyto, :amount, :currencyvalue, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':reference', $creference, PDO::PARAM_STR);
$stmt->bindParam(':refdate', $crefdate, PDO::PARAM_STR);
$stmt->bindParam(':ccin', $ccin, PDO::PARAM_STR);
$stmt->bindParam(':cout', $cout, PDO::PARAM_STR);
$stmt->bindParam(':r_key', $ref_key, PDO::PARAM_STR);
$stmt->bindParam(':r_key', $ref_key, PDO::PARAM_STR);
$stmt->bindParam(':gname', $cgname, PDO::PARAM_STR);
$stmt->bindParam(':totaladults', $ctotaladults, PDO::PARAM_STR);
$stmt->bindParam(':childrens', $cchildrens, PDO::PARAM_STR);
$stmt->bindParam(':infants', $cinfants, PDO::PARAM_STR);
$stmt->bindParam(':gphone', $cgphone, PDO::PARAM_STR);
$stmt->bindParam(':gemail', $cgemail, PDO::PARAM_STR);
$stmt->bindParam(':gfax', $cgfax, PDO::PARAM_STR);
$stmt->bindParam(':gaddress1', $cgaddress1, PDO::PARAM_STR);
$stmt->bindParam(':gaddress2', $cgaddress2, PDO::PARAM_STR);
$stmt->bindParam(':gregion', $cregion, PDO::PARAM_STR);
$stmt->bindParam(':city', $ccity, PDO::PARAM_STR);
$stmt->bindParam(':state', $cstate, PDO::PARAM_STR);
$stmt->bindParam(':country', $ccountry, PDO::PARAM_STR);
$stmt->bindParam(':currency', $ccurrency, PDO::PARAM_STR);
$stmt->bindParam(':currencyto', $ccurrencyto, PDO::PARAM_STR);
$stmt->bindParam(':amount', $camount, PDO::PARAM_STR);
$stmt->bindParam(':currencyvalue', $ccurrencyvalue, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database ' .$e->getMessage();
}
<*************** UPDATED CODES ***************>
foreach ( $_POST['slno'] as $key=>$slno )
{
$date = $_POST['date'][$key];
$particulars = $_POST['particulars'][$key];
$noofnights = $_POST['noofnights'][$key];
$rate = $_POST['rate'][$key];
$price = $_POST['price'][$key];
$tax = $_POST['tax'][$key];
$nettotal = $_POST['nettotal'];
$totalamount = $_POST['totalamount'];
$finaltotal = $_POST['finaltotal'];
$c_date = $date;
$c_slno = $slno;
$c_particulars = $particulars;
$c_noofnights = $noofnights;
$c_rate = $rate;
$c_price = $price;
$c_tax = $tax;
$c_nettotal = $nettotal;
$c_totalamount = $totalamount;
$c_finaltotal = $finaltotal;
try
{
$stmt = $conn->prepare("INSERT INTO ebvouchertariffs ( TariffSlNo, TariffDate, TariffParticulars, NoOfNights, TariffRate, TariffPrice, TariffTax, TariffNetTotal, TariffAddTotal, TariffFinalTotal, VoucherID_Fk, CreatedOn ) VALUES ( :c_slno, :c_date, :c_particulars, :c_noofnights, :c_rate, :c_price, :c_tax, :c_nettotal, :c_totalamount, :c_finaltotal, :voucher_fk, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':c_slno', $c_slno, PDO::PARAM_STR);
$stmt->bindParam(':c_date', $c_date, PDO::PARAM_STR);
$stmt->bindParam(':c_particulars', $c_particulars, PDO::PARAM_STR);
$stmt->bindParam(':c_noofnights', $c_noofnights, PDO::PARAM_STR);
$stmt->bindParam(':c_rate', $c_rate, PDO::PARAM_STR);
$stmt->bindParam(':c_price', $c_price, PDO::PARAM_STR);
$stmt->bindParam(':c_tax', $c_tax, PDO::PARAM_STR);
$stmt->bindParam(':c_nettotal', $c_nettotal, PDO::PARAM_STR);
$stmt->bindParam(':c_totalamount', $c_totalamount, PDO::PARAM_STR);
$stmt->bindParam(':c_finaltotal', $c_finaltotal, PDO::PARAM_STR);
$stmt->bindParam(':voucher_fk', $voucher_fk, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database ' .$e->getMessage();
}
$conn = null;
}
}
?>
You did not print your exception. If you have any exception you will not get it. and i think problem in your $conn= null;
$conn = null; this line makes your connection object invalid and after executing this line you have invalid pdo object.for this you have got this error in loop. it should execute all other query before this line is executed. just remove this line. and print your exception message like this:
Try this:
<?php
session_start();
include('config.php');
if(isset($_POST['submit_val']))
{
$cmeal = $_POST['meal'];
try
{
$stmt = $conn->prepare("INSERT INTO ebmealplans ( MealPlanName, CreatedOn ) VALUES ( :cmeal, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':cmeal', $cmeal, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
die('Query failed to insert into database ' .$e->getMessage());
}
$croom = $_POST['room'];
$ref_key = $conn->lastInsertId();
try
{
$stmt = $conn->prepare("INSERT INTO ebroomtypes ( RoomTypeName, CreatedOn ) VALUES ( :croom, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':croom', $croom, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
die( 'Query failed to insert into database ' .$e->getMessage());
}
foreach ( $_POST['slno'] as $key=>$slno )
{
$date = $_POST['date'][$key];
$particulars = $_POST['particulars'][$key];
$noofnights = $_POST['noofnights'][$key];
$rate = $_POST['rate'][$key];
$price = $_POST['price'][$key];
$tax = $_POST['tax'][$key];
$nettotal = $_POST['nettotal'];
$totalamount = $_POST['totalamount'];
$finaltotal = $_POST['finaltotal'];
$c_date = $date;
$c_slno = $slno;
$c_particulars = $particulars;
$c_noofnights = $noofnights;
$c_rate = $rate;
$c_price = $price;
$c_tax = $tax;
$c_nettotal = $nettotal;
$c_totalamount = $totalamount;
$c_finaltotal = $finaltotal;
try
{
$stmt = $conn->prepare("INSERT INTO ebvouchertariffs ( TariffSlNo, TariffDate, TariffParticulars, NoOfNights, TariffRate, TariffPrice, TariffTax, TariffNetTotal, TariffAddTotal, TariffFinalTotal, VoucherID_Fk, CreatedOn ) VALUES ( :c_slno, :c_date, :c_particulars, :c_noofnights, :c_rate, :c_price, :c_tax, :c_nettotal, :c_totalamount, :c_finaltotal, :voucher_fk, NOW() )");
$conn->errorInfo();
$stmt->bindParam(':c_slno', $c_slno, PDO::PARAM_STR);
$stmt->bindParam(':c_date', $c_date, PDO::PARAM_STR);
$stmt->bindParam(':c_particulars', $c_particulars, PDO::PARAM_STR);
$stmt->bindParam(':c_noofnights', $c_noofnights, PDO::PARAM_STR);
$stmt->bindParam(':c_rate', $c_rate, PDO::PARAM_STR);
$stmt->bindParam(':c_price', $c_price, PDO::PARAM_STR);
$stmt->bindParam(':c_tax', $c_tax, PDO::PARAM_STR);
$stmt->bindParam(':c_nettotal', $c_nettotal, PDO::PARAM_STR);
$stmt->bindParam(':c_totalamount', $c_totalamount, PDO::PARAM_STR);
$stmt->bindParam(':c_finaltotal', $c_finaltotal, PDO::PARAM_STR);
$stmt->bindParam(':voucher_fk', $voucher_fk, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
die('Query failed to insert into database ' .$e->getMessage());
}
//$conn = null;
}
}
?>