crud php fatal error Invalid parameter number - php

i have a little problem.
i have a contact-form and want to update my database with a crud.
My Contact-Form:
<!-- UPDATE -->
<div class="page-wrapper bg-gra-01 p-t-180 p-b-100 font-poppins">
<div class="container">
<?php
if(isset($_GET['edit'])):
$result = $crud->getMember($_GET['edit']);
?>
<hr />
<div class="row mt-5">
<h3> UPDATE </h3>
<form method="post" action="formprocess.php" class="col-12" enctype="multipart/form-data">
<div class="form-group">
<input type="text" class="form-control" name="vorname" value="<?= $result['vorname']; ?>">
</div>
<div class="form-group">
<label>Foto</label>
<input type="file" class="form-control" name="Foto">
</div>
<div class="form-group">
<input type="text" name="birthday" value="<?= $result['birthday']; ?>">
</div>
<div class="form-group">
<h5> Geschlecht </h5>
<select name="Geschlecht">
<option value=""> </option>
<option value=" Männlich" <?php if($result['Geschlecht'] == 'Männlich'){ ?> selected <?php } ?>> Männlich </option>
<option value=" Weiblich" <?php if($result['Geschlecht'] == 'Weiblich'){ ?> selected <?php } ?>> Weiblich </option>
<option value="Divers" <?php if($result['Geschlecht'] == 'Divers'){ ?> selected <?php } ?>> Divers </option>
</select>
</div>
<div class="input-group">
<input class="input--style-3" type="email" placeholder="Max-Mustermann#gmail.com" name="email" value="<?= $result['email'];?>">
</div>
<div class="input-group">
<input class="input--style-3" type="text" placeholder="01575 2234455" name="phone" value="<?= $result['phone'];?>">
</div>
<p> <input type="hidden" name="ID" value="<?= $result['ID']; ?>">
<p> <input type="submit" class="btn btn-outline-Success" name="update" Value="Update"> </p>
</form>
</div>
<?php
endif;
?>
My formprocess:
if(isset($_POST['update'])) {
if(isset($_POST['vorname']) && !empty($_POST['vorname']) &&
isset($_FILES['Foto']) && !empty($_FILES['Foto']) &&
isset($_POST['Geschlecht']) && !empty($_POST['Geschlecht']) &&
isset($_POST['birthday']) && !empty($_POST['birthday']) &&
isset($_POST['phone']) && !empty($_POST['phone']) &&
isset($_POST['email']) && !empty($_POST['email']) &&
isset ($_POST['ID']) && !empty($_POST['ID'])
){
$vorname = $_POST['vorname'];
$pfad = "upload/";
$filename = $_FILES['Foto'] ['tmp_name'];
$name = $pfad . time() . "-" . $_FILES['Foto'] ['name'];
$Geschlecht = $_POST['Geschlecht'];
$birthday = $_POST ['birthday'];
$phone = $_POST ['phone'];
$email = $_POST['email'];
$ID = $_POST ['ID'];
if(move_uploaded_file($filename,$name)){
if($crud->updateMember($ID, $vorname, $name, $Geschlecht, $birthday, $phone, $email)) {
$_SESSION['msg-class'] = "success";
$_SESSION['msg'] = "Update war erfolgreich!";
header('location: Admin.php');
} else{
$_SESSION['msg-class'] = "danger";
$_SESSION['msg'] = "Es ist ein Fehler aufgetreten!";
header('location: Admin.php');
}
}
}
}
My crud.php:
public function updateMember($ID, $vorname, $Foto, $Geschlecht, $birthday, $phone, $email) {
$stmt = $this->conn->prepare("UPDATE testing SET vorname = :vorname, Foto = :Foto, Geschlecht = :Geschlecht, birthday = :birthday, phone = :phone, email = :email WHERE ID=:ID");
$erg = $stmt->execute(array(
':vorname' => $vorname,
':Foto' => $Foto,
':Geschlecht' => $Geschlecht,
':birthday' => $birthday,
':phone' => $phone,
':email:' => $email,
':ID' => $ID
));
return $erg;
If i press the Update button i get that error:
Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\Xampp\htdocs\dashboard\pRAKTI\Testing 3\classes\crud.php:51 Stack trace: #0 C:\Xampp\htdocs\dashboard\pRAKTI\Testing 3\classes\crud.php(51): PDOStatement->execute(Array) #1 C:\Xampp\htdocs\dashboard\pRAKTI\Testing 3\formprocess.php(66): Crud->updateMember('12', 'Boris', 'upload/16693640...', ' Weiblich', '0000-00-01', '666', 'b#web.de') #2 {main} thrown in C:\Xampp\htdocs\dashboard\pRAKTI\Testing 3\classes\crud.php on line 51
i don't know why, can anyone help?

i got the solution...
my code was apparently "unsorted". For example, I had the birthday in the 3rd place, but entered it as a 4th in the code

I'm not a PHP specialist, but I think your values and DB columns count mismatch. From the exception, I see that you have an invalid parameter number. You can post the whole file so we can debug it together.

Related

HTML form not submitting to PHP

I have an html form set to submit to itself with $SERVER['PHP_SELF'] but the form does not seem to be able submit, instead it simply returns the same form when I click submit (with and input of type submit.
NOTE: the actual code is too long to post here, and I've included all that I think is necessary. The form in question is actually a duplicate of another (which works perfectly) but this one doesn't.
EDIT: I was advised to eventually post the code
SECOND EDIT: I actually removed the tag enctype='multipart/formdata' on the form tag, and the code script now works. But, I need that enctype to be able upload the images. Does anyone know how I can work around that?
<?php
include 'templates/inc/header.php';
include 'templates/inc/system_helpers.php';
include 'config/config.php';
?>
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');
ob_start();
$listing_saved = FALSE;
if (isset($_POST['submit'])) {
// property type
$property_type = isset($_POST['property_type']) ? $_POST['property_type'] : '';
// property details
$area_sq = isset($_POST['area_sq']) ? $_POST['area_sq'] : '';
$location = isset($_POST['ex_location']) ? $_POST['ex_location'] : '';
$bedrooms = isset($_POST['bedrooms']) ? $_POST['bedrooms'] : '';
$bathrooms = isset($_POST['bathrooms']) ? $_POST['bathrooms'] : '';
$furnished = isset($_POST['furnished']) ? $_POST['furnished'] : '';
// additional information
$description = isset($_POST['description']) ? $_POST['description'] : '';
$garden = isset($_POST['garden']) ? $_POST['garden'] : '';
$pool = isset($_POST['pool']) ? $_POST['pool'] : '';
$flatlet = isset($_POST['flatlet']) ? $_POST['flatlet'] : '';
$garage = isset($_POST['garage']) ? $_POST['garage'] : '';
$parking = isset($_POST['parking']) ? $_POST['parking'] : '';
$parking_spaces = isset($_POST['parking_sapces']) ? $_POST['parking_spaces'] : '';
// pricing
$price = isset($_POST['price']) ? $_POST['price'] : '';
// contact person
$first_name = isset($_POST['f_name']) ? $_POST['f_name'] : '';
$last_name = isset($_POST['l_name']) ? $_POST['l_name'] : '';
$email_address = isset($_POST['email_address']) ? $_POST['email_address'] : '';
$phone = isset($_POST['phone']) ? $_POST['phone'] : '';
$physical_address = isset($_POST['physical_address']) ? $_POST['physical_address'] : '';
$region = isset($_POST['region']) ? $_POST['region'] : '';
// legal consent
$consent = isset($_POST['consent']) ? $_POST['consent'] : '';
$isFNBBanked = isset($_POST['isFNBBanked']) ? $_POST['isFNBBanked'] : '';
$account_holder = isset($_POST['account_holder']) ? $_POST['account_holder'] : '';
$account_number = isset($_POST['account_number']) ? $_POST['account_number'] : '';
$commercialAcceptance = isset($_POST['commercialAcceptance']) ? $_POST['commercialAcceptance'] : '';
$isInfoCorrect = isset($_POST['isInfoCorrect']) ? $_POST['isInfoCorrect'] : '';
$optionToOptOut = isset($_POST['optionToOptOut']) ? $_POST['optionToOptOut'] : '';
$isAuthorized = isset($_POST['isAuthorized']) ? $_POST['isAuthorized'] : '';
// create an uploads directory
if (!is_dir(UPLOAD_DIR)) {
mkdir(UPLOAD_DIR, 0777, true);
}
/*
* List of file names to be filled in by the upload script
* below and to be saved in the db table "images" afterwards.
*/
$file_names_to_save = [];
$allowed_mime_types = explode(',', UPLOAD_ALLOWED_MIME_TYPES);
// capture the image uploads
if (!empty($_FILES)) {
if (isset($_FILES['images']['error'])) {
foreach ($_FILES['images']['error'] as $uploadedFileKey => $uploadedFileError) {
if ($uploadedFileError === UPLOAD_ERR_NO_FILE) {
$errors[] = 'You did not provide any files.';
} elseif ($uploadedFileError === UPLOAD_ERR_OK) {
$uploadedFileName = basename($_FILES['images']['name'][$uploadedFileKey]);
if ($_FILES['images']['size'][$uploadedFileKey] <= UPLOAD_MAX_FILE_SIZE) {
$uploadedFileType = $_FILES['images']['type'][$uploadedFileKey];
$uploadedFileTempName = $_FILES['images']['tmp_name'][$uploadedFileKey];
$uploadedFilePath = rtrim(UPLOAD_DIR, '/') . '/' . $uploadedFileName;
if (in_array($uploadedFileType, $allowed_mime_types)) {
if (!move_uploaded_file($uploadedFileTempName, $uploadedFilePath)) {
$errors[] = 'The file "' . $uploadedFileName . '" could not be uploaded.';
} else {
$file_names_to_save[] = $uploadedFilePath;
}
} else {
$errors[] = 'The extension of the file "' . $uploadedFileName . '" is not valid. Allowed extensions: JPG, JPEG, PNG, or GIF.';
}
} else {
$errors[] = 'The size of the file "' . $uploadedFileName . '" must be of max. ' . (UPLOAD_MAX_FILE_SIZE / 1024) . ' KB';
}
}
}
}
}
if (!isset($errors)) {
// add captured data into database
$query = 'INSERT INTO property (
propertytype_id,
land_area,
ex_location,
bedrooms,
bathrooms,
is_furnished,
short_desc,
has_garden,
has_pool,
has_flatlet,
has_parking,
parking_spaces,
price)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
//prepare the statement
$stmt = $connection->prepare($query);
//bind the parameters
$stmt->bind_param('iisiissssssii', $property_type, $area_sq, $location, $bedrooms, $bathrooms, $furnished, $description, $garden, $pool, $flatlet, $parking, $parking_spaces);
//execute the statement
$stmt->execute();
//grab the last car insert ID
$last_insert_id = $connection->insert_id;
// insert into persons table
$persons_sql = 'INSERT INTO person (
property_id,
firstname,
lastname,
email_address,
phone,
city,
region)
VALUES (?, ?, ?, ?, ?, ?, ?)';
$stmt = $connection->prepare($persons_sql);
$stmt->bind_param('isssiss', $last_insert_id, $first_name, $last_name, $email_address, $phone, $physical_address, $region);
$stmt->execute();
// grab the last person's id
$last_person_insert = $connection->insert_id;
// insert into legal table
$legal_sql = 'INSERT INTO legal (
person_id,
consent,
isFNBBanked,
account_holder,
account_number,
commercialAcceptance,
isInfoCorrect,
optionToOptOut,
isAuthorized
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)';
$stmt = $connection->prepare($legal_sql);
$stmt->bind_param('isssissss', $last_person_insert, $consent, $isFNBBanked, $account_holder, $account_number, $commercialAcceptance, $isInfoCorrect, $optionToOptOut, $isAuthorized);
$stmt->execute();
// close the statement
$stmt->close();
// save a record for each uploaded file
foreach ($file_names_to_save as $file_name) {
$query = 'INSERT INTO images (
property_id,
image_name)
VALUES (?, ?)';
$stmt = $connection->prepare($query);
$stmt->bind_param('is', $last_insert_id, $file_name);
$stmt->execute();
$stmt->close();
}
$listing_saved = TRUE;
}
}
?>
<!-- Page Contents -->
<div class="form-container">
<div class="sticky-anchor"></div>
<div class="banner">
<img src="./assets/MarketSquare banner for PROPERTY.jpg" alt="Market Square Form Banner">
</div>
<?php display_message(); ?>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="POST" enctype="multipart/form-data">
<!-- PROPERTY DETAILS -->
<div class="section-one">
<h3>Property Details</h3>
<div class="text-fields">
<div class="extra-fields">
<select name="property_type" id="property-type" class="select">
<option value="0">Property Type</option>
<?php
$query = mysqli_query($connection, "SELECT * FROM property_type");
if (mysqli_num_rows($query)) {
$i = 0;
while ($propertytype = mysqli_fetch_array($query)) {
?>
<option value="<?php echo $propertytype['propertytype_id']; ?>"><?php echo $propertytype['type_name']; ?></option>
<?php
$i++;
}
}
?>
</select>
</div>
</div>
<div class="text-fields">
<div class="extra-fields">
<input type="text" name="area_sq" placeholder="Area (in square metres)" required>
<input type="text" name="location" placeholder="Location (e.g. Veki's Village, Mountain Drive, Mbabane)">
</div>
</div>
<div class="text-fields selected">
<div class="extra-fields">
<input type="text" name="bedrooms" placeholder="No. of Bedrooms" required>
<input type="text" name="bathrooms" placeholder="No. of Bathrooms">
</div>
</div>
<label class="check-box">Furnished
<input type="checkbox" name="furnished" value="Yes">
<span class="checkmark"></span>
</label>
</div>
<!-- ADDITIONAL INFORMATION -->
<div class="section-two">
<h3>
Additional Information
<span> (Provide details about additional features)</span>
</h3>
<div class="extra-fields">
<textarea name="description" id="description" cols="30" rows="4" placeholder="Separate your items with a comma ( , )"></textarea>
</div>
External Features <span>(tick where appropriate)</span>
<div class="checks">
<label class="check-box">Garden
<input type="checkbox" name="garden" value="Available">
<span class="checkmark"></span>
</label>
<label class="check-box">Swimming Pool
<input type="checkbox" name="pool" value="Available">
<span class="checkmark"></span>
</label>
<label class="check-box">Bedsitter/flatlet
<input type="checkbox" name="flatlet" value="Available">
<span class="checkmark"></span>
</label>
<label class="check-box">Garage
<input type="checkbox" name="garage" value="Available">
<span class="checkmark"></span>
</label>
<label class="check-box">Open Parking
<input type="checkbox" name="parking" value="Available" id="parking-space" onclick="show_input()">
<span class="checkmark"></span>
</label>
<input type="text" name="parking_spaces" id="parking" placeholder="Number of parking spaces">
</div>
<div class="file-input">
Photos: <span>(max. 12, in all angles incl. interior)</span>
<input type="file" name="images[]" accept=".jpg, .jpeg, .png, .gif, .webp" id="imgUpload" multiple required>
</div>
</div>
<!-- PRICING -->
<div class="section-two pricing">
<h3>
Give it a Price
<span>(The sale price you wish to attach, based on the Valuation Report)</span>
</h3>
<div class="extra-fields">
<input type="text" name="price" placeholder="E " required>
</div>
</div>
<!-- CONTACT PERSON -->
<div class="section-three">
<h3>Contact Person</h3>
<div class="text-fields">
<div class="extra-fields">
<input type="text" name="f_name" placeholder="First name" required>
<input type="text" name="l_name" placeholder="Last name">
</div>
</div>
<div class="text-fields">
<div class="extra-fields">
<input type="email" name="email_address" placeholder="Email address">
<input type="text" name="phone" placeholder="Phone number" required>
</div>
</div>
<div class="text-fields">
<div class="extra-fields">
<input type="text" name="physical_address" placeholder="Town/city (e.g. Lobamba)">
<input type="text" name="region" placeholder="Region (e.g. Hhohho)" required>
</div>
</div>
</div>
<!-- LEGAL -->
<div class="section-four">
<h3>Legal</h3>
<div class="consent">
<input type="checkbox" name="consent" value="Given" required>
I/We give
</div>
<div class="consent">
<input type="checkbox" name="consent_1" value="Yes" required>
I/We confirm .
<div class="extra-fields">
<input type="text" name="acount_name" placeholder="Account Name">
<input type="text" name="account_number" placeholder="Account Number" required>
</div>
</div>
<div class="consent">
<input type="checkbox" name="consent_3" value="Accepted" required>
I/We agree .
</div>
<div class="consent">
<input type="checkbox" name="consent_4" value="Confirmed" required>
I/We confirm
</div>
<div class="consent">
<input type="checkbox" name="consent_5" value="Acknowledged" required>
I/We acknowledge
</div>
<div class="consent">
<input type="checkbox" name="consent_6" value="Confirmed" required>
authorised.
</div>
</div>
<input type="submit" value="Submit" name="submit">
</form>
<?php
if ($listing_saved) {
redirect('listings_Properties.php', 'Your submition has been received. Please give us time to verify validity of the provided information.', 'sucess');
}
?>
</div>
<?php include 'templates/inc/footer.php' ?>
code for the redirect script is
<?php
function redirect($page = FALSE, $message = NULL, $message_type = NULL){
if(is_string($page)){
$location = $page;
}
else{
$location = $_SERVER['SCRIPT_NAME'];
}
// check for message
if($message != null){
$_SESSION['message'] = $message;
}
// check for message type
if($message_type != null){
$_SESSION['message_type'] = $message_type;
}
//...then redirect
header('Location: '. $location);
exit;
}
// display the message
function display_message(){
if(!empty($_SESSION['message'])){
$message = $_SESSION['message'];
if(!empty($_SESSION['message_type'])){
$message_type = $_SESSION['message_type'];
if($message_type == 'error'){
echo '<div class="alert alert-danger" id="msg">'.$message.'</div>';
}
else{
echo '<div class="alert alert-success" id="msg">'.$message.'</div>';
}
}
unset($_SESSION['message']);
unset($_SESSION['message_type']);
}
else{
echo '';
}
}
Thank you to everyone who contributed towards me figuring out what really the problem.
What I didn't realize was that the max file upload in the script is set to 2MB while I was uploading images larger than 2MB, and my error handler wasn't working to actually prompt that. Again thank you to everyone who had suggestions. They really helped me figure out each step

PDO error 42000

i had an error when i run my code and i don't understand this error
error:
Fatal error: Uncaught PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE UserID = 'ahmed' SET Username = 'adasda#dmail.ck',Email = 'ahmed',FullName' at line 1 in C:\wamp64\www\eC
<?php
/*
==============================================================
= Manage Member do
= you can Add | Edit | Delete Members from here
==============================================================
*/
session_start();
$pageTitle = 'Members';
if(isset($_SESSION['Username'])){
include 'init.php';
$do = isset($_GET['do']) ? $_GET['do'] : 'Manage';
// $do= '';
//
// if(isset($_GET['do'])){
//
// $do = $_GET['do'];
// }else {
// $do = 'Manage';
// }
// start Manage do
if ($do == 'Manage') {
echo 'welcom in manage do';
//Manage page
}elseif ($do == 'Edit') { //edit page
// check If the GET Request is Numeric && Get the Integer value of it
$userid = isset($_GET['userid']) && ($_GET['userid']) ? intval($_GET['userid']) : 0;
// Select the row of user from the table
// select All data Depend on this Id
$stmt = $con->prepare("SELECT * FROM users WHERE UserID = ? LIMIT 1");
// extract Query
$stmt->execute(array($userid));
// Fetch the data
$row = $stmt->fetch();
// the row count
$count = $stmt->rowCount(); // to count the row in the table
if ($stmt->rowCount() > 0) {
?>
<h1 class="text-center">Edit Member</h1>
<div class="container">
<form class="form-horizontal" action="?do=Update" method="POST">
<input type="hidden" name='userid' value="<?php echo $userid ?>"/>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Username</label>
<div class="col-sm-10">
<input type="text" name="username" class="form-control" value="<?php echo $row['Username'] ?>" autocomplete="off"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Password</label>
<div class="col-sm-10">
<input type="hidden" name="oldpassword"/>
<input type="password" name="newpassword" class="form-control" autocomplete="new-password"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">E-mail</label>
<div class="col-sm-10">
<input type="email" name="email" class="form-control" value="<?php echo$row['Email'] ?>" autocomplete="off"/>
</div>
</div>
<div class="form-group form-group-lg">
<label class="col-sm-2 control-lable">Full-Name</label>
<div class="col-sm-10">
<input type="text" name="full" class="form-control" value="<?php echo$row['FullName'] ?>" autocomplete="off" />
</div>
</div>
<div class="form-group form-group-lg">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" value="save" class="btn btn-primary btn-lg" />
</div>
</div>
</form>
</div>
<?php
}else {
echo "you are not welcom in this page ";
}
}
// update page
elseif ($do == 'Update') {
echo "<h1 class='text-center'> welcom in the update page </h1>";
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
# get the variable from the form
$id = $_POST['userid'];
$user = $_POST['username'];
$email= $_POST['email'];
$name = $_POST['full'];
//echo $id . $user . $pass . $name;
$stmt = $con->prepare('UPDATE users WHERE UserID = ? SET Username = ?,Email = ?,FullName = ?,');
$stmt->execute(array($user,$email,$name,$id));
echo $stmt->rowCount() . "Record Updated";
}else {
echo "you cant brows this page directly";
}
}
include $tpl . 'footer.php';
}else {
header('location: index.php');
exit();
}
?>
ommers\first_project\admin\members.php on line 110
Your update query is incorrect, you need to use the following:
$stmt = $con->prepare('UPDATE users SET Username = ?,Email = ?,FullName = ? Where UserId =?');
And change the rest of the code accordingly.

PHP- Form Validation Errors

This is my first time validating, I am having the hardest time have spent endless hours on this already. I have a registration form that needs to be validated, i have tried 2 scripts for this. The script that works best can be seen below: however every time I try to echo the error message to display under my text field i receive the following error messages:
Notice: Undefined variable: c_email in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 161
Notice: Undefined variable: c_emailErr in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 163
Notice: Undefined variable: c_pass1Err in /Applications/MAMP/htdocs/PhpProject2/Reg_1.php on line 169
C_emailErr and c_pass1Err are both defined.
any help would be appreciated.
HTML
<section class="container">
<form id="myform " class="Form" method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" accept-charset="utf-8">
<!--<div id="first">-->
<input type="email" id="email" name="email" placeholder="Email Address" value="<?= $c_email ?>" required >
<br>
<span class="error"><?php echo $c_emailErr; ?></span>
<br>
<figure>
<input class ="login-field" type="password" id="pass1" name="pass1" value="<?= $c_pass1 ?>" placeholder="Password" maxlength="30" required>
<br>
<span class="error"><?php echo $c_pass1Err; ?></span>
<br>
<input class ="login-field" type="password" id="pass2" name="pass2" value="" placeholder=" Confirm password" maxlength="30" required><!--<span class="error"><?php //echo $c_pass2Err; ?></span>-->
<div id="messages"></div>
</figure>
<p class="remember_me">
</p>
<input type="submit" name="submit" value="Register" id="submit_button" class="btn btn-default">
<br>
</form>
<?php
?>
</form>
</section>
PHP
<?php
if (isset($_POST['submit'])) {
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
//Checking the email address
if (!filter_var($c_email, FILTER_VALIDATE_EMAIL) === false) {
echo ("<b id='email'> This is a valid email address </b>");
} else {
echo ("<b id='email'> Email is not a valid email address</b>");
}
if (strlen($c_pass1) <= '8') {
echo "<b>Your Password Must Contain At Least 8 Characters!</br>";
//check passwords
} elseif ($c_pass1 == $c_pass2) {
$q = "INSERT INTO Cus_Register(Cus_Email,Cus_Password,Cus_confirm_password) VALUES (?,?,?)";
$stmt = mysqli_prepare($dbc, $q);
//new
// $stmt = mysqli_prepare($dbc, $insert_c);
//debugging
//$stmt = mysqli_prepare($dbc, $insert_c) or die(mysqli_error($dbc));
mysqli_stmt_bind_param($stmt, 'sss', $c_email, $c_pass1, $c_pass2);
if ($q) {
echo "<script> alert('registration sucessful')</script>";
}
} else {
echo "<b>Oops! Your passwords do not </b>";
}
}
?>
You are defining those variables, but you are defining them inside of an if block.. Move them outside of the if block.
<?php
$c_emailErr = $c_pass1Err = $c_pass2Err = "";
if (isset($_POST['submit'])) {
$c_email = $_POST['email'];
$c_pass1 = $_POST['pass1'];
$c_pass2 = $_POST['pass2'];

PHP Adding Data to Database

I've been testing a CRUD interface with PHP and SQLSRV driver but i got stuck on the creating part, i can read the data that alredy was added on the database by id, but i cant get to work the create data from PHP to the database, when i press the create Button it clears the inputs and shows the errors. Would like to know if there is something wrong with my code so far.
PHP CODE:
<?php
require 'database.php';
if ( !empty($_POST)) {
$iError = null;
$nError = null;
$dError = null;
$tError = null;
$id = $_POST['id'];
$name = $_POST['name'];
$Address = $_POST['Address'];
$phone = $_POST['phone'];
$valid = true;
if (empty($id)) {
$iError = 'add id';
$valid = false;
}
if (empty($name)) {
$nError = 'add name';
$valid = false;
}
if (empty($Address)) {
$dError = 'add address';
$valid = false;
}
if (empty($phone)) {
$tError = 'add phone';
$valid = false;
}
if ($valid) {
$tsql = "INSERT INTO dbo.TEST1 (id, name, Address, phone) values(?, ?, ?, ?)";
$arr1 = array($id, $name, $Address, $phone);
$stmt = sqlsrv_query($conn, $tsql, $arr1 );
if ( $stmt === FALSE ){
echo "New data created";
}
else {
echo "Error creating data";
die(print_r(sqlsrv_errors(),true));
}
}
}?>`
this is the HTML part:
<body>
<div>
<div>
<h3>CREAR</h3>
</div>
<form class="form-horizontal" action="create.php" method="post">
<div class=" <?php echo !empty($iError)?'error':'';?>">
<label >ID</label>
<div >
<input name="name" type="text" placeholder="ID" value="<?php echo !empty($id)?$id:'';?>">
<?php if (!empty($iError)): ?>
<span ><?php echo $iError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($nError)?'error':'';?>">
<label>name</label>
<div>
<input name="name" type="text" placeholder="name" value="<?php echo !empty($name)?$name:'';?>">
<?php if (!empty($nError)): ?>
<span><?php echo $nError;?></span>
<?php endif; ?>
</div>
</div>
<div class=" <?php echo !empty($emailError)?'error':'';?>">
<label >Address</label>
<div >
<input name="email" type="text" placeholder="Address" value="<?php echo !empty($Address)?$Address:'';?>">
<?php if (!empty($dError)): ?>
<span><?php echo $dError;?></span>
<?php endif;?>
</div>
</div>
<div class=" <?php echo !empty($tError)?'error':'';?>">
<label >phoner</label>
<div >
<input name="mobile" type="text" placeholder="phone" value="<?php echo !empty($phone)?$phone:'';?>">
<?php if (!empty($tError)): ?>
<span ><?php echo $tError;?></span>
<?php endif;?>
</div>
</div>
<div >
<button type="submit">Create</button>
Return
</div>
</form>
</div>
</div>

Bootstrap modal doesn't respond to my PHP submit form

It doesn't show any error and it doesn't respond when I click Save button. I've tried the PHP insert code in other page without bootstrap and it works I wonder why it's not working in bootstrap modal.
Here's my HTML code:
<div class="modal-content">
<div class="modal-header">
<h4>Add Topic</h4>
</div>
<div class="modal-body">
<form method="POST" action="index.php" role="form">
<div class="form-group">
<label for="cCategory">Category</label>
<input type="text" class="form-control" id="cCategory" name="category" value="<?php if (!empty($categ)) { echo $categ; } ?>">
</div>
<div class="form-group">
<label for="cTitle">Title</label>
<input type="text" class="form-control" id="cTitle" name="topicTitle" value="<?php if (!empty($topicTitle)) { echo $topicTitle; } ?>">
</div>
<div class="form-group">
<label for="cDesc">Description</label>
<textarea class="form-control custom-control" rows="3" style="resize:none" name="desc" value="<?php if (!empty($desc)) { echo $desc; } ?>"> </textarea>
</div>
<div class="form-group">
<label for="cDesc">Created By</label>
<input type="text" class="form-control" id="cDesc" name="createdby" value="<?php if (!empty($created)) { echo $created; } ?>">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" name="submit" class="btn btn-primary">Save changes</button>
</div>
</div>
And this my PHP code:
if(!empty($desc) && !empty($categ) && !empty($topicTitle) && !empty($topicTitle) && !empty($created)) {
if($insert = $db->query("
INSERT INTO pncontent (category, title, description, createdby, dateadded)
VALUES ('$categ', '$topicTitle', '$desc', '$created', NOW() )
")) {
echo $db->affected_rows, " Topic Save!";
}else {
echo "Failed to Save";
}
}else {
echo "<p>All Fields are required</p>";
$desc = $_POST['desc'];
$categ = $_POST['category'];
$topicTitle = $_POST['topicTitle'];
$created = $_POST['createdby'];
}
}
Your button Submit is out of <form></form> tag. Kepp it inside <form></form> tag to submit the form.
And also check this line:
if(!empty($desc) && !empty($categ) && !empty($topicTitle) && !empty($topicTitle) && !empty($created))
Should be:
if(!empty($_POST['desc']) && !empty($_POST['category']) && !empty($_POST['topicTitle']) && !empty($_POST['createdby']))
You are checking variables before declaring it, use $_POST instead.
Your code should look like this:
<?php
if(!empty($_POST['desc']) && !empty($_POST['category']) && !empty($_POST['topicTitle']) && !empty($_POST['createdby'])) {
$desc1 = $_POST['desc'];
$categ1 = $_POST['category'];
$topicTitle1 = $_POST['topicTitle'];
$created1 = $_POST['createdby'];
if($insert = $db->query("
INSERT INTO pncontent (category, title, description, createdby, dateadded)
VALUES ('$categ1', '$topicTitle1', '$desc1', '$created1', NOW() )
")) {
echo $db->affected_rows, " Topic Save!";
}else {
echo "Failed to Save";
}
}else {
echo "<p>All Fields are required</p>";
$desc = $_POST['desc'];
$categ = $_POST['category'];
$topicTitle = $_POST['topicTitle'];
$created = $_POST['createdby'];
}
}

Categories