Parameter error, SQLSTATE[HY093]: Invalid parameter number: parameter was not defined - php

So I'm getting SQLSTATE[HY093]: Invalid parameter number: parameter was not defined, when I try to submit my form. I have a reservations folder with a index.php file that has an include file as reservations.html.php which has the forms in html.
So my forms in the reservations.html.php when filled out and has a value in first name will then try to post all the values in the form into the reservations table I have created in mysql. Below are my code in the index.php
<?php
// Edit or Replace this try/catch statement to work with the current PHT configuration
include '../includes/db.inc.php';
// Modify the If statement so the try only runs if the First Name field has been submitted AND the honeypot field is empty ''
if (isset($_POST['myfname'])) {
$myFName = $_POST['myfname'];
$myTour = $_POST['tour'];
$myLName = $_POST['mylname'];
$myEmail = $_POST['myemail'];
// If the if statement is true, save each form field value as a variable. These variable values will be used in the thank you page.
// And run the try/catch to attempt to insert data in the database. Modify the INSERT statement to write all the form filed values (except the honeypot) to the database.
try
{
$sql = 'INSERT INTO reservations SET
tour = :tour,
fname = :fname,
lname = :lname,
email = :email';
$s = $pdo->prepare($sql);
$s->bindValue(':tour', $myTour);
$s->bindValue(':myfname', $myFName);
$s->bindValue(':mylname', $myLName);
$s->bindValue(':myemail', $myEmail);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error adding submitted joke: ' . $e->getMessage();
include '../includes/error.html.php';
exit();
}
// load the thank you page after the INSERT runs
include 'success.html.php';
// Add an else to load the initial page if the initial (line 19) if statement is false
} else {
include 'reservations.html.php'; //Modify this to include the initial file for this folder
}

The syntax for your insert statement is off, and appears to be hybrid between an insert and an update. Try this version:
$sql = "INSERT INTO reservations (tour, fname, lname, email) ";
$sql .= "VALUES (:tour, :fname, :lname, :email)";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':tour', $myTour, PDO::PARAM_STR);
$stmt->bindParam(':fname', $myFName, PDO::PARAM_STR);
$stmt->bindParam(':lname', $myLName, PDO::PARAM_STR);
$stmt->bindParam(':email', $myEmail, PDO::PARAM_STR);
$stmt->execute();
$stmt->close();
To be clear here, a SQL insert statement takes the following things:
The INSERT INTO keywords, followed by a list of columns
Then a VALUES clause, followed by a tuple containing the values to be inserted
There is also an INSERT INTO ... SELECT, which uses a select statement to provide the values, but you are not using this form.

Related

how to use 2 inserts in the same record PHP SQL

I am using the below code to grab a users ID from another table and creating a new record in this table. in the same row there is a field called action and I would like to insert either 'Log-In' or 'Log-Out' in this field for the same record.
my question is im not sure how to incorporate it with the code below without the database creating a new blank line
try{
// check for user ID in sessions table and apply to new session_log record
$sql = "INSERT INTO session_logs (USER_ID, first, last, email) SELECT USER_ID, first, last, email FROM sessions WHERE email=:email";
$stmt = $pdo->prepare($sql);
// Bind parameters to statement
$stmt->bindParam(':email', $_REQUEST['email']);
// Execute the prepared statement
$stmt->execute();
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
Unfortunately, Table and Column names CANNOT be replaced by parameters in PDO so you cant just bind the SELECT column as a value or similar, however, you can manipulate the string yourself to add in the required value like so:
$action = 'Log-In'; // if you get this value from user input in any way, be sure to sanitize it with something like `mysqli_real_escape_string`
$sql = "INSERT INTO session_logs (USER_ID, first, last, email, action) SELECT USER_ID, first, last, email, '$action' FROM sessions WHERE email=:email";

PHP insert not working when using the ' symbol

I'm trying to insert some text into my database using mysqli trough PHP.
My insert statement is as follows:
$userID="1";
$description="Hi! It's been a while..."; //For example...
$sql = "INSERT INTO projecten (user_ref, description)
VALUES ('$userID','$description')";
if ($conn->query($sql) === TRUE) {
//redirect to right page
} else {
//error message...
}
The problem:
I always get an error message saying that there is something not right in my sql syntax near " 'ts been " Now I tried removing the ' symbol and then the code works, but I need to be able to let my users type what they want to type...
Does somebody know what I can do about this?
Thanks in advance!
Use bind_param It will handle all those string and prevent you form sql injection
$userID = "1";
$description = "Hi! It's been a while..."; //For example...
$stmt = $conn->prepare("INSERT INTO projecten (`user_ref`, `description`) VALUES (?, ?)");
$stmt->bind_param('is', $userID, $description);
/* execute prepared statement */
$stmt->execute();
printf("%d Row inserted.\n", $stmt->affected_rows);
/* close statement and connection */
$stmt->close();

PDO multiple inserts only insert last value from multiple checkboxes

I am trying to insert data into my db using PDO. I have been successful until now but the following error has happened to me and I do not know the reason.
My goal is to insert data into three different tables at once ussing transactions. In the last two tables the records come from multiple checkboxes and store them as an array is not an option. I have been successful in storing the multiple values from the checkboxes when I only use first two queries but as soon as I add the third query in the transaction only the last value from the while is included into the database.
It's very strange because when I save the data into the user and language table using the while it works fine including all data but when I added the third query. The program stops working as I intended and the data base only receive the last record for both language and education table.
I get the following data from a html form and I send it to the class:
if($_POST){
// set values to object properties
$user->firstname=$_POST['firstname'];
$user->lastname=$_POST['lastname'];
$user->user_id=$_SESSION['user_id'];
// Data for the language table, second query in class function
while(list($key,$value) = each($_POST['language']))
{$user->language=$value;}
while(list($key,$value) = each($_POST['level']))
{$user->level=$value;}
// Data for the education table, third query in class function
while(list($key,$value) = each($_POST['studies']))
{$user->studies=$value;}
while(list($key,$value) = each($_POST['insti']))
{$lawyer->institution=$value;}
while(list($key,$value) = each($_POST['from']))
{$user->from_start=$value;}
while(list($key,$value) = each($_POST['to']))
{$user->to_end=$value;}
// create the user
if($user->registeruser()){
echo "<div class=\"alert alert-info\">";
echo "Registration completed, thank you. In the following 24 hours a member of our team will contact you. ";
echo "</div>";
}else{
echo "<div class=\"alert alert-danger\" role=\"alert\">Unable to register. Please try again.</div>";
}
}
The class function is written as follow:
function registeruser(){
try {
$this->conn->beginTransaction();
$query = "UPDATE
users
SET
firstname = :firstname,
lastname = :lastname,
WHERE
id = :id";
// prepare query statement
$stmt = $this->conn->prepare($query);
// bind variable values
$stmt->bindParam(':firstname', $this->firstname);
$stmt->bindParam(':lastname', $this->lastname);
$stmt->bindParam(':id', $this->user_id);
// execute the query
$stmt->execute();
$query = 'INSERT INTO language (user_id,language,level) VALUES (?,?,?)';
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->user_id);
$stmt->bindParam(2, $this->language);
$stmt->bindParam(3, $this->level);
$stmt->execute();
$query = 'INSERT INTO education (user_id,studies,school,from_start,to_end) VALUES (?,?,?,?,?)';
$stmt = $this->conn->prepare($query);
$stmt->bindParam(1, $this->user_id);
$stmt->bindParam(2, $this->studies);
$stmt->bindParam(3, $this->institution);
$stmt->bindParam(4, $this->from_start);
$stmt->bindParam(5, $this->to_end);
$stmt->execute();
$this->conn->commit();
return true;
} catch (Exception $e) {
$stmt->rollBack();
return false;
}
}
Thank you in advance.
PD: There is not error from db or php code. The problem is that the second and third query in the transaction are not inserting the multiple values from checkboxes into the DB, only the last. When I only include two queries into the transaction all values from the checkboxes are included the different table.

mySQLi Prepared Statement Select with Escape Characters

I am trying to select from a mySQL table using prepared statements. The select critera is user form input, so I am binding this variable and using prepared statements. Below is the code:
$sql_query = "SELECT first_name_id from first_names WHERE first_name = ?";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows == '1') {
$stmt->bind_result($_SESSION['first_name_id']);
$stmt->fetch();
} else {
$stmt->close();
$sql_query = "INSERT INTO first_names (first_name) VALUES (?)";
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('s', $_SESSION['first_name']);
$stmt->execute();
$_SESSION['first_name_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
Obviously my code is just determining whether or not the first_name already exists in the first_names table. If it does, it returns the corresponding ID (first_name_id). Otherwise, the code inserts the new first_name into the first_names table and gets the insert_id.
The problem is when a user enters a name with an escape character ('Henry's). Not really likely with first names but certainly employers. When this occurs, the code does not execute (no select or insert activity in the log files). So it seems like mySQL is ignoring the code due to an escape character in the variable.
How can I fix this issue? Is my code above efficient and correct for the task?
Issue #2. The code then continues with another insert or update, as shown in the code below:
if (empty($_SESSION['personal_id'])) {
$sql_query = "INSERT INTO personal_info (first_name_id, start_timestamp) VALUES (?, NOW())";
} else {
$sql_query = "UPDATE personal_info SET first_name_id = ? WHERE personal_info = '$_SESSION[personal_id]'";
}
$stmt = $_SESSION['mysqli']->prepare($sql_query);
$stmt->bind_param('i', $_SESSION['first_name_id']);
$stmt->execute();
if (empty($_SESSION['personal_id'])) {
$_SESSION['personal_id'] = $_SESSION['mysqli']->insert_id;
}
$stmt->close();
The issue with the code above is that I cannot get it to work at all. I am not sure if there is some conflict with the first part of the script, but I have tried everything to get it to work. There are no PHP errors and there are no inserts or updates showing in the mySQL log files from this code. It appears that the bind_param line in the code may be where the script is dying...
Any help would be very much appreciated.
you should validate/escape user input before sending it to the db.
checkout this mysql-real-escape-string()

mysqli INSERT anomaly

I have the following table:
ID: bigint autoinc
NAME: varchar(255)
DESCRIPTION: text
ENTRYDATE: date
I am trying to insert a row into the table. It executes without error but nothing gets inserted in database.
try {
$query = "INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES(?,?,?)";
$stmt = $conn->prepare($query);
$name= 'something';
$desc = 'something';
$curdate = "CURDATE()";
$stmt->bind_param("sss", $name, $desc, $curdate);
$stmt->execute();
$stmt->close();
$conn->close();
//redirect to success page
}
catch(Exception $e) {
print $e;
}
It runs fine and redirects to success page but nothing can be found inside the table. Why isn't it working?
What about replacing DESCTIPTION with DESCRIPTION inside the $query?
Edit
Just out of curiosity, I created a table called mytable and copy-pasted your code into a PHP script.
Here everything worked fine and rows got inserted, except that the binded parameter CURDATE() did not execute properly and the ENTRYDATE cell was assigned 0000-00-00.
Are you sure you are monitoring the same database and table your script is supposedly inserting to?
What happens when going with error_reporting(E_ALL); ?
Have you verified that the script actually completes the insertion?
The following appears to be working as expected:
error_reporting(E_ALL);
try {
$query = "INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES (?, ?, CURDATE())";
$stmt = $conn->prepare($query);
$name= 'something';
$desc = 'something';
$stmt->bind_param("ss", $name, $desc);
$stmt->execute();
if ($conn->affected_rows < 1) {
throw new Exception('Nothing was inserted!');
}
$stmt->close();
$conn->close();
//redirect to success page
}
catch(Exception $e) {
print $e->getMessage();
}
Are you sure there is no error? There seems to be a typo in your column name for example.
Note that PDO is extremely secretive about errors by default.
See How to squeeze error message out of PDO? on how to fix this.
Try preparing this query instead:
"INSERT INTO mytable (NAME, DESCRIPTION, ENTRYDATE) VALUES(?,?,CUR_DATE())"
And check the results of $stmt->execute(). It would have given you a warning that "CUR_DATE()" (sic) is not a valid DATE.
You can check if a statement was correctly executed by checking the return value of execute() and querying the errorInfo() method:
if (!$stmt->execute()) {
throw new Exception($stmt->errorInfo(), stmt->errorCode());
}
Be aware that upon failure, execute() does not throw an exception automagically. You'll have to check for successful operation and failure for yourself.
Is it possible that autocommit is OFF?
If so then you have to commit your insert like so
/* commit transaction */
$conn->commit();
Regards

Categories