PDO multiple inserts only insert last value from multiple checkboxes - php

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.

Related

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

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.

BindParam for inserting multiple values

Let's say I have value for user,form,and ownerID. The value for user stays the same however ownerID might vary from time to time.
for example:
$user = "Farhana"; // fix value
$form = "Registration"; // fix value
$ownerID = array("23","50","33"); // item in array not fix, may have many ownerID
then I want to insert multiple values with single sql statement like this.
INSERT INTO messages (user,ownerID,form) VALUES ("Farhana","23","Registration"),("Farhana","50","Registration"),("Farhana","33","Registration");
so I have come out with foreach solution but I'm not sure this is correct or not.
// prepare
$stmt = $this->conn->prepare("INSERT INTO messages (user,ownerID,form) VALUES (?,?,?)");
// bind param
foreach ($ownerID as $ID){
$stmt->bind_param("sss",$user,$ID,$form);
$stmt->execute();
}
It's not really important, but just for sake of clarity bind_param have to be called only once.
$stmt = $this->conn->prepare("INSERT INTO messages (user,ownerID,form) VALUES (?,?,?)");
$stmt->bind_param("sss",$user,$ID,$form);
foreach ($ownerID as $ID){
$stmt->execute();
}

How to update MySQL table by calculated form value?

I'm trying to update MySQL table recored by any calculated form values in php, but it doesn't work. May you help me please thank you.
You should use mysqli with prepared statements, like so.
I hope this is enough for you, you gave me nothing to work with so...
<?php
//Get the form value and ID of the database record to update
$value = $_POST['value']; // Value submitted by a form element (replace this with whatever you want to change)
$id = $_POST['id']; //ID, could be of the user etc. (this will be a primary key inside the database) (does not have to be submitted via POST, I assume you know this already)
//Establish a new mysql connection
$mysqli = new mysqli($db_host,$db_user,$db_pass,$db_name);
//Set up a query
$query = "UPDATE table SET column_one=? WHERE id=?";
//Prepare the statement
$stmt = $mysqli->prepare($query);
//Bind the parameters
// 'si' = in the order of submitted valurs (column_one=? and id=?) (column_one is s and id is i, s is for string, i is for integer) (this defines what types of variables we are sending)
$stmt->bind_param('si', $value, $id);
//Execute the query
if($stmt->execute()){
//Get the amount of affected rows
$affected = $stmt->affected_rows(); //Should only be 1, but if your ID or whatever you're using to define which parts of the DB to update is not unique, then it can go higher ofc.
//Show success
echo "Database updated, $affected rows affected";
}else{
//Show error
echo "Error, say that this is shown, on stack overflow, as there's obviously something wrong.";
}
//Close the stmt/mysqli stuff
$stmt->close();
$mysqli->close();

update mysqli query with set values

I can update my columns dynamically, but I dont know how to update it with set values (stupid I know)
This is my sql code that updates the columns with set values:
if (isset($_POST['delete'])) {
$sql = 'UPDATE users SET user_deletion_date = NOW(), user_deleted_by = '.$_SESSION['id'].', deleted = Y
WHERE user_id = ?';
if ($stmt->prepare($sql)) {
// bind the query parameters
$stmt->bind_param('i', $_GET['user_id']);
// bind the result to variables
$stmt->bind_result($user_id, $user_deletion_date, $user_deleted_by, $deleted);
// execute the query, and fetch the result
$done = $stmt->execute();
$stmt->fetch();
}
}
if ($done) {
header('Location: update_users_confirm.php');
exit;
}
this doesn't update the table at all, I know that the issue is with my bind_param, could someone please help
Michael B's answer is mostly likely the solution. Change the $_GET to $_POST

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()

Categories