I have this code below to insert in my Admins table the data that I store when when I fills the fields.
The insert is working fine, but Im having two notices and I´m trying to solve this but Im not finding a good method.
Somebody there can give a little help?
the two notices Im having:
-> Undefined index: date in $insertAdmin->bindValue(':avatar', $f['avatar']);
-> Undefined index: date in $insertAdmin->bindValue(':date_register', $f['date']);
My code:
if(isset($_POST['sendForm']))
{
$f['name'] = $_POST['name'];
$f['email'] = $_POST['email'];
//$f['avatar'] = $_POST['avatar'];
$f['date'] = $_POST['date_register'];
if(in_array('',$f))
{
echo 'Please, fill all fields.';
}
else
{
if(!empty($_FILES['avatar']['tmp_name']))
{
$image = $_FILES['avatar'];
$tmp = $imagem['tmp_name'];
$folder = '../uploads/avatars/';
$ext = substr($image['name'],-3);
$name = md5(time()).'.'.$ext;
$f['avatar'] = $name;
uploadImage($tmp, $name, '200', $folder);
}
$insertAdmin = $pdo->prepare("INSERT INTO admin (name, email, avatar, date_register) VALUES (:name, :email, :avatar, :date_register)");
$insertAdmin->bindValue(':name', $f['name']);
$insertAdmin->bindValue(':email', $f['email']);
$insertAdmin->bindValue(':avatar', $f['avatar']);
$insertAdmin->bindValue(':date_register', $f['date']);
}
}
My form:
<form name="form" action="" method="post" enctype="multipart/form-data">
<label class="line">
<span class="data">Name:</span>
<input type="text" name="name" value="<?php if(isset($f['name'])) echo $f['name'] ; ?>" />
</label>
<label class="line">
<span class="data">Email:</span>
<input type="text" name="email" value="<?php if(isset($f['email'])) echo $f['email'] ; ?>" />
</label>
<label class="line">
<span class="data">Avatar:</span>
<input type="file" class="fileinput" name="avatar" size="60" />
</label>
<label class="line">
<span class="data">Date of register:</span>
<input type="text" name="date_register" id="date" value="<?php if(isset($f['date'])) echo $f['date']; else echo date('d/m/Y H:i:s');?>" />
</label>
<input type="submit" value="Register" name="sendForm"/>
</form>
I see no valid reason to have the $f variable, it just makes it confusing.
I would personaly use the POST directly
if(isset($_POST['sendForm']
isset($_POST['name'] &&
isset($_POST['email'] &&
isset($_POST['avatar'] &&
isset($_POST['date'] &&){
//Insert
}else{
//please fill out everything
}
then execute like this
$insertAdmin = $pdo->prepare("INSERT INTO admin (name, email, avatar, date_register) VALUES (:name, :email, :avatar, :date_register)");
$insertAdmin->bindValue(':name', $_POST['name']);
$insertAdmin->bindValue(':email', $_POST['email']);
$insertAdmin->bindValue(':avatar', $_POST['avatar']);
$insertAdmin->bindValue(':date_register', $_POST['date']);
//do not forget to execute
$insertAdmin->execute();
You have a spelling error:
$f['date'] = $_POST['data_register'];
Needs to be:
$f['date'] = $_POST['date_register'];
//----------------------^
Which explains why $f['date'] is undefined.
use below an check again.
if(isset($_POST['sendForm']))
{
$f['name'] = $_POST['name'];
$f['email'] = $_POST['email'];
$f['avatar'] = $_POST['avatar'];
$f['date'] = $_POST['date_register'];
if(in_array('',$f))
{
echo 'Please, fill all fields.';
}
else
{
if(!empty($_FILES['avatar']['tmp_name']))
{
$image = $_FILES['avatar'];
$tmp = $imagem['tmp_name'];
$folder = '../uploads/avatars/';
$ext = substr($image['name'],-3);
$name = md5(time()).'.'.$ext;
$f['avatar'] = $name;
uploadImage($tmp, $name, '200', $folder);
}
$insertAdmin = $pdo->prepare("INSERT INTO admin (name, email, avatar, date_register) VALUES (:name, :email, :avatar, :date_register)");
$insertAdmin->bindValue(':name', $f['name']);
$insertAdmin->bindValue(':email', $f['email']);
$insertAdmin->bindValue(':avatar', $f['avatar']);
$insertAdmin->bindValue(':date_register', $f['date']);
}
}
Related
I am having a trouble to saving data into the database. My connection details and sql insert query everything is correct and image is also uploading to folder but I do not know why data along with image is not saving into an database when i hit upload button.Can anyone help me please?
My php code
<?php
include('server.php');
$userID = 1;
if(isset($_SESSION['username']))
{
$userName = $_SESSION['username'];
$queryID = "SELECT id from users WHERE username = '$userName'";
$resultID = $db->query($queryID);
$row=$resultID->fetch_assoc();
$userID = $row['id'];
}
if(isset($_POST['submit']))
{
$image = $_FILES['image']['name'];
$target = "images/".basename($image);
$eventName = $_POST['eventName'];
$eventDetail = $_POST['eventDetail'];
$eventDate = $_POST['eventDate'];
$eventTime = $_POST['eventTime'];
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES('$eventName','$eventDetail','$eventDate','$eventTime','$image','$userID')";
mysqli_query($db,$queryImage);
if(move_uploaded_file($_FILES['image']['tmp_name'],$target))
{
$msg = "Image uploaded successfully";
}
else
{
$msg = "There is problem";
}
}
?>
html
<form method="post" enctype="multipart/form-data">
<label for="eventName">Event Name:<label>
<input type="text" id="eventName" name="eventName" ><br><br>
<label for="eventDetail">Event Detail:<label>
<textarea id="eventDetail" name="eventDetail" ></textarea><br><br>
<label for="eventDate">Event Date:<label>
<input type="text" id="eventDate" name="eventDate" ><br><br>
<label for="eventTime">Event Time:<label>
<input type="text" id="eventTime" name="eventTime" ><br><br>
<input type="file" id="image" name="image"><br><br>
<button type="submit" id="submit" name="submit" >Submit</button>
</form>
Change this
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES ('$eventName','$eventDetail','$eventDate','$eventTime','$image','$userID')";
to
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES ($eventName,$eventDetail,$eventDate,$eventTime,$image,$userID)";
I have created a form with HTML/PHP/SQL where a user can either choose to submit their email into a database or else select a radio button to opt out of their email being submitted, alongside some other user data.
To achieve this, I have written an if/else statement, however my current code isn't working, and I can't quite work out the correct syntax that I should be using. If the user selects the radio-button, I would like "Email unavailable" to be inserted into the database, else the user-inputted email is inserted. All help appreciated!
Note, my code worked fine until I added the radio-button "no email" option.
HTML file:
<form id="newStaff" method="POST" action="staffportal.php" enctype="multipart/form-data">
<b><i class="fas fa-user-alt"></i> Full name:</b>
<input class="form-control" type="text" id="staffName" name="myStaffName" size="40" maxlength="50"/>
//THE RELEVANT CODE
<b><i class="fas fa-paper-plane"></i> Email:</b>
<div class="form-group row">
<div class="col-xs-4">
<input class="form-control" type="text" id="staffEmail" name="myStaffEmail" size="40"/>
<br>
<input class="form-check-input" type="radio" name="myStaffNoEmail" id="staffNoEmail" value="option1">
<label class="form-check-label" for="gridRadios1">
No available email
</label>
</div>
</div>
<hr>
<b>Job title(s):</b>
<input class="form-control" type="text" id="staffJob" name="myStaffJob" size="40" maxlength="60"/>
<b>Personal bio:</b>
<textarea class="form-control summernote" rows='6' cols='70' id="staffBio" name="myStaffBio" maxlength='1500'></textarea>
<b>Profile photo:</b>
<input type="file" class="custom-file-input" name="myStaffPhoto" id="staffPhoto">
<button name="newStaffBtn" id="newStaffButton" onclick="return confirm('Create new profile?');" type="submit" class="btn btn-primary">Create Profile></button>
</form>
PHP file:
if(isset($_POST["newStaffBtn"])) {
//Text inputs
$staffName = mysqli_real_escape_string($conn, $_POST["myStaffName"]);
//$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
$staffJob = mysqli_real_escape_string($conn, $_POST["myStaffJob"]);
$staffBio = mysqli_real_escape_string($conn, $_POST["myStaffBio"]);
$staffNoEmail = mysqli_real_escape_string($conn, $_POST["myStaffNoEmail"]);
//Staff email option
if (!empty($staffNoEmail)){
$staffEmail = "Email unavailable";
} else {
$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
}
//Image input
$file = $_FILES["myStaffPhoto"];
... profile photo code blah blah...
$insertquery ="INSERT INTO `staff` (staffID, staffName, staffEmail, staffRole, staffDesc, staffPic) VALUES (null, '$staffName', '$staffEmail', '$staffJob','$staffBio', '".$fileNameNew."')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
$msg = "<small>Profile uploaded!</small>";
$css_class = "alert-success";
}
If radio input is checked, it will send value with post, if it is not checked it will not send any value and it will not exist in your $_POST array.In your case, you should be checking if it is set.
if(isset($_POST["newStaffBtn"])) {
//Text inputs
$staffName = mysqli_real_escape_string($conn, $_POST["myStaffName"]);
//$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
$staffJob = mysqli_real_escape_string($conn, $_POST["myStaffJob"]);
$staffBio = mysqli_real_escape_string($conn, $_POST["myStaffBio"]);
//Staff email option
if (isset($_POST["myStaffNoEmail"])){
$staffEmail = mysqli_real_escape_string($conn, $_POST["myStaffEmail"]);
} else {
$staffEmail = "Email unavailable";
}
//Image input
$file = $_FILES["myStaffPhoto"];
... profile photo code blah blah...
$insertquery ="INSERT INTO `staff` (staffID, staffName, staffEmail, staffRole, staffDesc, staffPic) VALUES (null, '$staffName', '$staffEmail', '$staffJob','$staffBio', '".$fileNameNew."')";
$result = mysqli_query($conn, $insertquery) or die(mysqli_error($conn));
$msg = "<small>Profile uploaded!</small>";
$css_class = "alert-success";
}
I am trying to add records into a database. Each record has a corresponding image. The records are getting inserted into the database but it is not working for the image. I am getting this error "connected succesfully
Notice: Undefined variable: sql in C:\xampp\htdocs\Syokimaufc\addplayer.php on line 35
Error: Query was empty" How can i solve this?
HTML form
<p> id: <input type="text" name="playerid"/></p>
<p> Name: <input type="text" name="name"/></p>
<p> Age: <input type="text" name="age"/></p>
<p> Position: <input type="text" name="position"/></p>
<p> Nationality: <input type="text" name="nationality"/></p>
<p> Photo: <input type="file" name="image"/></p>
<input type="submit" value="submit"/>
<form/>
php script
<?php
require 'connection.php';
$id = filter_input(INPUT_POST, 'playerid');
$name = filter_input(INPUT_POST, 'name');
$age = filter_input(INPUT_POST, 'age');
$position = filter_input(INPUT_POST, 'position');
$nationality = filter_input(INPUT_POST, 'nationality');
$_id = mysql_real_escape_string( $id );
$_name = mysql_real_escape_string( $name );
$_age = mysql_real_escape_string( $age );
$_position = mysql_real_escape_string( $position );
$_nationality = mysql_real_escape_string( $nationality );
if (isset($_POST['submit']))
{
$imageName = mysql_real_escape_string($_FILES ["image"]["iname"]);
$imageData = mysql_real_escape(file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = mysql_real_escape_string($_FILES["image"]["iname"]);
if (substr($imageType,0,5) == "image")
{
$sql = "INSERT INTO players ( playerid, name, age, position, nationality, iname, image ) VALUES ( '$_id', '$_name', '$_age', '$_position', '$_nationality', '$imageName', '$imageData' )";
}
else
{
echo "only images are allowed";
}
}
if (!mysql_query($sql)){
die('Error: ' . mysql_error());
}
in your form try adding an attribute:
<form enctype="multipart/form-data">
......
..
</form>
Have you tried it with the name property in the submit ?, it seems that is not going to "if"
<input type="submit" name="submit" value="submit"/>
just check following steps:
In html file, a form with image upload should be set with enctype="multipart/form-data"
e.g. <form enctype="multipart/form-data>
In PHP script
$_FILES["image"]["iname"] is wrong.
$_FILES["image"]["name"] should be the right one.
I am new to this form and to php. I have got this code but always I got these errors.
Notice: Undefined index: id
Notice: Undefined index: name
Notice: Undefined index: remarcs
Notice: Undefined index: test_res
Notice: Undefined index: date
Notice: Undefined index: phone_num
Notice: Undefined index: file
I have this html code of the form:
<form action="/clinic form/insert/insert.php" id="Form2" method="POST" enctype="multipart/form-data" class="c">
<div align="center">
<?php echo "Insert information about a new Patient "?>
<table class="imagetable" border="1" cellspacing="3" align="center">
<th>Personal Informations</center></th>
<th>Test Results</th>
<tr><td>Name<br>
<input type="text" class="large-fld" name="name" placeholder="Patient Name"></td>
<td>Remarcs:<br>
<textarea type="text" cols="40" rows="5" class="large-fld" name="remarcs" placeholder="Remarcs"></textarea></td>
<tr><td>Address<br>
<input type="text" class="large-fld" name="address" placeholder="Address"/>
</td>
<td>Test<br> <textarea type="text" cols="40" rows="5" class="large-fld" name="test_res" placeholder="Test Result"></textarea></td></tr>
</td>
</tr>
<tr><td>Phone Number<br>
<input type="text" class="large-fld" name="phone_num" placeholder="Phone Number"/>
</td>
<th>Files</th>
</tr>
<td>Date<br>
<input type="text" class="large-fld" name="date" id="date" placeholder="0000-00-00"/></td>
<td>Echo Files:<br>
<input type="file" name="file" id="file"/><br></td>
</tr></th></table>
<div class="row" align="center">
<input type="image" name="login" value="Login" src="images/insert.png" width="widthInPixels" height="heightInPixels" onMouseOver="this.src='images/insertRoll.png';" onMouseOut="this.src='images/insert.png';"> </td></tr>
</table></div>
</form>
And this html code that I found it online:
<?php
require_once ('../include/global.php');
$name = '';
$remarcs = '';
$address = '';
$test_res = '';
$date = '';
$phone = '';
$new_path = '';
if(isset($_POST['submit'])){
if (isset ($_POST['name'])) {
$name = $_POST['name'];
}
if (isset ($_POST['remarcs'])) {
$remarcs = $_POST['remarcs'];
}
if (isset ($_POST['test_res'])) {
$test_res = $_POST['test_res'];
}
if (isset ($_POST['address'])) {
$address = $_POST['address'];
}
if (isset ($_POST['date'])) {
$date = $_POST['date'];
$desiredFormat = date('d/m/Y', strtotime($date));
}
if (isset ($_POST['phone_num'])) {
$phone = $_POST['phone_num'];
}
$path = "../uploads/".$_FILES['file']['name'];
//$path2 = "../uploads/".$_FILES['echo_photo']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
//if(move_uploaded_file($_FILES["file"]["tmp_name"], $path.'_'.time().date().$_FILES['file']['name'])){
move_uploaded_file($_FILES["file"]["tmp_name"], $path.'_'.time().date().'.'.$ext);
$new_path = "./uploads/".$path.'_'.time().date().'.'.$ext;
$sql="INSERT INTO patients (name, echo_files, remarcs, test_res, date, address, phone_num)
VALUES
('$name', '$new_path', '$remarcs', '$test_res', '$desiredFormat', '$address', '$phone')";
$result=mysqli_query($con,$sql) or die('Unable to execute query. '. mysqli_error($con));
if($result){
/*echo $name."<p>\n</p>";
echo $remarcs."<p>\n</p>";
echo $test_res."<p>\n</p>";
echo $address."<p>\n</p>";
echo $phone."<p>\n</p>";*/
header("location:insert_done.php");
} else {
header("location:insert_false.php");}
}
?>
Can someone tells me what is wrong with this code ?
Its because, you are trying to get $_POST ed variables before form submit.
Try this:
if (isset($_POST['YOUR_SUBMIT_BUTTON']) {
$remarcs = $_POST['remarcs'];
// Your other variables which are posted.
// Place all your code you need to execute after form submit.
}
Another thing is that you are using date as one of your field.
It is a reserved keyword in MySQL.
You should enclose it with backtick (`) to avoid conflict.
Corrected Code:
<?php
require_once ('../include/global.php');
$name = '';
$remarcs = '';
$address = '';
$test_res = '';
$date = '';
$phone = '';
$new_path = '';
if (isset($_POST['submit'])){
$name = isset($_POST['name']) ? $_POST['name'] : '';
$remarcs = isset($_POST['remarcs']) ? $_POST['remarcs'] : '';
$test_res = isset($_POST['test_res']) ? $_POST['test_res'] : '';
$address = isset($_POST['address']) ? $_POST['address'] : '';
$phone_num = isset($_POST['phone_num']) ? $_POST['phone_num'] : '';
$date = isset($_POST['date']) ? $_POST['date'] : date('d/m/Y', strtotime($date));
$path = "../uploads/".$_FILES['file']['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
//if(move_uploaded_file($_FILES["file"]["tmp_name"], $path.'_'.time().date().$_FILES['file']['name'])){
move_uploaded_file($_FILES["file"]["tmp_name"], $path.'_'.time().date().'.'.$ext);
$new_path = "./uploads/".$path.'_'.time().date().'.'.$ext;
$sql="INSERT INTO patients (name, echo_files, remarcs, test_res, `date`, address, phone_num)
VALUES
('$name', '$new_path', '$remarcs', '$test_res', '$desiredFormat', '$address', '$phone')";
$result=mysqli_query($con,$sql) or die('Unable to execute query. '. mysqli_error($con));
if($result){
header("location:insert_done.php");
}
else {
header("location:insert_false.php");
}
}
?>
I'm working on an HTML form, which is connected to MySQL database. Database is updating with new data every time, when I reload the page and also when a failed submit occur.
This is my code, Anyone please help me to add session to this page and please give me a solution
<body>
<?php
// define variables and set to empty values
$email_id = $first_name = $last_name = $district = $city = $address = $mobile_no = $password = "";
$email_idErr = $first_nameErr = $last_nameErr = $districtErr = $cityErr = $addressErr = $mobile_noErr = $passwordErr = "";
?>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
//First name validation
if(empty($_POST["first_name"]))
{$first_nameErr="First name is required";}
else
{$first_name = test_input($_POST["first_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$first_name))
{$first_nameErr="Only letters and white spaces allowed";}
}
//Second name validation
if(empty($_POST["last_name"]))
{$last_nameErr="Last name is required";}
else
{$last_name = test_input($_POST["last_name"]);
//checking name formats
if(!preg_match("/^[a-zA-Z]*$/",$last_name))
{$last_nameErr="Only letters and white spaces allowed";}
}
//E-mail validation
if(empty($_POST["email_id"]))
{$email_idErr="E-mail id is required";}
else
{$email_id = test_input($_POST["email_id"]);
//checking email format
if(!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/",$email_id))
{$email_idErr="Invalid email format";}
}
//District is required
if(empty($_POST["district"]))
{ $districtErr="District is required";}
else
{ $district = test_input($_POST["district"]);
if(!preg_match("/^[a-zA-Z]*$/",$district))
{$districtErr="Only letters and white spaces allowed";}
}
$city = test_input($_POST["city"]);
$address = test_input($_POST["address"]);
//Mobile number validation
if(empty($_POST["mobile_no"]))
{$mobile_noErr="Mobile number is required";}
else
{$mobile_no = test_input($_POST["mobile_no"]);
if(!preg_match("/^[0-9]*$/",$mobile_no))
{$mobile_noErr="Invalid Mobile number";}
}
//Password validation
if(empty($_POST["password"]))
{$passwordErr="Password is required";}
else
{ $password = test_input($_POST["password"]);
}
}
function test_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<?php
$con=mysqli_connect("localhost","root","","ashlyn");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{echo "Connection Established";}
$sql="INSERT INTO user_details (email_id, first_name, last_name, district, city, address, mobile_no, password)
VALUES ('$email_id', '$first_name', '$last_name', '$district', '$city', '$address', '$mobile_no', '$password')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "You are successfully registered..";
mysqli_close($con);
?>
<section class="container">
<div class="login">
<h1>User Login Page</h1>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);>">
<p><input type="text" name="first_name" value="" placeholder="First Name"><span class="error">* <?php echo $first_nameErr;?></span></p>
<p><input type="text" name="last_name" value="" placeholder="Last Name"> <span class="error">* <?php echo $last_nameErr;?></span>
</p>
<p><input type="text" name="email_id" value="" placeholder="Email"><span class="error">* <?php echo $email_idErr;?></span>
</p>
<p><input type="text" name="district" value="" placeholder="District"><span class="error">* <?php echo $districtErr;?></span></p>
<p><input type="text" name="city" value="" placeholder="City">
</p>
<p><input type="text" name="address" value="" placeholder="Address">
</p>
<p><input type="text" name="mobile_no" value="" placeholder="Mobile Number"> <span class="error">* <?php echo $mobile_noErr;?></span>
</p>
<p><input type="password" name="password" value="" placeholder="Password"> <span class="error">* <?php echo $passwordErr;?></span>
</p>
<p class="submit"><input type="submit" name="submit" value="Submit"></p>
</form>
what you need is
<?php session_start();
on the first line bevor any output
https://stackoverflow.com/a/8084900/1792420