Kafi Brown Kafi Brown - 6 months ago 14
PHP Question

php unidentified index error message

Since I added

$city=$_POST['city'];


I've been getting this error message.


Undefined index: city in C:\wamp\www\assignment\html\img_upload.php on line 39.


city is a select field in the form.

This is the code

<?php
require 'login.php';

$path = 'img/';
if (isset($_POST['submit'])) {
// Grab the image from the POST array
$fn=$_POST['fname'];
$ln=$_POST['lname'];
$sex=$_POST['sex'];
$city=$_POST['city'];
$em=$_POST['email'];
$pass=$_POST['pword'];
$confirm=$_POST['cword'];
//$gend = $_POST['gender']; not using now
$pic = $_FILES['pic']['name'];
if (!empty($fn) && !empty($ln) && !empty($pic)) {
// Move the file to the target upload folder
$target = $path.$pic;//create image source (src)
if (move_uploaded_file($_FILES['pic']['tmp_name'], $target)) {


// // Connect to the database
$dbase = mysqli_connect('localhost', 'root', '', 'flowers');
// Write the data to the database
$my_query = "insert into members values ('$fn', '$ln', '$sex','$city','$em','$pass', '$pic');";
mysqli_query($dbase, $my_query);

$result = mysqli_query($dbc, $query);


if ($result){
// // Confirm success with the user
// echo '<p>Thank you for registering with us!</p>';
// echo '<p><strong>Name:</strong> ' . $fn .' '.$ln .'<br />';
// echo '<img src="' . $path . $pic . '" alt="profile image" /></p>';
// echo '<p><a href="index.html">&lt;&lt; Return to home page</a></p>';
}
else echo "Sorry you have an error: ".$mysqli_error($dbc);

}
}
}

?>

Answer

It seems that you have not posted the variable $_POST['city'].

Whenever you have dynamic fields in your form, you are unsure which fields will get posted.

In this case, use isset().

$city = isset($_POST['city']) ? $_POST['city'] : '';

This ensures that you do not get any Notice error.