Redirect function after successful PDO insert - php

To put it briefly, I'm looking for a way to do a redirect after a successful PDO insert. Here is what I have so far.
Function for redirecting
<?php
function redirect_to($new_location) {
header("Location: " . $new_location);
exit;
}
?>
PDO INSERT
Please note, I've trimmed some code in my example below to make it easier to read.
try {
$sql = "INSERT INTO location_info (`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries` )
VALUES (:department, :participant, :activity, :location, :rec_injuries, :rec_injuries_timeframe, :non_rec_injuries, :non_rec_injuries_timeframe, '{$id}')";
$stmt = $db->prepare($sql);
for($i = 0, $l = count($_POST["department_name"]); $i < $l; $i++) {
$loc_info = array(':department' => $_POST["department_name"][$i],
':rec_injuries_timeframe' => $_POST["injury_time_frame"][$i],
':non_rec_injuries' => $_POST["non_rec_injuries"][$i],
':non_rec_injuries_timeframe' => $_POST["non_rec_injury_timeframe"][$i],
':competitor' => $_POST["competitor"][$i],
':cost_per_pair' => $_POST["cost_per_pair"][$i],
':usage_rate' => $_POST["usage_rate"][$i],
':leakage' => $_POST["leakage"][$i],
':cost_of_productivity' => $_POST["cost_of_productivity"][$i],
':non_rec_impact' => $_POST["non_rec_impact"][$i],
':non_rec_sprain' => $_POST["non_rec_sprain"][$i],
':non_rec_puncture' => $_POST["non_rec_puncture"][$i],
':non_rec_dermatitis' => $_POST["non_rec_dermatitis"][$i],
':non_rec_infection' => $_POST["non_rec_infection"][$i],
':non_rec_burns' => $_POST["non_rec_burns"][$i],
':non_rec_cuts' => $_POST["non_rec_cuts"][$i],
':rec_impact' => $_POST["impact"][$i],
':rec_sprain' => $_POST["sprain"][$i],
':rec_puncture' => $_POST["puncture"][$i],
':rec_dermatitis' => $_POST["dermatitis"][$i],
':rec_infection' => $_POST["infection"][$i],
':rec_burns' => $_POST["burns"][$i],
':rec_cuts' => $_POST["cuts"][$i],
':condition' => $_POST["condition"][$i] );
$stmt->execute($loc_info);
}
if ($stmt->execute()) {
redirect_to($_SERVER["DOCUMENT_ROOT"]."/testing/tim/results.php");
}
}
catch (Exception $e) {
$error = $e->getMessage();
print "<b>error:</b> " . $error;
}
You'll see that I have an if statement for the redirect with if ($stmt->execute()) {
redirect_to($_SERVER["DOCUMENT_ROOT"]."/testing/tim/results.php");
Where am I going wrong?

Where am I going wrong?
When you are adding A LOT of useless code.
Here goes the FULL code you need (save for the trimmed array):
$sql = "INSERT INTO location_info (`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries` )
VALUES (:department, :participant, :activity, :location, :rec_injuries, :rec_injuries_timeframe, :non_rec_injuries, :non_rec_injuries_timeframe, '{$id}')";
$stmt = $db->prepare($sql);
for($i = 0, $l = count($_POST["department_name"]); $i < $l; $i++) {
$loc_info = array(
':department' => $_POST["department_name"][$i],
':condition' => $_POST["condition"][$i]
);
$stmt->execute($loc_info);
}
redirect_to("/testing/tim/results.php");
This is all.
This code will redirect if all executes will be executed successfully.

You have a bit of a structure issue here...
If you're wanting to execute an indeterminate number of queries, then redirect after all queries have been executed successfully, then you need to track all the statement executions and errors.
If you want to throw an error the first time you have one, and stop inserting, then you just check the return result of the execute function and throw an error if it fails:
$sql = "INSERT INTO location_info (`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries` )
VALUES (:department, :participant, :activity, :location, :rec_injuries, :rec_injuries_timeframe, :non_rec_injuries, :non_rec_injuries_timeframe, '{$id}')";
$stmt = $db->prepare($sql);
$errors = array();
for($i = 0, $l = count($_POST["department_name"]); $i < $l; $i++) {
$loc_info = array(':department' => $_POST["department_name"][$i],
':rec_injuries_timeframe' => $_POST["injury_time_frame"][$i],
':non_rec_injuries' => $_POST["non_rec_injuries"][$i],
':non_rec_injuries_timeframe' => $_POST["non_rec_injury_timeframe"][$i],
':competitor' => $_POST["competitor"][$i],
':cost_per_pair' => $_POST["cost_per_pair"][$i],
':usage_rate' => $_POST["usage_rate"][$i],
':leakage' => $_POST["leakage"][$i],
':cost_of_productivity' => $_POST["cost_of_productivity"][$i],
':non_rec_impact' => $_POST["non_rec_impact"][$i],
':non_rec_sprain' => $_POST["non_rec_sprain"][$i],
':non_rec_puncture' => $_POST["non_rec_puncture"][$i],
':non_rec_dermatitis' => $_POST["non_rec_dermatitis"][$i],
':non_rec_infection' => $_POST["non_rec_infection"][$i],
':non_rec_burns' => $_POST["non_rec_burns"][$i],
':non_rec_cuts' => $_POST["non_rec_cuts"][$i],
':rec_impact' => $_POST["impact"][$i],
':rec_sprain' => $_POST["sprain"][$i],
':rec_puncture' => $_POST["puncture"][$i],
':rec_dermatitis' => $_POST["dermatitis"][$i],
':rec_infection' => $_POST["infection"][$i],
':rec_burns' => $_POST["burns"][$i],
':rec_cuts' => $_POST["cuts"][$i],
':condition' => $_POST["condition"][$i] );
if(!$stmt->execute($loc_info)){
$errors[] = $e->getMessage();
// un-comment if you want to stop on error:
// print "<b>error:</b> " . $e->getMessage();
// die();
};
}
if(count($errors)){
foreach($errors as $error){
print "<b>error:</b> " . $e->getMessage()."<br/>";
}
} else {
redirect_to($_SERVER["DOCUMENT_ROOT"]."/testing/tim/results.php");
}

Related

MYSQL query duplicating the rows

I'm having the problem that the query I'm passing through a function is duplicating me the rows. Before, instead of the statement->execute(array()), I had PARAM_STR working for each value. However, it started to give me problems. This is the code that is duplicating me the rows.
static public function mdlIngresarUsuario($datos){
$statement = Conexion::conectar()->prepare("INSERT INTO usuarios (id, nombre, usuario, password, rol, estado) VALUES (null, :nombre, :usuario, :password, :rol, :estado)");
$statement->execute(array(
':nombre' => $datos['nombre'],
':usuario' => $datos['usuario'],
':password' => $datos['password'],
':rol' => $datos['rol'],
':estado' => 0
));
if ($statement->execute()) {
return "ok";
} else {
return "error";
}
}
You're executing the statement twice:
$statement->execute(array(
':nombre' => $datos['nombre'],
':usuario' => $datos['usuario'],
':password' => $datos['password'],
':rol' => $datos['rol'],
':estado' => 0
));
and then in the condition of the if statement:
if ($statement->execute()) {
return "ok";
}
Just log the return of the first "execute", and use that as the condition:
$success = $statement->execute(array(
':nombre' => $datos['nombre'],
':usuario' => $datos['usuario'],
':password' => $datos['password'],
':rol' => $datos['rol'],
':estado' => 0
));
if( $success ) { return "ok"; }
This is happening because you call $statement->execute twice, once where you 'create' it and once in the if statement. You should assign the value of the first execute to a variable and use that variable in the if statement, like:
public static function mdlIngresarUsuario($datos)
{
$statement = Conexion::conectar()->prepare("INSERT INTO usuarios (id, nombre, usuario, password, rol, estado) VALUES (null, :nombre, :usuario, :password, :rol, :estado)");
$result = $statement->execute(array(
':nombre' => $datos['nombre'],
':usuario' => $datos['usuario'],
':password' => $datos['password'],
':rol' => $datos['rol'],
':estado' => 0
));
if ($result) {
return "ok";
} else {
return "error";
}
}

Insert XML Data into Mysql Table Using PHP with Ajax

I am using the below PHP file to upload XML to MySQL database, but the issue is my table name is Con-1 and cannot use it.
I have error in the below line:
array(
':name' => $data->Con-1[$i]->name,
':address' => $data->Con-1[$i]->address,
':gender' => $data->Con-1[$i]->gender,
':designation' => $data->Con-1[$i]->designation,
':age' => $data->Con-1[$i]->age
)
please help me to solve it
<?php
//import.php
sleep(3);
$output = '';
if(isset($_FILES['file']['name']) && $_FILES['file']['name'] != '')
{
$valid_extension = array('xml');
$file_data = explode('.', $_FILES['file']['name']);
$file_extension = end($file_data);
if(in_array($file_extension, $valid_extension))
{
$data = simplexml_load_file($_FILES['file']['tmp_name']);
$connect = new PDO('mysql:host=localhost;dbname=testing','root', '');
$query = "
INSERT INTO `Con-1`
(name, address, gender, designation, age)
VALUES(:name, :address, :gender, :designation, :age);
";
$statement = $connect->prepare($query);
for($i = 0; $i < count($data); $i++)
{
$statement->execute(
array(
':name' => $data->Con-1[$i]->name,
':address' => $data->Con-1[$i]->address,
':gender' => $data->Con-1[$i]->gender,
':designation' => $data->Con-1[$i]->designation,
':age' => $data->Con-1[$i]->age
)
);
}
$result = $statement->fetchAll();
if(isset($result))
{
$output = '<div class="alert alert-success">Import Data Done</div>';
}
}
else
{
$output = '<div class="alert alert-warning">Invalid File</div>';
}
}
else
{
$output = '<div class="alert alert-warning">Please Select XML File</div>';
}
echo $output;
?>
You should be able to do it using variable variables, so first assign Con-1 to a variable and then substitute this variable for the name in the assignment...
$var = 'Con-1';
$statement->execute(
array(
':name' => $data->$var[$i]->name,
':address' => $data->$var[$i]->address,
':gender' => $data->$var[$i]->gender,
':designation' => $data->$var[$i]->designation,
':age' => $data->$var[$i]->age
)
);

How to insert multiple arrays into a database?

I get some data from a form as arrays. Each $_POST value is an array itself:
//Example snippet from my code; I have some more data/arrays
$department_name = ($_POST[department_name]);
$participant_name = ($_POST[participant_name]);
$activity = ($_POST[activity]);
$location = ($_POST[location]);
Now I know that I could use a foreach loop to loop over each of these arrays and insert the values one by one into my database:
foreach($department_name as $department) {
$query = "INSERT INTO location_info (`department`) VALUES ('{$department}')";
$result = mysqli_query($connection, $query);
}
This seems like a lot of code for all my 35 POST variables as well as a lot of work for the server. More importantly how would I go about to "align" each piece of data? Because of the loop it would create a new row inside the database each iteration and leave blank fields for all other columns.
So I searched how I could loop through multiple arrays at once and found this solution:
<?php
$ZZ = array('a', 'b', 'c', 'd');
$KK = array('1', '2', '3', '4');
foreach($ZZ as $index => $value) {
echo $ZZ[$index] . $KK[$index];
echo "<br/>";
}
?>
But I don't really understand how this works and how I can apply this to my code?
Basically as an example I have multiple arrays like:
$department_name = array("A", "B", "C");
$participant_name = array(1, 2, 3);
And I need to insert them into my database like this:
INSERT INTO location_info (`department`, `participant`) VALUES ('A', 1);
INSERT INTO location_info (`department`, `participant`) VALUES ('B', 2);
INSERT INTO location_info (`department`, `participant`) VALUES ('C', 3);
So I think I have to use a foreach loop and loop over all arrays at once to insert the data row by row, but I fail to see how I can apply the code I found above to my code?
After some helpful comments I switched to PDO and made some progress.
My current code looks like the following.
Connection:
<?php
try {
$dsn = 'mysql:host=localhost;dbname=assessment';
$db = new PDO($dsn, 'xxx', 'xxx');
} catch (Exception $e) {
$error = $e->getMessage();
}
?>
Further down I have:
try {
$sql = "INSERT INTO location_info (`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries`, `non_rec_injuries_timeframe`, `competitor`, `cost_per_pair`, `usage_rate`, `leakage`, `cost_of_productivity`, `non_rec_impact`, `non_rec_sprain`, `non_rec_puncture`, `non_rec_dermatitis`, `non_rec_infection`, `non_rec_burns`, `non_rec_cuts`, `rec_impact`, `rec_sprain`, `rec_puncture`, `rec_dermatitis`, `rec_infection`, `rec_burns`, `rec_cuts`, `condition`, `general_id`)
VALUES (:department, :participant, :activity, :location, :rec_injuries, :rec_injuries_timeframe, :non_rec_injuries_timeframe, :competitor, :cost_per_pair, :usage_rate, :leakage, :cost_of_productivity,:non_rec_impact, :non_rec_sprain, :non_rec_puncture, :non_rec_dermatitis, :non_rec_infection, :non_rec_burns, :non_rec_cuts, :rec_impact, :rec_sprain, :rec_puncture, :rec_dermatitis, :rec_infection, :rec_burns, :rec_cuts, :condition, :general_id)";
$stmt = $db->prepare($sql);
for($i = 0, $l = count($_POST["department_name"]); $i < $l; $i++) {
$loc_info = array(':department' => $_POST["department_name"][$i],
':participant' => $_POST["participant_name"][$i],
':activity' => $_POST["activity"][$i],
':location' => $_POST["location"][$i],
':rec_injuries' => $_POST["injuries"][$i],
':rec_injuries_timeframe' => $_POST["injury_time_frame"][$i],
':non_rec_injuries' => $_POST["non_rec_injuries"][$i],
':non_rec_injuries_timeframe' => $_POST["non_rec_injury_timeframe"][$i],
':competitor' => $_POST["competitor"][$i],
':cost_per_pair' => $_POST["cost_per_pair"][$i],
':usage_rate' => $_POST["usage_rate"][$i],
':leakage' => $_POST["leakage"][$i],
':cost_of_productivity' => $_POST["cost_of_productivity"][$i],
':non_rec_impact' => $_POST["non_rec_impact"][$i],
':non_rec_sprain' => $_POST["non_rec_sprain"][$i],
':non_rec_puncture' => $_POST["non_rec_puncture"][$i],
':non_rec_dermatitis' => $_POST["non_rec_dermatitis"][$i],
':non_rec_infection' => $_POST["non_rec_infection"][$i],
':non_rec_burns' => $_POST["non_rec_burns"][$i],
':non_rec_cuts' => $_POST["non_rec_cuts"][$i],
':rec_impact' => $_POST["impact"][$i],
':rec_sprain' => $_POST["sprain"][$i],
':rec_puncture' => $_POST["puncture"][$i],
':rec_dermatitis' => $_POST["dermatitis"][$i],
':rec_infection' => $_POST["infection"][$i],
':rec_burns' => $_POST["burns"][$i],
':rec_cuts' => $_POST["cuts"][$i],
':condition' => $_POST["condition"][$i],
':general_id' => $_POST["id"][$i]
);
$stmt->execute($loc_info);
}
} catch (Exception $e) {
$error = $e->getMessage();
}
But this is still not working.
Thoughts? Can I not put an array inside an array?
Ok after a few trial and errors and some help from #Rizier123, here is the answer:
html on the form page
For clarity sake, I was trying to figure out how add several arrays of data to my db. So on dynamic form page, I have inputs similar to:
<p>Location: <input type='text' name='location[]' > </p>
Processing the Form and Inputting the Data to the DB
First, I switched from mysqli to PDO, then I ran with the following code:
try {
$sql = "INSERT INTO location_info (`department`, `participant`, `activity`, `location`, `rec_injuries`, `rec_injuries_timeframe`, `non_rec_injuries`, `non_rec_injuries_timeframe`, `competitor`, `cost_per_pair`, `usage_rate`, `leakage`, `cost_of_productivity`, `non_rec_impact`, `non_rec_sprain`, `non_rec_puncture`, `non_rec_dermatitis`, `non_rec_infection`, `non_rec_burns`, `non_rec_cuts`, `rec_impact`, `rec_sprain`, `rec_puncture`, `rec_dermatitis`, `rec_infection`, `rec_burns`, `rec_cuts`, `condition`, `general_id`)
VALUES (:department, :participant, :activity, :location, :rec_injuries, :rec_injuries_timeframe, :non_rec_injuries, :non_rec_injuries_timeframe, :competitor, :cost_per_pair, :usage_rate, :leakage, :cost_of_productivity,:non_rec_impact, :non_rec_sprain, :non_rec_puncture, :non_rec_dermatitis, :non_rec_infection, :non_rec_burns, :non_rec_cuts, :rec_impact, :rec_sprain, :rec_puncture, :rec_dermatitis, :rec_infection, :rec_burns, :rec_cuts, :condition, '{$id}')";
$stmt = $db->prepare($sql);
for($i = 0, $l = count($_POST["department_name"]); $i < $l; $i++) {
$loc_info = array(':department' => $_POST["department_name"][$i],
':participant' => $_POST["participant_name"][$i],
':activity' => $_POST["activity"][$i],
':location' => $_POST["location"][$i],
':rec_injuries' => $_POST["injuries"][$i],
':rec_injuries_timeframe' => $_POST["injury_time_frame"][$i],
':non_rec_injuries' => $_POST["non_rec_injuries"][$i],
':non_rec_injuries_timeframe' => $_POST["non_rec_injury_timeframe"][$i],
':competitor' => $_POST["competitor"][$i],
':cost_per_pair' => $_POST["cost_per_pair"][$i],
':usage_rate' => $_POST["usage_rate"][$i],
':leakage' => $_POST["leakage"][$i],
':cost_of_productivity' => $_POST["cost_of_productivity"][$i],
':non_rec_impact' => $_POST["non_rec_impact"][$i],
':non_rec_sprain' => $_POST["non_rec_sprain"][$i],
':non_rec_puncture' => $_POST["non_rec_puncture"][$i],
':non_rec_dermatitis' => $_POST["non_rec_dermatitis"][$i],
':non_rec_infection' => $_POST["non_rec_infection"][$i],
':non_rec_burns' => $_POST["non_rec_burns"][$i],
':non_rec_cuts' => $_POST["non_rec_cuts"][$i],
':rec_impact' => $_POST["impact"][$i],
':rec_sprain' => $_POST["sprain"][$i],
':rec_puncture' => $_POST["puncture"][$i],
':rec_dermatitis' => $_POST["dermatitis"][$i],
':rec_infection' => $_POST["infection"][$i],
':rec_burns' => $_POST["burns"][$i],
':rec_cuts' => $_POST["cuts"][$i],
':condition' => $_POST["condition"][$i] );
$stmt->execute($loc_info);
}

Can't access variable for unknown reason

I'm trying to execute two INSERT statements and I need the last inserted id to do so. I've tried $question_id = $dbh->lastInsertId();, but it doesn't work. Now I'm executing an additional SELECT LAST_INSERT_ID() statement, but that doesn't work either. I keep getting this error: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined, which occurs because $question_id is empty because selecting the last insert id doesn't seem to work.
Here's my code:
public function add_question($user_id, $group_id, $title, $caption, $datetime, $status) {
// Add user to database
try {
$dbh = new DBHandler();
$sql =
"INSERT INTO question(
user_id,
group_id,
title,
caption,
created_date_time,
question_status
)
VALUES(
:user_id,
:group_id,
:title,
:caption,
:created_date_time,
:question_status
)";
$stmt = $dbh->get_instance()->prepare($sql);
$stmt->execute(
array(
':user_id' => $user_id,
':group_id' => $group_id,
':title' => $title,
':caption' => $caption,
':created_date_time' => $datetime,
':status' => $status
)
);
//$question_id = $dbh->lastInsertId();
$sql= "SELECT LAST_INSERT_ID() AS question_id";
$stmt = $dbh->get_instance()->prepare($sql);
$stmt->execute();
// Resultset
$result = $stmt->fetchAll();
foreach($result AS $question_id_row) {
$question_id = $question_id_row['question_id'];
}
$sql =
"INSERT INTO notification(
n_question_id,
n_question_user_id,
n_question_group_id,
n_question_title
)
VALUES(
:n_question_id,
:n_question_user_id,
:n_question_group_id,
:n_question_title
)";
$stmt = $dbh->get_instance()->prepare($sql);
$stmt->execute(
array(
':n_question_id' => $question_id,
':n_question_user_id' => $user_id,
':n_question_group_id' => $group_id,
':n_question_title' => $title
)
);
echo 'Question added!';
}
catch(PDOException $e) {
echo $e->getMessage();
}
}
Your query fails with invalid number of parameter and parameter was not defined because you define this parameter
:question_status
but you bind
':status' => $status
change
$stmt->execute(
array(
':user_id' => $user_id,
':group_id' => $group_id,
':title' => $title,
':caption' => $caption,
':created_date_time' => $datetime,
':question_status' => $status //here
)
);
and it will work

How to combine single row with array of data in prepared statements

I have two table ad_post and ad_img . One ad_post row has many images in ad_img. I am trying to execute 2 queries together and than combine at the end. but
table:ad_images
colums (img_id, ad_id, img_name)
table : ad_post
colums(id, user_id, title, price, cat, condit, description, vid)
Relationship
ad_post (1)------>(many)ad_images
public function read_ads()
{
$this;
$this->sql = 'SELECT ad_post.id,ad_post.user_id,ad_post.title,ad_post.price,
sub_cat.s_cat_name,ad_post.condit,ad_post.description,ad_post.vid FROM ad_post,sub_cat
where sub_cat.id=ad_post.cat';
$sql1 = 'SELECT `img_id`,`img_name` FROM `ad_images` WHERE ad_id=?';
$stmt = $this->con->prepare ( $this->sql );
$stmt1 = $this->con->prepare ( $sql1 );
if ($stmt === false) {
trigger_error ( 'Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR );
}
// STMT
$stmt->execute ();
$stmt->store_result ();
$stmt->bind_result ( $id, $uId, $title, $price, $cat, $usage, $desc, $vid );
// STMT1
// $ad =AdPost::__getAll('','','','','','','','');
// $ad = Array();
$img = Array ();
$count = 0;
$count = 0;
$ads_img = Array ();
$a_img = Array ();
while ( $stmt->fetch () != NULL ) {
$stmt1->bind_param ( 'i', $id );
$stmt1->execute ();
$stmt1->store_result ();
$stmt1->bind_result ( $img_id, $img_name );
while ( $stmt1->fetch () != NULL ) {
echo $img_id;
$a_img = Array (
'img_id' => $img_id,
'img_name' => $img_name
);
try {
$ads_img [$count] = $a_img;
} catch ( Exception $exc ) {
echo $exc->getTraceAsString ();
}
}
$count ++;
$ad_set = Array (
'id' => $id,
'uid' => $uId,
'title' => $title,
'price' => $price,
'cat' => $cat,
'usage' => $usage,
'desc' => $desc,
'img_name' => $a_img
);
try {
$ads [$count] = $ad_set;
} catch ( Exception $exc ) {
echo $exc->getTraceAsString ();
}
$count ++;
}
$stmt->free_result ();
$stmt->close ();
return $ads;
}
I have got the ids of ads now i want to save imgs in array of $ad_set
The values of image array are returning null

Categories