After uploading the image, image is not show with user profile
Image profile not display correctly.
Code Given as below:
Uploaded image doesn't display immediately
When I submit the user profile first name last name and image upload when click submit button first name and last name is updated first and last name is show but image is updated and image is not show.
<?php
if (!defined('ABSPATH')) {
header("Location: /theme");
die("");
}
if (isset($_POST['update'])) {
$user_id = esc_sql($_POST['user_id']);
$fname = esc_sql($_POST['user_fname']);
$lname = esc_sql($_POST['user_lname']);
if ($_FILES['user_img']['error'] == false) {
$file = $_FILES['user_img'];
$ext = explode('/', $file['type'])[1];
$file_name = "$user_id.$ext";
$image = wp_upload_bits($file_name, null, file_get_contents($file['tmp_name']));
if (!metadata_exists('user', $user_id, 'user_profile_img_url')) {
add_user_meta($user_id, 'user_profile_img_url', $image['url']);
add_user_meta($user_id, 'user_profile_img_path', esc_sql($image['file']));
} else {
update_user_meta($user_id, 'user_profile_img_url', $image['url']);
update_user_meta($user_id, 'user_profile_img_path', esc_sql($image['file']));
}
}
$userdata = array(
'ID' => $user_id,
'first_name' => $fname,
'last_name' => $lname,
);
$user = wp_update_user($userdata);
if (is_wp_error($user)) {
echo 'Can not update: ' . $user->get_error_message();
}
}
$user_id = get_current_user_id();
$user = get_userdata($user_id);
if ($user != false) :
// echo $user;
// echo get_usermeta($user_id);
$fname = get_usermeta($user_id, 'first_name');
$lname = get_usermeta($user_id, 'last_name');
$profile_image = get_usermeta($user_id, 'user_profile_img_url');
/* global $current_user;
wp_get_current_user();
if (is_user_logged_in()) {
// $username = $current_user->user_login;
// $displayname = $current_user->display_name;
} else {
wp_loginout();
} */
// $lname = get_user_meta($user_id, 'last_name');
?>
<?php
if ($profile_image != '') {
?>
<img src="<?php echo $profile_image; ?>" />
<?php
}
?>
<h1><?php echo "$fname $lname "; ?></h1>
<p>Not <?php echo "$fname $lname"; ?> Logout</p>
<form action="<?php get_the_permalink(); ?>" method="post" enctype="multipart/form-data">
profile Image: <input type="file" name="user_img" id="user-img" /></br>
First name: <input type="text" name="user_fname" id="user-fname" value="<?php echo $fname; ?>"></br>
Last name: <input type="text" name="user_lname" id="user-lname" value="<?php echo $lname; ?>"></br>
<input type="hidden" name="user_id" value="<?php echo $user_id; ?> ">
<input type="submit" name="update" value="Update">
</form> <?php
endif;
?>
[enter image description here][1]
[1]: https://i.stack.imgur.com/tSQPd.png
Related
I got this form for adding new posts and i can't get it to write to DB. I debugged it as much as i can and when i try to add i don't get any errors but also i don't see the post stored in my DB. Am i missing something? Code:
-This is the form
<form method = "post" action = "vpost.php" enctype="multipart/form-data">
<label>
<h5>Наслов</h5>
<input type="text" name="title" placeholder="Enter title" value = "<?php if(isset($_POST['title'])) { echo $post_title; } ?>">
</label>
<label>
<h5>Адреса</h5>
<input type="text" name="address" placeholder="Enter address" value = "<?php if(isset($_POST['address'])) { echo $post_address; } ?>">
</label>
<hr>
<label>
<h5>Цена</h5>
<input type="number" name="price" placeholder="Enter price" value = "<?php if(isset($_POST['price'])) { echo $post_price; } ?>">
</label>
<hr>
<label>
<h5>Тип</h5>
<input type="text" name="type" placeholder="Enter type" value = "<?php if(isset($_POST['type'])) { echo $post_type; } ?>">
</label>
</div>
<hr>
<div class="user-information-second">
<label>
<h5>Година на градба</h5>
<input type="number" name="year_built" placeholder="Year Built" <?php if(isset($_POST['year_built'])) { echo $post_yearbt; } ?>>
</label>
<hr>
<label>
<h5>Паркинг</h5>
<input type="text" name="parking" placeholder="parking" value = "<?php if(isset($_POST['parking'])) { echo $post_parking; } ?>">
</label>
<hr>
<label>
<h5>Квадратура</h5>
<input type="number" name="sqmeter" placeholder="sqmeter" value = "<?php if(isset($_POST['sqmeter'])) { echo $post_sqmeter; } ?>">
</label>
<br>
<hr>
<label>
<h5>Греење/Ладење</h5>
<input type="text" name="heat" placeholder="Heating" value = "<?php if(isset($_POST['heat'])) { echo $post_heat; } ?>">
</label>
<br>
<hr>
<label>
<h5>Галерија</h5>
<div class="file">
<input type="file" name="image" enctype="multipart/form-data" placeholder="Upload Image">
</div>
</label>
<br>
<hr>
<label>
<button type="submit" id="submit">Внеси Оглас</button>
</label>
</form>
-This is the validation and writing to base file
<?php
include('includes/general.php');
if (isset($_POST['title']) && isset($_POST['address']) && isset($_POST['price']) &&
isset($_POST['type']) && isset($_POST['year_built']) && isset($_POST['parking']) &&
isset($_POST['sqmeter']) && isset($_POST['heat']) && isset($_POST['image'])) {
require("GUMP-master/gump.class.php");
$gump = new GUMP();
$_POST = $gump->sanitize($_POST);
$gump->validation_rules(array(
'title' => 'required|max_len,120|min_len,15',
'address' => 'required|max_len,100|min_len,3',
'price' => 'required',
'type' => 'required',
'year_built' => 'required',
'parking' => 'required',
'sqmeter' => 'required',
'heat' => 'required',
));
$gump->filter_rules(array(
'title' => 'trim|sanitize_string',
'address' => 'trim|sanitize_string',
));
$validated_data = $gump->run($_POST);
if($validated_data === false) {
?>
<center><font color="red" > <?php echo $gump->get_readable_errors(true); ?> </font></center>
<?php
$post_title = $_POST['title'];
$post_address = $_POST['address'];
$post_price = $_POST['price'];
$post_type = $_POST['type'];
$post_yearbt = $_POST['year_built'];
$post_parking = $_POST['parking'];
$post_sqmeter = $_POST['sqmeter'];
$post_heat = $_POST['heat'];
}
else {
$post_title = $validated_data['title'];
$post_address = $validated_data['address'];
$post_price = $validated_data['price'];
$post_type = $validated_data['type'];
$post_yearbt = $validated_data['year_built'];
$post_parking = $validated_data['parking'];
$post_sqmeter = $validated_data['sqmeter'];
$post_heat = $validated_data['heat'];
if (isset($_SESSION['firstname'])) {
$post_author = $_SESSION['firstname'];
}
$post_date = date('Y-m-d');
$image = $_FILES['image']['name'];
$ext = $_FILES['image']['type'];
$validExt = array ("image/gif", "image/jpeg", "image/pjpeg", "image/png", "image/jpg");
if (empty($image)) {
echo "<script>alert('Attach an image');</script>";
}
else if ($_FILES['image']['size'] <= 0 || $_FILES['image']['size'] > 1024000 )
{
echo "<script>alert('Image size is not proper');</script>";
}
else if (!in_array($ext, $validExt)){
echo "<script>alert('Not a valid image');</script>";
}
else {
$folder = 'postpics/';
$imgext = strtolower(pathinfo($image, PATHINFO_EXTENSION) );
$picture = rand(1000 , 1000000) .'.'.$imgext;
if(move_uploaded_file($_FILES['image']['tmp_name'], $folder.$picture)) {
$query = "INSERT INTO posts (title,address,price,type,year_built,parking,sqmeter,heat,date,image) VALUES ('$post_title' , '$post_address' , '$post_price' , '$post_type' , '$post_yearbt' , '$post_parking', '$post_sqmeter','$post_heat','$post_date','$picture')";
$result = mysqli_query($conn , $query) or die(mysqli_error($conn));
if (mysqli_affected_rows($conn) > 0) {
echo "<script> alert('Posted!');
window.location.href='index.php';</script>";
}
else {
"<script> alert('Error while posting..try again');</script>";
}
}
}
}
}
?>
First i thought that i might be missing a field in my DB but i rechecked and i created the table again. If needed i will post a picture of my posts table and the columns.
Your issue I suspect is you are checking if your image file has been uploaded with $_POST['image']. This isn't how PHP handles file uploads - they are stored in $_FILES instead so your isset($_POST['image'] == false.
This should work:
<?php
include('includes/general.php');
if (isset($_POST['title']) && isset($_POST['address']) && isset($_POST['price']) &&
isset($_POST['type']) && isset($_POST['year_built']) && isset($_POST['parking']) &&
isset($_POST['sqmeter']) && isset($_POST['heat']) && isset($_POST['image']) && count($_FILES) > 0)
{
//Properly sanitise and validate your inputs and do what else you need to do
}
Tip: if you ever find a PHP file just isn't doing what it should be, a conditional statement you're using to validate data is a very likely culprit. Try debugging by putting die('OK up to here'); within your if blocks to pinpoint whether code is being executed.
For example, in your code if you had debugged with:
<?php
include('includes/general.php');
if (isset($_POST['title']) && isset($_POST['address']) && isset($_POST['price']) &&
isset($_POST['type']) && isset($_POST['year_built']) && isset($_POST['parking']) &&
isset($_POST['sqmeter']) && isset($_POST['heat']) && isset($_POST['image'])) {
die('OK up to here');
//Your code
}
Then the OK up to here message wouldn't have been displayed in your output and you would know there was a problem with the conditional statement.
I encountered problem with codeigniter. I want to update my profile page. I have problem when passing data from textbox in view to controller. In controller Profile.php, i have print_r $data that show no data get from view. Hope you guys can help me. Thank you.
View profile.php
if(isset($profile)){
?>
<?php echo validation_errors();?>
<?php echo form_open('profile/update_profile'); ?>
<div class="field half first"><input type="password" name="pass" placeholder="Password" value="<?php echo $profile['password']; ?>" /></div>
<div class="field half"><input type="password" name="con_pass" placeholder="Confirm Password" value="<?php echo $profile['con_password']; ?>" /></div>
<div class="field half"><input type="text" name="phone_no" placeholder="Phone Number" value="<?php echo $profile['phone_no']; ?>" /></div>
<li><?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?></li>
</ul>
<?php echo validation_errors();?>
<?php echo form_close(); ?>
<?php
}
?>
Controller Profile.php
public function update_profile(){
$email = $_SESSION['email'];
// $data['profile'] = $this->profile_model->getprofile($email);
$data = array(
'password' => $this->input->post('pass'),
'con_password' => $this->input->post('con_pass'),
'phone_no' => $this->input->post('phone_no')
);
print_r($data);
if($this->profile_model->updateprofile($email,$data))
{
$this->load->view('provider/profile', $data);
}
}
Model profile_model.php
public function updateprofile($email, $data){
$this->db->where('email', $email);
return $this->db->update('user', $data);
}
}
Try like below with form validation
https://www.codeigniter.com/user_guide/libraries/form_validation.html
https://www.codeigniter.com/user_guide/libraries/form_validation.html#rule-reference
EXAMPLE
public function update_profile() {
$this->load->library('form_validation');
// You can change what you want set for the rules your self this just example:
$this->form_validation->set_rules('pass', 'pass', 'trim|required');
$this->form_validation->set_rules('con_pass', 'con_pass', 'trim|required|matches[pass]');
$this->form_validation->set_rules('phone_no', 'phone_no', 'trim|required');
if ($this->form_validation->run() == TRUE) {
// Update model stuff
}
$email = $_SESSION['email']; // User id instead of email.
$profile_data = $this->users_model->getprofile($email);
if ($this->input->post('pass')) {
$data['pass'] = $this->input->post('pass');
} elseif (!empty($profile_data)) {
$data['pass'] = $profile_data['pass'];
} else {
$data['pass'] = '';
}
if ($this->input->post('con_pass')) {
$data['con_pass'] = $this->input->post('con_pass');
} elseif (!empty($profile_data)) {
$data['con_pass'] = $profile_data['con_pass'];
} else {
$data['con_pass'] = '';
}
if ($this->input->post('phone_no')) {
$data['phone_no'] = $this->input->post('phone_no');
} elseif (!empty($profile_data)) {
$data['phone_no'] = $profile_data['phone_no'];
} else {
$data['phone_no'] = '';
}
$this->load->view('provider/profile', $data);
}
Model function
public function getprofile($email) {
$this->db->where('email', $email);
$query = $this->db->get('users');
return $query->row_array();
}
View Example
<?php echo form_open('profile/update_profile'); ?>
<?php echo validation_errors();?>
<input type="password" name="pass" value="<?php echo set_value('pass', $pass);?>"/>
<input type="password" name="con_pass" value="<?php echo set_value('con_pass', $con_pass);?>"/>
<input type="text" name="phone_no" value="<?php echo set_value('phone_no', $phone_no);?>" />
<?php echo form_submit(array('id' => 'submit', 'value' => 'Update')); ?>
<?php echo form_close();?>
i try to challenge my self but i stuck(
I try to create a php form with 2 steps confirmation:
When the user fill up the form and hit Submit, it checks all the conditions(name, pass etc.). If everything ok automatically redirecting the user.
After redirecting (to the same page) the user can check all the details again.
If they ok, hit again the submit button which redirects to the final page.
I stuck on the 2nd phase...how to redirect to the final page?
I'm very beginner so i'm curios what could be done better or any advise.
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
</body>
</html>
Add action in your form to redirect final page.
You already have all values in session so you can access it in final page also
<?php
// the php code
session_start();
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// setting up the variables
$title = $_POST['title'];
$fName = trim(filter_input(INPUT_POST,'fName', FILTER_SANITIZE_STRING));
$lName = trim(filter_input(INPUT_POST,'lName',FILTER_SANITIZE_STRING));
$age = intval($_POST['age']);
$_SESSION['title'] = $title;
$_SESSION['fName'] = $fName;
$_SESSION['lName'] = $lName;
$_SESSION['age'] = $age;
//checking for possible errors
if ( $fName == "" || strlen($fName) <= 2 ) {
$errorMsg1 = "<span>Provide your First name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $lName == "" || strlen($lName) <= 2 ) {
$errorMsg2 = "<span>Provide your Last name!(minimum 3 characters)</span>";
$status = false;
}
else if ( $age < 18 ) {
$errorMsg3 = "<span>You must be 18 or above!</span>";
$status = false;
}
else { $status = true; }
// redirecting to done page
if ($status) {
header("Location:TEST ZONE.php?status=awaiting");
}
}
?>
<!doctype html>
<html>
<head>
<title></title>
</head>
<body>
<div id="wrapper">
<?php
if ( isset($_GET['status']) && $_GET['status'] == "awaiting" ) {
echo "<form action='final_page.php'>"
. "Check your Details!<br>"
. $_SESSION['title'] . "<br>"
. $_SESSION['fName'] . "<br>"
. $_SESSION['lName'] . "<br>"
. $_SESSION['age'] . "<br>"
// **NOW WHEN I'M in the awaiting phase, i don't know what to do(**
. "<input type='submit' name='submit'/>";
echo "</form>";
}
else { ?>
<form action="TEST ZONE.php" method="post">
<h3>Register Form </h3>
<label for="title">Title </label>
<select name="title">
<option name="mr">Mr</option>
<option name="ms">Ms</option>
</select><br><br><br>
<label for="fName">First Name</label><br>
<input type="text" name="fName" id="fName" value="<?php if (isset($fName)) { echo $fName; } ?>"><br><?php
if (isset( $errorMsg1 )) {
echo $errorMsg1;
}
?><br><br>
<label for="lName">Last Name</label><br>
<input type="text" name="lName" id="lName" value="<?php if (isset($lName)) { echo $lName; } ?>"><br><?php
if (isset( $errorMsg2 )) {
echo $errorMsg2;
}
?><br><br>
<label for="age">Age</label><br>
<input type="text" name="age" id="age" value="<?php if (isset($age)) { echo $age; }?>"><br><?php
if (isset($errorMsg3)){
echo $errorMsg3;
} ?><br><br>
<input type="submit" value="Submit"><input type="reset">
</form> <?php } ?>
</div>
final_page.php
<?php
session_start();
$title = $_SESSION['title'];
$fName = $_SESSION['fName'];
$lName = $_SESSION['lName'];
$age = $_SESSION['age'];
?>
I wrote a customer_display.php to validate data (only First Name so far), but no matter First Name field is empty or not, the webpage will jump to customer_search.php & did not change information in database. why?
<?php include '../view/header.php';
<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>
<?php
// Initialize variables and set to empty strings
$firstName=$lastName="";
$firstNameErr=$lastNameErr="";
// Control variables
$app_state = "empty"; //empty, processed, logged in
$valid = 0;
// Validate input and sanitize
if ($_SERVER['REQUEST_METHOD']== "POST") {
if(isset($_POST["first_name"]))
{
if (empty($_POST["first_name"])) {
$firstNameErr = "First name is required";
}
else {
$firstName = test_input($_POST["firstName"]);
if(strlen($firstName)>5){
$firstNameErr = "First name is too long";
}
else{
$valid++;
}
}
}
if (empty($_POST["lastName"])) {
$lastNameErr = "Last name is required";
}
else {
$lastName = test_input($_POST["lastName"]);
$valid++;
}
if ($valid >= 2) {
$app_state = "processed";
}
}
// Sanitize data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if ($app_state == "empty") {
?>
<!-- display a table of customer information -->
<h2>View/Update Customer</h2>
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']);?>" method="POST" id="aligned">
<input type="hidden" value="update_customer">
<input type="hidden" name="customer_id"
value="<?php echo htmlspecialchars($customer['customerID']); ?>">
<label>First Name:</label>
<input type="text" name="first_name"
value="<?php echo htmlspecialchars($customer['firstName']); ?>">
<span class="error"><?php echo $firstNameErr;?></span><br>
<label>Last Name:</label>
<input type="text" name="last_name"
value="<?php echo htmlspecialchars($customer['lastName']); ?>"><br>
<label>Address:</label>
<input type="text" name="address"
value="<?php echo htmlspecialchars($customer['address']); ?>"
size="50"><br>
<label>City:</label>
<input type="text" name="city"
value="<?php echo htmlspecialchars($customer['city']); ?>"><br>
<label>State:</label>
<input type="text" name="state"
value="<?php echo htmlspecialchars($customer['state']); ?>"><br>
<label>Postal Code:</label>
<input type="text" name="postal_code"
value="<?php echo htmlspecialchars($customer['postalCode']); ?>"><br>
<label>Country:</label>
<select name="selected">
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass ='';
$db = 'tech_support';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $db);
if($conn->connect_error)
die('Could not connect: '. $conn->connect_error);
$selected= $conn->query("select * from countries where countryCode = '" .$customer['countryCode']. "'");
$sql = $conn->query("select * from countries order by countryName");
if($selectedrow = $selected->fetch_assoc()){
echo "<option selected value='" . $selectedrow['countryName']."'>". $selectedrow['countryName']."</option>";
}
//echo "<select>";
while ($row = $sql->fetch_assoc()) {
echo "<option value ='". $row['countryName']."'>". $row['countryName']."</option>";
}
//echo "</select>";
$conn->close();
?>
</select><br>
<label>Phone:</label>
<input type="text" name="phone"
value="<?php echo htmlspecialchars($customer['phone']); ?>"><br>
<label>Email:</label>
<input type="text" name="email"
value="<?php echo htmlspecialchars($customer['email']); ?>"
size="50"><br>
<label>Password:</label>
<input type="text" name="password"
value="<?php echo htmlspecialchars($customer['password']); ?>"><br>
<label> </label>
<input type="submit" value="Update Customer"><br>
</form>
<p>Search Customers</p>
</body>
</html>
<?php
}
elseif ($app_state == "processed") {
if ($firstName == "Vincent") {
$app_state = "Logged in";
}
}
if ($app_state == "Logged in") {
echo("Logged in<br> Hello Vincent</body></html>");
}
?>
<?php include '../view/footer.php'; ?>
index.php(to process the data):
<?php
require('../model/database.php');
require('../model/customer_db.php');
$action = filter_input(INPUT_POST, 'action');
if ($action === NULL) {
$action = filter_input(INPUT_GET, 'action');
if ($action === NULL) {
$action = 'search_customers';
}
}
//instantiate variable(s)
$last_name = '';
$customers = array();
if ($action == 'search_customers') {
include('customer_search.php');
} else if ($action == 'display_customers') {
$last_name = filter_input(INPUT_POST, 'last_name');
if (empty($last_name)) {
$message = 'You must enter a last name.';
} else {
$customers = get_customers_by_last_name($last_name);
}
include('customer_search.php');
} else if ($action == 'display_customer') {
$customer_id = filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT);
$customer = get_customer($customer_id);
include('customer_display.php');
} else if ($action == 'update_customer') {
$customer_id = filter_input(INPUT_POST, 'customer_id', FILTER_VALIDATE_INT);
$first_name = filter_input(INPUT_POST, 'first_name');
//echo $first_name;
$last_name = filter_input(INPUT_POST, 'last_name');
$address = filter_input(INPUT_POST, 'address');
$city = filter_input(INPUT_POST, 'city');
$state = filter_input(INPUT_POST, 'state');
$postal_code = filter_input(INPUT_POST, 'postal_code');
$country_name = $_POST["selected"];
$phone = filter_input(INPUT_POST, 'phone');
$email = filter_input(INPUT_POST, 'email');
$password = filter_input(INPUT_POST, 'password');
//if(!$valid_fname == null){require ('customer_display.php');};
//echo $country_name;
$country_code = get_countryCode($country_name);
update_customer($customer_id, $first_name, $last_name,
$address, $city, $state, $postal_code, $country_code,
$phone, $email, $password);
include('customer_search.php');
}
?>
You have no name attribute with the value of 'action', so your update never happens.
<form action="" method="POST">
<input type="hidden" value="update_customer">
<!-- rest of the form -->
</form>
Edited for clarity.
I am new to php and have created two forms. One form takes in the user's first name and the second takes in the user's last name. I am not sure why that when the user inputs text into the forms nothing is being passed.
The php with the forms
<?php include '../view/header.php'; ?>
<div id="main">
<h1>Add Athlete</h1>
<form action="index.php" method="post" id="add_product_form">
<input type="hidden" name="action" value="add_product" />
<label>Country:</label>
<select name="category_id">
<?php foreach ( $categories as $category ) : ?>
<option value="<?php echo $category['categoryID']; ?>">
<?php echo $category['categoryName']; ?>
</option>
<?php endforeach; ?>
</select>
<br />
<label>Code:</label>
<input type="input" name="code" />
<br />
<label>First Name:</label>
<input type="input" name="first_name" />
<br />
<label>Last Name:</label>
<input type="input" name="last_name" />
<br />
<label> </label>
<input type="submit" value="Add Athlete" />
<br /> <br />
</form>
<p>View List of Olympic Athletes</p>
</div>
<?php include '../view/footer.php'; ?>
The php that takes in input from the forms
<?php
require('../model/database.php');
require('../model/product_db.php');
require('../model/category_db.php');
if (isset($_POST['action'])) {
$action = $_POST['action'];
} else if (isset($_GET['action'])) {
$action = $_GET['action'];
} else {
$action = 'list_products';
}
if ($action == 'list_products') {
// Get the current category ID
$category_id = $_GET['category_id'];
if (!isset($category_id)) {
$category_id = 1;
}
// Get product and category data
$category_name = get_category_name($category_id);
$categories = get_categories();
$products = get_products_by_category($category_id);
// Display the product list
include('product_list.php');
} else if ($action == 'delete_product') {
// Get the IDs
$product_id = $_POST['product_id'];
$category_id = $_POST['category_id'];
// Delete the product
delete_product($product_id);
// Display the Product List page for the current category
header("Location: .?category_id=$category_id");
} else if ($action == 'show_add_form') {
$categories = get_categories();
include('product_add.php');
} else if ($action == 'add_product') {
$category_id = $_POST['category_id'];
$first_name = "";
if(isset($_POST['first_name'])){$first_name = $_POST['FirstName'];}
$last_name = "";
if(isset($_POST['last_name'])){$last_name = $_POST['LastName'];}
// Validate the inputs
if (empty($first_name) || empty($last_name)) {
$error = "Invalid product data. Check all fields and try again.";
include('../errors/error.php');
} else {
add_product($category_id, $first_name, $last_name);
// Display the Product List page for the current category
header("Location: .?category_id=$category_id");
}
} else if ($action == 'list_categories') {
$categories = get_categories();
include('category_list.php');
} else if ($action == 'add_category') {
$first_name = $_POST['FirstName'];
// Validate inputs
if (empty($name)) {
$error = "Invalid category name. Check name and try again.";
include('view/error.php');
} else {
add_category($name);
header('Location: .?action=list_categories'); // display the Category List page
}
} else if ($action == 'delete_category') {
$category_id = $_POST['category_id'];
delete_category($category_id);
header('Location: .?action=list_categories'); // display the Category List page
}
?>
The add_product function
function add_product($category_id, $first_name, $last_name) {
global $db;
$query = "INSERT INTO products
(categoryID, FirstName, LastName)
VALUES
('$category_id', '$first_name', '$last_name')";
$db->exec($query);
}
?>
Besides #MahfuzulAlam's answer, another problem is:
if(isset($_POST['first_name'])){$first_name = $_POST['FirstName'];}
^^^^^^^^^
if(isset($_POST['last_name'])){$last_name = $_POST['LastName'];}
^^^^^^^^
It should be:
if(isset($_POST['first_name'])){$first_name = $_POST['first_name'];}
if(isset($_POST['last_name'])){$last_name = $_POST['last_name'];}
Also, in PHP 7, there's a shorthand for what you are currently doing:
$first_name = $_POST['first_name'] ?? "";
$last_name = $_POST['last_name'] ?? "";
It's called Null Coalesce Operator.
Try using type = text not input. <input type="text" name="last_name" /> and so on.
And there are problems in this code.
if(isset($_POST['first_name'])){$first_name = $_POST['FirstName'];}
if(isset($_POST['last_name'])){$first_name = $_POST['LastName'];}
Whatever you pass as first_name and last_name your $first_name and $last_name variables will be empty. Because you are using $_POST['FirstName'], $_POST['LastName'] to set their values respectively, this don't really exists and both returning NULL. Rewrite these line as below:
if(isset($_POST['first_name'])){$first_name = $_POST['first_name'];}
if(isset($_POST['last_name'])){$first_name = $_POST['last_name'];}