undefined values as error - php

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");
}
}
?>

Related

How to solved this kind of undefined variable problem in PHP [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 4 years ago.
I had written the code in below but i saw Undefined variable problem:
In this code, there is 2 file. One file is for login and another file is for the classes. its about create and login page. Registration is not a problem its work correctly but when i want to do in existing login i face the problem. they told Undefined variable problem.
login.php(file name)
<?php include "inc/header.php"; ?>
<?php
$cmr = new Customer();
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['login'])) {
$custLogin = $cmr->customerLogin($_POST);
}
?>
<div class="main">
<div class="content">
<div class="login_panel">
<?php
if (isset($custLogin)) {
echo $custLogin;
}
?>
<h3>Existing Customers</h3>
<p>Sign in with the form below.</p>
<form action="" method="post">
<input name="email" placeholder="Enter your email" type="text"/>
<input name="pass" placeholder="Enter your password" type="password"/>
<p class="note">If you forgot your passoword just enter your email and click here</p>
<div class="buttons"><div><button class="grey" name="login">Sign In</button></div></div>
</div>
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['register'])) {
$customerReg = $cmr->customerRegistration($_POST);
}
?>
<div class="register_account">
<?php
if (isset($customerReg)) {
echo $customerReg;
}
?>
<h3>Register New Account</h3>
<form action="" method="post">
<table>
<tbody>
<tr>
<td>
<div>
<input type="text" name="name" placeholder="Name"/>
</div>
<div>
<input type="text" name="city" placeholder="City"/>
</div>
<div>
<input type="text" name="zip" placeholder="Zip-Code"/>
</div>
<div>
<input type="text" name="email" placeholder="Email"/>
</div>
</td>
<td>
<div>
<input type="text" name="address" placeholder="Address"/>
</div>
<div>
<input type="text" name="country" placeholder="Country"/>
</div>
<div>
<input type="text" name="phone" placeholder="Phone"/>
</div>
<div>
<input type="text" name="pass" placeholder="Password"/>
</div>
</td>
</tr>
</tbody></table>
<div class="search"><div><button class="grey" name="register">Create Account</button></div></div>
<p class="terms">By clicking 'Create Account' you agree to the Terms & Conditions.</p>
<div class="clear"></div>
</form>
</div>
<div class="clear"></div>
</div>
</div>
<?php include "inc/footer.php"; ?>
//////////////////////////////////////////////////
Customer.php (file name)
/////////////////////////////////////////////////
<?php
$filepath = realpath(dirname(__FILE__));
include_once ($filepath."/../lib/Database.php");
include_once ($filepath."/../helpers/Format.php");
?>
<?php
class Customer{
private $db;
private $fm;
public function __construct(){
$this->db = new Database();
$this->fm = new Format();
}
public function customerRegistration($data){
$name = $this->fm->validation($data['name']);
$address = $this->fm->validation($data['address']);
$city = $this->fm->validation($data['city']);
$country = $this->fm->validation($data['country']);
$zip = $this->fm->validation($data['zip']);
$phone = $this->fm->validation($data['phone']);
$email = $this->fm->validation($data['email']);
$pass = $this->fm->validation($data['pass']);
$name = mysqli_real_escape_string($this->db->link, $data['name']);
$address = mysqli_real_escape_string($this->db->link, $data['address']);
$city = mysqli_real_escape_string($this->db->link, $data['city']);
$country = mysqli_real_escape_string($this->db->link, $data['country']);
$zip = mysqli_real_escape_string($this->db->link, $data['zip']);
$phone = mysqli_real_escape_string($this->db->link, $data['phone']);
$email = mysqli_real_escape_string($this->db->link, $data['email']);
$pass = mysqli_real_escape_string($this->db->link, md5($data['pass']));
if ($name == "" || $address == "" || $city == "" || $country == "" || $zip == "" || $phone == "" || $email == "" || $pass == ""){
$msg = "<span class='error'>Field must not be empty !</span>";
return $msg;
}
$mailquery = "select * from tbl_customer where email='$email' limit 1";
$mailchk = $this->db->select($mailquery);
if ($mailchk != false) {
$msg = "<span class='error'>Email already exist!</span>";
return $msg;
} else {
$query = "insert into tbl_customer(name,address,city,country,zip,phone,email,pass)
values ('$name','$address','$city','$country','$zip','$phone','$email','$pass')";
$userinsert = $this->db->insert($query);
if ($userinsert) {
$msg = "<span class='success'>Customer Data Added Successfully !</span>";
return $msg;
} else {
$msg = "<span class='error'>Customer Data not added !</span>";
return $msg;
}
}
}
public function customerLogin($date){
$email = $this->fm->validation($data['email']);
$pass = $this->fm->validation($data['pass']);
$email = mysqli_real_escape_string($this->db->link, $data['email']);
$pass = mysqli_real_escape_string($this->db->link, md5($data['pass']));
if (empty($email) || empty($pass)) {
$msg = "<span class='error'>Field must not be empty !</span>";
return $msg;
}
$query = "select * from tbl_customer where email = '$email' AND pass = '$pass'";
$result = $this->db->select($query);
if ($result != false) {
$value = $result->fetch_assoc();
Session::set("cuslogin",true);
Session::set("cmrId",$value['id']);
Session::set("cmrName",$value['name']);
header("Location:order.php");
} else {
$msg = "<span class='error'>Email or Password doesnot match!</span>";
return $msg;
}
}
}
?>
public function customerLogin($date){
$email = $this->fm->validation($data['email']);
$pass = $this->fm->validation($data['pass']);
$email = mysqli_real_escape_string($this->db->link, $data['email']);
$pass = mysqli_real_escape_string($this->db->link, md5($data['pass']));
these 4 line i faced a problem and the problem is below:
Notice: Undefined variable: data in D:\xampp\htdocs\shop\classes\Customer.php on line 60
Notice: Undefined variable: data in D:\xampp\htdocs\shop\classes\Customer.php on line 61
Notice: Undefined variable: data in D:\xampp\htdocs\shop\classes\Customer.php on line 63
Notice: Undefined variable: data in D:\xampp\htdocs\shop\classes\Customer.php on line 64
on row 59 - type-o
change this
public function customerLogin($date){
to
public function customerLogin($data){

Insert 1 row but shows 3 rows

I just want to insert one row with my form but MySQL is showing 3 rows, one of them is mine and two of them is just null.
Here is my code.
Form
<form method="post" id="contactform" action="iletisim-basarili.php">
<input type="text" name="isim" placeholder="İsim" class="formcontact"><br>
<input type="text" name="soyisim" placeholder="Soyisim" class="formcontact"><br>
<input type="text" name="telefon" placeholder="Telefon Numarası" class="formcontact"><br>
<input type="text" name="eposta" id="eposta" placeholder="E-Posta Adresi" class="formcontact"><br>
<input type="text" name="konu" id="konu" placeholder="Konu" class="formcontact"><br>
<textarea type="text" name="mesaj" id="mesaj" rows="8" placeholder="Mesajınız" class="form--contact--textarea"></textarea><br>
<div class="validred"></div><br>
<input type="submit" name="submit" class="button-form" value="Formu Gönder" />
</form>
PHP
<?php
require ('config.php');
$isim = trim( $_POST['isim']);
$soyisim = trim( $_POST['soyisim']);
$telefon = trim( $_POST['telefon']);
$eposta = trim( $_POST['eposta']);
$konu = trim( $_POST['konu']);
$mesaj = trim( $_POST['mesaj']);
$kaydet = mysql_query( "INSERT INTO contact SET
isim = '$isim',
soyisim = '$soyisim',
telefon = '$telefon',
eposta = '$eposta',
konu = '$konu',
mesaj = '$mesaj'
");
if( mysql_affected_rows()) {
echo "<h3 class='green'>destek talebini kaydettik.</h3><br><h4 class='text'>en kısa sürede"." <b>$destekmail</b>"." üzerinden seninle iletişime geçeceğimizden hiç şüphen olmasın.</h4>";
}
?>
This is function check wather submit button press or its self posted page.So you need to check for submit button.
<?php
require ('config.php');
//Check before form is submitted.
if(isset($_POST['submit'])){
$isim = trim( $_POST['isim']);
$soyisim = trim( $_POST['soyisim']);
$telefon = trim( $_POST['telefon']);
$eposta = trim( $_POST['eposta']);
$konu = trim( $_POST['konu']);
$mesaj = trim( $_POST['mesaj']);
$kaydet = mysql_query( "INSERT INTO contact SET
isim = '$isim',
soyisim = '$soyisim',
telefon = '$telefon',
eposta = '$eposta',
konu = '$konu',
mesaj = '$mesaj'
");
if( mysql_affected_rows()) {
echo "<h3 class='green'>destek talebini kaydettik.</h3><br><h4 class='text'>en kısa sürede"." <b>$destekmail</b>"." üzerinden seninle iletişime geçeceğimizden hiç şüphen olmasın.</h4>";
}
}
?>

Adding an image into a database using a html form

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.

Uploading blob files/images into Mysql

I had this php code that take values from an html form (name, file, photo, address,.....), and try to insert or update them in sql database.
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name=""; // Database name
$tbl_name=""; // Table name
session_start();
$con=mysqli_connect("localhost","","","");
$id=$_REQUEST['id'];
//Variable intilisation
$name = '';
$remarcs = '';
$address = '';
$test_res = '';
$date = '';
$phone = '';
$new_path = '';
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'];
}
if (isset ($_POST['phone_num'])) {
$phone = $_POST['phone_num'];
}
if(!empty($_FILES)){ //Check file is uploaded or not
$check = getimagesize($_FILES["file"]["tmp_name"]);
if($check !== false) {
$path = "../uploads/".$_FILES['file']['tmp_name'];
move_uploaded_file($file, $path);
$new_path = $path;
echo "Uploaded";
}
if($check == false){
echo "Not uploaded";
}
}
if(move_uploaded_file($_FILES['file']['tmp_name'], $path)){
$sql=" update patients set values
name = '$name',
echo_photo = 'NULL',
echo_file = '$new_path',
remarcs = '$remarcs',
test_res = '$test_res',
date = '$date',
address = '$address',
phone_num = '$phone'
WHERE id = ".$id;
$result=mysqli_query($con,$sql) or die('Unable to execute query. '. mysqli_error($con));
header("location:update_done.php");
}else{
header("location:update_false.php");
}
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>";
}
mysqli_close($con);
?>
The problem is that I am getting the following errors when only I upload a file shown in the image below:
And when I dont upload a file, I got an error: Please select a file.
Any help ? Thank you.
This is the html form:
<form action="update.php" id="Form2" method="POST" enctype="multipart/form-data" class="c">
<div align="center">
<?php echo "Updating information about Patient ".$row["name"]; ?>
<table class="imagetable" border="1" cellspacing="3" align="center">
<th>Personal Informations</th>
<th>Test Results</th>
<tr><td>Name<br>
<input type="text" class="large-fld" name="name" placeholder="Patient Name" value="<?php echo $row['name'];?>"/></td>
<td>Remarcs:<br>
<textarea type="text" cols="40" rows="5" class="large-fld" name="remarcs" placeholder="Remarcs"><?php echo $row['remarcs'];?></textarea></td>
<tr><td>Address<br>
<input type="text" class="large-fld" name="address" placeholder="Address" value="<?php echo $row['address'];?>"/>
</td>
<td>Test<br> <textarea type="text" cols="40" rows="5" class="large-fld" name="test_res" placeholder="Test Result"><?php echo $row['test_res'];?></textarea></td></tr>
</td>
</tr>
<tr><td>Phone Number<br>
<input type="text" class="large-fld" name="phone_num" placeholder="Phone Number" value="<?php echo $row['phone_num'];?>"/>
</td>
<th>Files</th>
</tr>
<td>Scanned Echo Photo<br>
<input type="file" class="" name="echo_photo" id="echo_photo" placeholder="Add echo photo" value="<?php echo $row['echo_photo'];?>"/></td>
<td>Echo Files:<br>
<input type="file" name="file" id="file" value="<?php echo $row['echo_files'];?>"/><br></td>
</tr></th></table>
<div class="row" align="center">
<input type="submit" name="submit" id="btnUploadId" class="large-btn" value="Update" onClick="btnOnClickUpload()">
<input type="hidden" id="courseIdHidden" value="<?php echo $idd; ?>" /></td></tr>
</table></div>
</form>
Try to initialise the variable. I have added the entire code. You don't need to get $_POST['file'].
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="root"; // Mysql password
$db_name="clinic"; // Database name
$tbl_name="patients"; // Table name
session_start();
$con=mysqli_connect("localhost","root","root","clinic");
$id=$_REQUEST['id'];
$name = '';
$remarcs = '';
$address = '';
$test_res = '';
$date = '';
$phone = '';
$new_path = '';
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'];
}
if (isset ($_POST['phone_num'])) {
$phone = $_POST['phone_num'];
}
if(isset($_FILES['file'])){ //Check file is uploaded or not
$path = "../uploads/".$_FILES['file']['name'];
if(move_uploaded_file($_FILES["file"]["tmp_name"], $path)){
$new_path = $path;
$sql=" update patients set
name = '$name',
echo_photo = 'NULL',
echo_file = '$new_path',
remarcs = '$remarcs',
test_res = '$test_res',
date = '$date',
address = '$address',
phone_num = '$phone'
WHERE id = ".$id;
$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>";
}
echo "Uploaded";
} else {
echo "Not uploaded";
}
}
mysqli_close($con);
?>
This is the final working code:
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'];
}
if (isset ($_POST['phone_num'])) {
$phone = $_POST['phone_num'];
}
if(isset($_FILES['file'])){ //Check file is uploaded or not
$path = "../uploads/".$_FILES['file']['name'];
//$path2 = "../uploads/".$_FILES['echo_photo']['name'];
if(move_uploaded_file($_FILES["file"]["tmp_name"], $path)){
$new_path = $path;
$sql="UPDATE $tbl_name SET
name = '$name',
echo_files = '$new_path',
remarcs = '$remarcs',
test_res = '$test_res',
date = '$date',
address = '$address',
phone_num = '$phone'
WHERE id = '$id'";
$result=mysqli_query($con,$sql) or die('Unable to execute query. '. mysqli_error($con));

Having two notices of undefined index

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']);
}
}

Categories