Display alert based on value and session - php

What I am trying to accomplish is if the user verified column is 0 it will echo out the message below if the users verified column is 1 it wont show the message.
so I have it working but if they close it I don't want it to show again for that session.
$db = dbconnect();
$stmt = $db->prepare("SELECT * FROM users WHERE ID = ?");
$stmt->bind_param('s', $_SESSION['ID']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['ID'];
$verified = $row['Verified'];
if ($verified == 0) {
echo '
<div class="alert alert-warning alert-dismissible fade show" role="alert">
Your account has not been verified.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>';
return true;
} else {
return false;
}
}

You should set a session variable to show the alert based off of the value retrieved from the database, like so :
PHP
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['verifymsg']) {
$_SESSION['VerifyMessage'] = false;
}
}
$db = dbconnect();
$stmt = $db->prepare("SELECT * FROM users WHERE ID = ?");
$stmt->bind_param('s', $_SESSION['ID']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['ID'];
if (!isset($_SESSION['VerifyMessage']) {
$_SESSION['VerifyMessage'] = ($row['Verified'] == 0) ? true : false;
}
if ($_SESSION['VerifyMessage']) {
echo '
<form method="POST" action="yourscript.php">
<input type="hidden" name="verifymsg" />
<div class="alert alert-warning alert-dismissible fade show" role="alert">
Your account has not been verified.
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
</form>';
return true;
} else {
return false;
}
}
Here, I used a ternary operation to set a session variable called 'VerifyMessage' if it isn't already set. I also added a <form> and hidden input with the name verifymsg to the html.
When this script sees verifymsg as a post variable, it will set the session variable to false. This can work anyway you want, for example with ajax, but it shows a concept.

Related

Data not saving in session variable

The data is not storing in session everything is working fine the login system all things but the Data like username user pass and user Id should be saved in session but it's not I know it because if it was saving when you login successfully it should show welcome {username}.
Proceed to forums the main page but it is not showing username it was showing before but I got to problems and when all problems fixed this error came out.
Code:
<style>
<?php include 'signin.css'; ?>
</style>
<script type="text/javascript" src="signup.js"></script>
<?php
//signin.php
include 'connect.php';
include 'header.php';
//first, check if the user is already signed in. If that is the case, there is no need to display this page
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can sign out if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form action="" method="post" >
<div class="all" >
<div class="container" >
<div class="first" >
<h2>SIGN IN</h2>
</div>
<div class="user" >
<input class="use" type="text" placeholder="Username" id="username" name="user_name" required>
</div>
<div class="userimg" >
<img src="user.png" style="height:2em;width:2em;" >
</div>
<div class="pass" >
<input type="password" placeholder="Password" id="password" name="user_pass" minlength="8" required >
<img src="lock.png" >
</div>
<div class="show">
<img src="visible.png" id="visible" class="visible" onclick="myFunction()">
<img src="invisible.png" id="invisible" class="invisible" onclick="mynot()" >
</div>
<div class="check" >
<input type="checkbox" required >
</div>
<div class="box" >
<p>I accept all <a href="#" >terms</a> and <a href="#" >privacy</a>.</p>
</div>
<div class="submit" >
<input type="submit" name="submit" onclick="submit()" value="Sign in">
</div>
<div class="close" >
<input type="button" value="Back" >
</div>
<div class="log" >
dont have an account? <a href="#" >Login</a>
</div>
<div class="organic" >
<img src="logo.png" class="organicpe" >
</div>
<div>
<h2 class="back" ><a href="#" >Go Back</a></h2>
</div>
</div>
</div>
</form>';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Verify if the data is correct and return the correct response
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['user_name']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['user_pass']))
{
$errors[] = 'The password field must not be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo 'Uh-oh.. a couple of fields are not filled in correctly..';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li>' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul>';
}
else
{
//the form has been posted without errors, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$sql = "SELECT
user_id,
user_name,
user_level
FROM
Users
WHERE
user_name = '" . mysql_real_escape_string($_POST['user_name']) . "'
AND
user_pass = '" . sha1($_POST['user_pass']) . "'";
$result = mysqli_query($conn,$sql);
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
while ($row = $result -> fetch_row())
session_start();
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
$_SESSION['user_level'] = $row['user_level'];
}
while ($row = mysqli_fetch_array($result)) {
//set the $_SESSION['signed_in'] variable to TRUE
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['user_name'] = $row['user_name'];
}
}
echo '<h3>Welcome, ' . $_SESSION['user_name'] . '. Proceed to the forum overview.</h1>';
}
}
}
}
}
include 'footer.php';
?>
You need to start every php file use session with
session_start();

I can't send data to database using ajax and php

For some reason I can't get data to send to my database using ajax and php.
I click the add to cart button, the success message doesn't show up at all, and no data is sent to the database. No errors show up at all. What is going on here?
<form action="includes/addcart.inc.php?id=<?= $row['id'] ?>" class="cart-form">
<input type="hidden" class="pid" value="<?= $row['id'] ?>">
<input type="hidden" class="pname" value="<?= $row['product_name'] ?>">
<input type="hidden" class="pprice" value="<?= $row['product_price'] ?>">
<input type="hidden" class="pimage" value="<?= $row['product_image'] ?>">
<input type="hidden" class="pcode" value="<?= $row['product_code'] ?>">
<input type="submit" class="atcbutton btn btn-info btn-block" name="Add To Cart" value="Add To Cart">
</form>
Here is the form I'm using.
$(document).ready(function() {
// Send product details in the server
$('.cart-form').submit(function(e) {
e.preventDefault();
var $form = $(this).closest(".cart-form");
var pid = $form.find(".pid").val();
var pname = $form.find(".pname").val();
var pprice = $form.find(".pprice").val();
var pimage = $form.find(".pimage").val();
var pcode = $form.find(".pcode").val();
var pqty = $form.find(".pqty").val();
$.ajax({
url: 'includes/addcart.inc.php',
method: 'POST',
data: {
pid: pid,
pname: pname,
pprice: pprice,
pqty: pqty,
pimage: pimage,
pcode: pcode
},
success: function(response) {
$("#message").html(response);
}
});
});
});
Here's the js and ajax.
<?php
require 'dbh.inc.php';
if (isset($_POST['pid'])) {
$pid = $_POST['pid'];
$pname = $_POST['pname'];
$pprice = $_POST['pprice'];
$pimage = $_POST['pimage'];
$pcode = $_POST['pcode'];
$pqty = $_POST['pqty'];
$total_price = $pprice * $pqty;
$sql = ('SELECT product_code FROM cart WHERE product_code=?');
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, 's', $pcode);
mysqli_stmt_execute($stmt);
$res = mysqli_stmt_get_result($stmt);
$r = mysqli_fetch_assoc($res);
$code = $r['product_code'] ?? '';
if (!$code) {
$query = ('INSERT INTO cart (product_name, product_price, product_image, qty, total_price, product_code) VALUES (?,?,?,?,?,?)');
mysqli_stmt_init($conn);
mysqli_stmt_bind_param($query, 'ssssss', $pname, $pprice, $pimage, $pqty, $total_price, $pcode);
mysqli_stmt_execute($query);
echo '<div class="alert alert-success alert-dismissible mt-2">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Item added to your cart!</strong>
</div>';
} else {
echo '<div class="alert alert-danger alert-dismissible mt-2">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>Item already added to your cart!</strong>
</div>';
}
}
header("location: ../shop");
exit();
and that's the php. (dbh.inc.php is just a simple database connection)
I have tried double checking for typos/errors and I can't seem to find anything wrong.

Password_verify is not verifying the hash in the database

I'm trying to log a user in but I get an error every time I try to verify the password. The username is verified just fine. My password is stored by password_hash in the database. For example, let's say I signup a username 'thisIsAUser' and the password is 'thisIsAUsersPassword'. The hash would be something like: $2y$10$VR5FKZVLP6/43adb1PsGD.bsmrzp15jdftotz6xubDQtypZ1rKEFW. The error would be the else statement of the if(password_verify). Notice that the else statement of the username not matching has a '.' at the end while the password not matching has a '!'.
Logging in script:
<?php
session_start();
$link = mysqli_connect("localhost", "root", "Yuvraj123", "KingOfQuiz");
if(mysqli_connect_error()) {
die("Couldn't connect to the database. try again later.");
}
$query = "SELECT * FROM `users`";
if($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
}
// define variables and set to empty values
$loginSignupButton = "";
$loginUsername = "";
$loginPassword = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$loginUsername = form_input($_POST["loginUsername"]);
$loginPassword = form_input($_POST["loginPassword"]);
$loginSignupButton = form_input($_POST["loginSignupButton"]);
}
function form_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$loginUsernameError = "";
$loginPasswordError = "";
$error = "";
$loggingInUsername = "";
$unhashedPasswordThingyMajig = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["loginUsername"])) {
$loginUsernameError = "<p style='color: red'>Username is required</p>";
echo $loginUsernameError;
} else {
$loginUsername = form_input($_POST["loginUsername"]);
}
if (empty($_POST["loginPassword"])) {
$loginPasswordError = "<p style='color: red'>Password is required</p>";
echo $loginPasswordError;
} else {
$loginPassword = form_input($_POST["loginPassword"]);
}
if($_POST['loginActive'] == "0") {
$query = "SELECT * FROM users WHERE username = '". mysqli_real_escape_string($link, $_POST['loginUsername'])."' LIMIT 1";
$result = mysqli_query($link, $query);
if(mysqli_num_rows($result) > 0) {
$error = "<p style='color: red'>That username is already taken.</p>";
echo $error;
} else {
header ('location: signup.php');
}
} elseif($_POST['loginActive'] == "1") {
$sql = "
SELECT *
FROM users
WHERE username = ?
";
$query = mysqli_prepare($link, $sql);
mysqli_stmt_bind_param($query, "s", $_POST["loginUsername"]);
mysqli_stmt_execute($query);
$result = mysqli_stmt_get_result($query);
if (mysqli_num_rows($result)) {
$logInPassword = $_POST['loginPassword'];
if(password_verify($logInPassword, $row['password'])) {
echo "Hello World!";
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid!</p>";
echo $error;
}
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid.</p>";
echo $error;
}
}
}
?>
Form(This is the logging in one, not the signup):
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" id="LoginModalTitle">
<h5 class="modal-title" id="exampleModalLabel LoginModalTitle">Login</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true" style="color: white">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" id="modal-details">
<div class="form-group">
<input type="hidden" id="loginActive" name="loginActive" value="1">
<label for="loginUsername">Username</label>
<input type="text" class="form-control formInput" id="inputUsername" placeholder="Eg: RealKingOfQuiz" name="loginUsername" autocomplete="off" required>
<p><span class="error"><?php echo $loginUsernameError;?></span><p>
</div>
<div class="form-group">
<label for="loginPassword">Password</label>
<input type="password" class="form-control formInput" id="inputPassword" name="loginPassword" required autocomplete="on">
<small>Forgot Password?</small>
<p><span class="error"><?php echo $loginPasswordError;?></span></p>
</div>
<p><span class="error"><?php echo $error;?></span></p>
<div class="alert alert-danger" id="loginAlert"></div>
</form>
</div>
<div class="modal-footer">
<a id="toggleLogin">Sign Up?</a>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
<button class="btn btn-success" id="LoginSignUpButton" name="loginSignupButton" form="modal-details" disabled>Login</button>
</div>
</div>
</div>
</div>
If you update the section of code from...
$result = mysqli_stmt_get_result($query);
...to the end of the code block with the below; then it should work.
The problem is that you're reading the password from the wrong result set.
$result = mysqli_stmt_get_result($query);
$dbPassword = mysqli_fetch_assoc($result)["password"] ?? null;
if ($dbPassword) {
$logInPassword = $_POST['loginPassword'];
if(password_verify($logInPassword, $dbPassword)) {
echo "Hello World!";
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid!</p>";
echo $error;
}
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid.</p>";
echo $error;
}
You never fetched the row for the user logging in. When you check $row['password'] it's checking the first password in the table, which came from the SELECT * FROM users query at the beginning of the script.
You need to call mysqli_fetch_assoc() after querying for the row for the user.
if (mysqli_num_rows($result)) {
$logInPassword = $_POST['loginPassword'];
$row = mysqli_fetch_assoc($result);
if(password_verify($logInPassword, $row['password'])) {
echo "Hello World!";
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid!</p>";
echo $error;
}
} else {
$error = "<p style='color: red'> The Password and Username combination Is not Valid.</p>";
echo $error;
}

Password Reset in codeigniter

I have a user system with user registration and user login. on the login page there is a password reset button and on the password rest button the following codes are there but nothing happens when I try to send a password rest link.
CONTROLLER:
function resetPasswordUser()
{
$status = '';
$this->load->library('form_validation');
$this->form_validation->set_rules('login_email','Email','trim|required|valid_email|xss_clean');
if($this->form_validation->run() == FALSE)
{
$this->forgotPassword();
}
else
{
$email = $this->input->post('login_email');
if($this->user_model->checkEmailExist($email))
{
$encoded_email = urlencode($email);
$this->load->helper('string');
$data['email'] = $email;
$data['activation_id'] = random_string('alnum',15);
$data['createdDtm'] = date('Y-m-d H:i:s');
$data['agent'] = getBrowserAgent();
$data['client_ip'] = $this->input->ip_address();
$save = $this->user_model->resetPasswordUser($data);
if($save)
{
$data1['reset_link'] = base_url() . "resetPasswordConfirmUser/" . $data['activation_id'] . "/" . $encoded_email;
$userInfo = $this->user_model->getCustomerInfoByEmail($email);
if(!empty($userInfo)){
$data1["username"] = $userInfo[0]->username;
$data1["email"] = $userInfo[0]->email;
$data1["message"] = "Reset Your Password";
}
$sendStatus = resetPasswordEmail($data1);
if($sendStatus){
$status = "send";
setFlashData($status, "Reset password link sent successfully, please check mails.");
} else {
$status = "notsend";
setFlashData($status, "Email has failed, try again.");
}
}
else
{
$status = 'unable';
setFlashData($status, "It seems an error while sending your details, try again.");
}
}
else
{
$status = 'invalid';
setFlashData($status, "This email is not registered with us.");
}
redirect('users/forgotPassword');
}
}
// This function used to reset the password
function resetPasswordConfirmUser($activation_id, $email)
{
// Get email and activation code from URL values at index 3-4
$email = urldecode($email);
// Check activation id in database
$is_correct = $this->user_model->checkActivationDetails($email, $activation_id);
$data['email'] = $email;
$data['activation_code'] = $activation_id;
if ($is_correct == 1)
{
$this->load->view('templates/header');
$this->load->view('newPassword', $data);
$this->load->view('templates/footer');
}
else
{
redirect('users/login');
}
}
// This function used to create new password
function createPasswordUser()
{
$status = '';
$message = '';
$email = $this->input->post("email");
$activation_id = $this->input->post("activation_code");
$this->load->library('form_validation');
$this->form_validation->set_rules('password','Password','required|max_length[20]');
$this->form_validation->set_rules('cpassword','Confirm Password','trim|required|matches[password]|max_length[20]');
if($this->form_validation->run() == FALSE)
{
$this->resetPasswordConfirmUser($activation_id, urlencode($email));
}
else
{
$password = $this->input->post('password');
$cpassword = $this->input->post('cpassword');
// Check activation id in database
$is_correct = $this->user_model->checkActivationDetails($email, $activation_id);
if($is_correct == 1)
{
$this->user_model->createPasswordUser($email, $password);
$status = 'success';
$message = 'Password changed successfully';
}
else
{
$status = 'error';
$message = 'Password changed failed';
}
setFlashData($status, $message);
redirect("users/login");
}
}
MODEL:
function checkEmailExist($email)
{
$this->db->select('id');
$this->db->where('email', $email);
$this->db->where('isDeleted', 0);
$query = $this->db->get('users');
if ($query->num_rows() > 0){
return true;
} else {
return false;
}
}
/**
* This function used to insert reset password data
* #param {array} $data : This is reset password data
* #return {boolean} $result : TRUE/FALSE
*/
function resetPasswordUser($data)
{
$result = $this->db->insert('reset_password', $data);
if($result) {
return TRUE;
} else {
return FALSE;
}
}
/**
* This function is used to get customer information by email-id for forget password email
* #param string $email : Email id of customer
* #return object $result : Information of customer
*/
function getCustomerInfoByEmail($email)
{
$this->db->select('id, email, username');
$this->db->from('users');
$this->db->where('isDeleted', 0);
$this->db->where('email', $email);
$query = $this->db->get();
return $query->result();
}
/**
* This function used to check correct activation deatails for forget password.
* #param string $email : Email id of user
* #param string $activation_id : This is activation string
*/
function checkActivationDetails($email, $activation_id)
{
$this->db->select('id');
$this->db->from('reset_password');
$this->db->where('email', $email);
$this->db->where('activation_id', $activation_id);
$query = $this->db->get();
return $query->num_rows;
}
// This function used to create new password by reset link
function createPasswordUser($email, $password)
{
$this->db->where('email', $email);
$this->db->where('isDeleted', 0);
$this->db->update('users', array('password'=>getHashedPassword($password)));
$this->db->delete('reset_password', array('email'=>$email));
}
VIEW:
<div class="row">
<div class="col-md-12">
<?php echo validation_errors('<div class="alert alert-danger alert-dismissable">', ' <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button></div>'); ?>
</div>
</div>
<?php
$this->load->helper('form');
$error = $this->session->flashdata('error');
$send = $this->session->flashdata('send');
$notsend = $this->session->flashdata('notsend');
$unable = $this->session->flashdata('unable');
$invalid = $this->session->flashdata('invalid');
if($error)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $this->session->flashdata('error'); ?>
</div>
<?php }
if($send)
{
?>
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $send; ?>
</div>
<?php }
if($notsend)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $notsend; ?>
</div>
<?php }
if($unable)
{
?>
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $unable; ?>
</div>
<?php }
if($invalid)
{
?>
<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<?php echo $invalid; ?>
</div>
<?php } ?>
<form action="<?php echo base_url(); ?>users/resetPasswordUser" method="post">
<div class="form-group has-feedback">
<input type="email" class="form-control" placeholder="Email" name="login_email" required />
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
</div><!-- /.col -->
<div class="col-xs-4">
<input type="submit" class="btn btn-primary btn-block btn-flat" value="Submit" />
</div><!-- /.col -->
</div>
</form>
Login<br>
</div><!-- /.login-box-body -->
</div><!-- /.login-box -->
CONSTANT:
define('EMAIL_FROM', 'xxxx#gmail.com'); // e.g. email#example.com
define('EMAIL_BCC', 'xxxx#gmail.com'); // e.g. email#example.com
define('FROM_NAME', 'CTL '); // Your system name
define('EMAIL_PASS', 'Your email password'); // Your email password
define('PROTOCOL', 'smtp'); // mail, sendmail, smtp
define('SMTP_HOST', 'smtp.gmail.com'); // your smtp host e.g. smtp.gmail.com
define('SMTP_PORT', '25'); // your smtp port e.g. 25, 587
define('SMTP_USER', 'Your smtp user'); // your smtp user
define('SMTP_PASS', 'Your smtp password'); // your smtp password
define('MAIL_PATH', '/usr/sbin/sendmail');
QUESTION UPDATE
I changed my view to load out my errors and what I get is "Email has failed, try again." Error for mail not sent. Thanks
From your comments, it looks like you are using a localhost server. Localhost servers cannot send emails out IIRC. To test sending emails, you have to have a server that has access to the real world (and the feature has to be enabled on that server).

Attempting to add multiple records to MYSQL using form

I have a form which allows a user to add a new course title and gives them the option to add more record making it more convenient instead of submitting each one separately.
I've attempted to use syntax which I've seen in a number of examples online and it works in adding extra rows dynamically however this affects the form submission when it connects to the mysql database.
It will add the first record however not the second and I'm not sure if I'm executing it correctly using PDO.
if anyone could provide some insight as to how i can achieve this and why my code is failing i would be much appreciative.
the php file:
<?php
include "db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = $db_conx->prepare("INSERT INTO `insights`.`course_details` (`course_title`) VALUES (:course_title)");
$course_title = $_POST['course_title'];
//$course_code = $_POST['course_code'];
$sql->bindParam(':course_title', $course_title, PDO::PARAM_STR);
//$sql->bindParam(':course_code', $course_code, PDO::PARAM_STR);
/*** execute the prepared statement ***/
$courses = array();
if ($sql->execute()) {
$courses[] = $sql;
}
}
/*** success message ***/
$message = "<p class='text-success'> Record Successfully Added <span class='glyphicon glyphicon-ok'/></p>";
}
catch(Exception $e)
{
$message = 'Message: ' .$e->getMessage();
}
die($message);
?>
the AJAX which adds more rows when clicked and submits the form when 'submit' is clicked:
function addCall() {
var data = $('#addForm').serialize();
$.post('ManageCourses_AddSubmit.php', data, function(response){
$("#addForm").html(response);
//'soft'reload parent page, after a delay to show message
setTimeout(function(){
$('#addModal').modal('hide')
location.reload();
},3500);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
jQuery(function($){
var i = 1;
var $button = $('#add_row'),
$row = $('.addForm').clone();
$button.click(function(){
$row.clone().insertBefore( $button );
});
});
the form where the data is sent from:
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title">Add New Record: </h4>
</div>
<div class="modal-body">
<form id="addForm" class="addForm">
<div class="form-group">
<label for="course_code" class="pull-left" class="control-label">Course Code:</label>
<input type="text" class="form-control" id="course_code_id" name="code[]" readonly value ="NULL">
</div>
<div class="form-group">
<label for="course_name" class="pull-left" class="control-label">Course Title:</label>
<input type="text" class="form-control" placeholder="Enter Course Title" id="course_title_id" name="course_title">
</div>
</form>
</div>
<div class="modal-footer">
<div class="btn-toolbar">
<button type="button" class="btn btn-primary" id="add_row" name="add_row">Add New Record <span class="glyphicon glyphicon-plus"></button>
<button type="button" class="btn btn-danger" id="del_row" name="del_row">Delete Row <span class="glyphicon glyphicon-trash"></button>
<button type="button" class="btn btn-default" class="pull-right" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" class="pull-right" onclick="addCall();">Submit <span class="glyphicon glyphicon-saved"></button>
</div>
</div>
</div>
</div>
</div>
thank you! :)
Your problem is coming from targeting an element id in the following line:
var data = $('#addForm').serialize();
First off, you should always treat the id attribute as if it only exists in one location of the DOM. For more information, see:
http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute
To fix your problem, you need to pass the data from each element and handle the data differently on the backend. In your JavaScript, change the following line:
var data = $('#addForm').serialize();
to:
var data = {};
var index = 0;
// use the class of the form elements instead
$('.addForm').each(function(){
// take each form value an store it within the data variable
data['course_code'][index] = $(this).find('input[name=course_code]').val();
data['course_title'][index] = $(this).find('input[name=course_title]').val();
index++;
});
Now, you need to update your backend to accept the new array of values...
<?php
include "db_conx.php";
try
{
$db_conx = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password);
$db_conx->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$courses = array();
// check if we have valid post data
if(isset($_POST['course_code']) && isset($_POST['course_title']))
{
foreach($_POST['course_code'] as $index=>$course_code)
{
// check if we have a matching title (needed for the title insert)
$course_title = '';
if(isset($_POST['course_title'][$index]))
$course_title = $_POST['course_title'][$index];
else
continue; // no title found, skip to the next index
// at this point, use $course_title and $course_code in your query
$sql = $db_conx->prepare("INSERT INTO `insights`.`course_details` (`course_title`, `course_code`) VALUES (:course_title, :course_code)");
$sql->bindParam(':course_title', $course_title, PDO::PARAM_STR);
$sql->bindParam(':course_code', $course_code, PDO::PARAM_STR);
/*** execute the prepared statement ***/
if ($sql->execute()) {
$courses[] = $sql;
}
}
}
/*** success message ***/
$message = "<p class='text-success'> Records Successfully Added <span class='glyphicon glyphicon-ok'/></p>";
}
catch(Exception $e)
{
$message = 'Message: ' .$e->getMessage();
}
die($message);
?>

Categories