PHP Database records Insertion Notification

incMultiDBConnection.php:
<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1);
 
$username = 'root';
$password = 'xxxxxx';
$dsn      = 'mysql:host=localhost;dbname=inventas;charset=utf8mb4';

$options  = [
    PDO::ATTR_EMULATE_PREPARES   => false,
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
];

try {
    $db = new PDO($dsn, $username, $password, $options);
    
if ($db->query($insert)) {
     echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} 
else{
     echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
    
} catch(PDOException $e) {
    die( $e->getMessage() );
}

?>

Open in new window


<?php require_once('incMultiDBConnection.php'); ?>
<?php 


$insert = $db->prepare("INSERT INTO inventasequipment (equip_companyname, equip_name, equip_type, equip_sn, equip_productno, equip_website, equip_support, equip_use, equip_purchasedate, equip_warrenty, equip_performance, equip_comments, equip_cost, equip_datevisited, equip_timefrom, equip_timeto) VALUES (:company, :name, :type, :sn, :pn, :web, :support, :use, :purchase, :warrenty, :perf, :comments, :cost, :visitdate, :timefrom, :timeto)");

foreach ($_POST['equip'] as $equipment):
    $insert->execute([
        'company' => $equipment['companyname'],
        'name' => $equipment['equipname'],
        'type' => $equipment['equiptype'],
        'sn' => $equipment['equipsn'],
        'pn' => $equipment['equippn'],
        'web' => $equipment['equipweb'],
        'support' => $equipment['equipsupport'],
        'use' => $equipment['equipuse'],
        'purchase' => $equipment['equippurchase'],
        'warrenty' => $equipment['equipwarrenty'],
        'perf' => $equipment['equipperf'],
        'comments' => $equipment['equipcomments'],
        'cost' => $equipment['equipcost'],
        'visitdate' => $equipment['equipvisit'],
        'timefrom' => $equipment['equiptimefrom'],
        'timeto' => $equipment['equiptimeto'],
    ]);
endforeach;

 

//vardump:
// Loop through the array
//foreach( $_POST['person'] as $person ):
// var_dump($person);
  //echo $person['firstname'];
 // echo $person['lastname'];
//endforeach;

?>

Open in new window


The first code block is the include for the second code block. I am trying to te following working:
if ($db->query($insert)) {
     echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
     echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}

The page works and successfully inserts data into the database but the echo message for successful insertion does not work. I get the "Data not successfully Inserted" message
Any ideas, please
doctorbillTechAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Julian HansenCommented:
Several issues here.
1. Your insert code runs in a loop - do you want a response message for each iteration
2. Are the inserts related - i.e. if one fails must none of them go through? If so you should consider wrapping them in a transaction
3. Reporting output to the client should not really be done using the method you are trying. It is best to keep the server and client side code where possible. It might seem to make sense that you want to output a response at the time you do the insert but when you consider the fact that the entire PHP script must terminate before anything is actually sent to the browser and starts rendering - then it makes sense - they are two completely separate processes. One (server) passes off its output to the other (client) and only then does the client render the page at which point the alert's show.

The best way of doing this is calling the server side script with an AJAX call, handling the response and using client side code to report the result to the user.
doctorbillTechAuthor Commented:
I think all I need is to notify the user after all the code has run or just a redirect to another page
Julian HansenCommented:
Ajax is still the way to go

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Protecting & Securing Your Critical Data

Considering 93 percent of companies file for bankruptcy within 12 months of a disaster that blocked access to their data for 10 days or more, planning for the worst is just smart business. Learn how Acronis Backup integrates security at every stage

doctorbillTechAuthor Commented:
Awesome - will check it out
Chris StanyonWebDevCommented:
The queries in your first file won't work. If you look at it logically, you are including a file that tries to run the following code:

if ($db->query($insert)) {
     echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} 
else{
     echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}

Open in new window

At the point it's included, your $query variable doesn't exist, so it will fail!

That code just doesn't belong in the connection file at all. All that file should do is make the connection - nothing else.
doctorbillTechAuthor Commented:
Thanks all - the solution was AJAX and to put the code in the correct location
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Databases

From novice to tech pro — start learning today.