Uploading blob files/images into Mysql - php

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));

Related

php string validation not working

So I have the following code:
<body>
<?php
$firstname = $lastname = $phone = $phone = $email = $date = $code = "";
$firstnameerr = $lastnameerr = $phoneerr = $emailerr = $dateerr = $codeerr = "";
$check = 0;
$str = "abcdefghijklmnopqrstuvwxyz";
$rand1 = $str[rand(0, strlen($str) - 1)];
$rand2 = $str[rand(0, strlen($str) - 1)];
$rand3 = $str[rand(0, strlen($str) - 1)];
$rand4 = $str[rand(0, strlen($str) - 1)];
$rand5 = $str[rand(0, strlen($str) - 1)];
$final = $rand1 . $rand2 . $rand3 . $rand4 . $rand5;
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["ffirstname"])){
$firstnameerr = "First Name is empty!";
$check = 1;
} else {
$firstname = testInput($_POST['ffirstname']);
$check = 0;
if (!preg_match("/^[a-zA-Z]*$/",$firstname)){
$firstnameerr = "This is not a valid name!";
$check = 1;
}
}
if (empty($_POST["flastname"])){
$lastnameerr = "Last Name is empty!";
$check = 1;
} else {
$lastname = testInput($_POST['flastname']);
$cheek = 0;
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)){
$lastnameerr = "This is not a valid name";
$check = 1;
}
}
if (empty($_POST["fphone"])){
$phoneerr = "Phone field is empty!";
$check = 1;
}else {
$phone = testInput($_POST['fphone']);
if(!is_numeric($phone)){
$phoneerr = "Phone number is not a number";
$check = 1;
}
}
if (empty($_POST["femail"])){
$emailerr = "E-mail field is empty!";
} else {
$email = testInput($_POST['femail']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailerr = "E-mail is not valid";
$check = 1;
}
}
if (empty($_POST["fdate"])){
$dateerr = "No date selected!";
$check = 1;
} else {
$date = testInput($_POST['fdate']);
}
if (empty($_POST["fcode"])){
$codeerr = "There is no code!";
$check = 1;
} else {
$code = $_POST["fcode"];
if ($code !== $final){
$codeerr = "The code is wrong";
$check = 1;
}
}
if ($check == 0) {
$host = "localhost";
$user = "root";
$pass = "";
$db = "myfirstdb";
$connect = new mysqli($host,$user,$pass,$db);
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
} else {
echo "Connected successfully!";
}
$sql = "INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES ('$firstname', '$lastname', '$phone', '$email', '$date')";
if ($connect->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
}
}
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="header">
<img src="http://stupidname.org/files/gfx/design/random%20logos/RandomLogo1.png" alt="logo" height="250px" width="250px">
<div id="top"><h1 id="first">Welcome to my website</h1></div>
</div>
<div id="section">
<div id="nav">
<ul>
<li>Home</li>
<li>About</li>
<li>Project</li>
<li>Contact</li>
</ul>
</div>
<div id="article">
<h3 style="text-align: center"><b>Please confirm the form below:</b></h3>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p class="namer">First Name</p><br>
<input type="text" name="ffirstname" id="ffirstnameid"><span class="error"><?php echo $firstnameerr; ?></span><br>
<p class="namer">Last Name</p><br>
<input type="text" name="flastname" id="flastnameid"><span class="error"><?php echo $lastnameerr; ?></span><br>
<p class="namer">Phone Number</p><br>
<input type="text" name="fphone" id="fphoneid"><span class="error"><?php echo $phoneerr; ?></span><br>
<p class="namer">E-mail</p><br>
<input type="text" name="femail" id="femailid"><span class="error"><?php echo $emailerr; ?></span><br>
<p class="namer">Date</p><br>
<input type="text" name="fdate" id="fdateid"><span class="error"><?php echo $dateerr; ?></span><br>
<p class="namer">Enter the Captcha code!</p><br>
<h1><?php echo $final?></h1><br>
<input type="text" name="fcode" id="fcodeid"><span class="error"><?php echo $codeerr; ?></span><br>
<input type="submit" name="fsubmit" value="Submit">
</form>
</div>
</div>
My problem is with the code a.k.a in the if that uses $code and $final to check wheather it's a human or not. Now whenever i write the exact same thing as in the $final variable the program thinks it's not the same so i get the $codeerr. Can someone please help me fix it?
Ok, I added little changes to your code, and I think it should work now.
<?php
session_start();
?>
<body>
<?php
function generateCode() {
$str = "abcdefghijklmnopqrstuvwxyz";
$rand1 = $str[rand(0, strlen($str) - 1)];
$rand2 = $str[rand(0, strlen($str) - 1)];
$rand3 = $str[rand(0, strlen($str) - 1)];
$rand4 = $str[rand(0, strlen($str) - 1)];
$rand5 = $str[rand(0, strlen($str) - 1)];
return $rand1 . $rand2 . $rand3 . $rand4 . $rand5;
}
$firstname = $lastname = $phone = $phone = $email = $date = $code = "";
$firstnameerr = $lastnameerr = $phoneerr = $emailerr = $dateerr = $codeerr = "";
$check = 0;
if(!isset($_SESSION['final'])) {
$_SESSION['final'] = generateCode();
}
if ($_SERVER["REQUEST_METHOD"] == "POST"){
if (empty($_POST["ffirstname"])){
$firstnameerr = "First Name is empty!";
$check = 1;
} else {
$firstname = testInput($_POST['ffirstname']);
$check = 0;
if (!preg_match("/^[a-zA-Z]*$/",$firstname)){
$firstnameerr = "This is not a valid name!";
$check = 1;
}
}
if (empty($_POST["flastname"])){
$lastnameerr = "Last Name is empty!";
$check = 1;
} else {
$lastname = testInput($_POST['flastname']);
$cheek = 0;
if (!preg_match("/^[a-zA-Z ]*$/",$lastname)){
$lastnameerr = "This is not a valid name";
$check = 1;
}
}
if (empty($_POST["fphone"])){
$phoneerr = "Phone field is empty!";
$check = 1;
}else {
$phone = testInput($_POST['fphone']);
if(!is_numeric($phone)){
$phoneerr = "Phone number is not a number";
$check = 1;
}
}
if (empty($_POST["femail"])){
$emailerr = "E-mail field is empty!";
} else {
$email = testInput($_POST['femail']);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailerr = "E-mail is not valid";
$check = 1;
}
}
if (empty($_POST["fdate"])){
$dateerr = "No date selected!";
$check = 1;
} else {
$date = testInput($_POST['fdate']);
}
if (empty($_POST["fcode"])){
$codeerr = "There is no code!";
$check = 1;
} else {
$code = $_POST["fcode"];
if ($code !== $_SESSION['final']){
$codeerr = "The code is wrong";
$check = 1;
}
}
if ($check == 0) {
$host = "localhost";
$user = "root";
$pass = "";
$db = "myfirstdb";
$connect = new mysqli($host,$user,$pass,$db);
if ($connect->connect_error){
die("Connection failed: " . $connect->connect_error);
} else {
echo "Connected successfully!";
}
$sql = "INSERT INTO table1 (firstname , lastname , phone , email , date) VALUES ('$firstname', '$lastname', '$phone', '$email', '$date')";
if ($connect->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $connect->error;
}
$connect->close();
}
}
if($check == 1) {
$_SESSION['final'] = generateCode();
}
function testInput($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="header">
<img src="http://stupidname.org/files/gfx/design/random%20logos/RandomLogo1.png" alt="logo" height="250px" width="250px">
<div id="top"><h1 id="first">Welcome to my website</h1></div>
</div>
<div id="section">
<div id="nav">
<ul>
<li>Home</li>
<li>About</li>
<li>Project</li>
<li>Contact</li>
</ul>
</div>
<div id="article">
<h3 style="text-align: center"><b>Please confirm the form below:</b></h3>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p class="namer">First Name</p><br>
<input type="text" name="ffirstname" id="ffirstnameid"><span class="error"><?php echo $firstnameerr; ?></span><br>
<p class="namer">Last Name</p><br>
<input type="text" name="flastname" id="flastnameid"><span class="error"><?php echo $lastnameerr; ?></span><br>
<p class="namer">Phone Number</p><br>
<input type="text" name="fphone" id="fphoneid"><span class="error"><?php echo $phoneerr; ?></span><br>
<p class="namer">E-mail</p><br>
<input type="text" name="femail" id="femailid"><span class="error"><?php echo $emailerr; ?></span><br>
<p class="namer">Date</p><br>
<input type="text" name="fdate" id="fdateid"><span class="error"><?php echo $dateerr; ?></span><br>
<p class="namer">Enter the Captcha code!</p><br>
<h1><?php echo $_SESSION['final']?></h1><br>
<input type="text" name="fcode" id="fcodeid"><span class="error"><?php echo $codeerr; ?></span><br>
<input type="submit" name="fsubmit" value="Submit">
</form>
</div>
</div>
You must save $final code in $_SESSION for example, because after submit of the form the code for generating $final will get executed and $final will get new value different from the rendered code before submit.

using multiple html forms to update mysql data using php

My code is given below (didn't include any html, no error/warning/notice). The program executes fine. The only problem I have is when I try to change the member_id and date fields in database- it doesn't work! As you can see I have used separate names for same fields mmid (used in the form) for member_id and dd (used in the form) for today. So, when user enters a different value it is assigned to mmid and dd while keeping the original values to member_id and dd allowing me to properly execute the update query. All other fields update is done as expected. None of the fields in the db is primary/unique/index. Could you please help me find where the problem is?
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
// define variables and set to empty values
$memberErr = $employeeErr = $dateErr = $blankfieldErr ="";
$mmid = $dd = $member_id = $employee_id = $paid_installment = $savings_deposit = $late_fee = $today = $dayx = $monthx = $yearx = "";
if (isset($_POST['SubmitFirst']))
{
if (empty($_POST["member_id"])) {
$memberErr = "আপনি সদস্যর আইডি দিতে ভুলে গেছেন";
} else {
$member_id = test_input($_POST["member_id"]);
}
if(!empty($_POST["dayx"]))
{
$dayx = test_input($_POST["dayx"]);
}
if(!empty($_POST["monthx"]))
{
$monthx = test_input($_POST["monthx"]);
}
if(!empty($_POST["yearx"])) // if all of them are selected
{
$yearx = test_input($_POST["yearx"]);
}
if(!empty($_POST["dayx"]) and !empty($_POST["monthx"]) and !empty($_POST["yearx"])){
$today= $yearx. "-" . $monthx. "-" . $dayx; }
else { $dateErr = "আপনি দিন / মাস / বছর লিখতে ভুলে গেছেন"; }
}
if (isset($_POST['Submit']))
{
echo $mmid;
echo " ";
echo $dd;
if (empty($_POST["mmid"])) {
$memberErr = "আপনি সদস্যর আইডি দিতে ভুলে গেছেন";
} else {
$mmid = test_input($_POST["mmid"]);
}
if (empty($_POST["dd"])) {
$dateErr = "আপনি সদস্যর আইডি দিতে ভুলে গেছেন";
} else {
$dd = test_input($_POST["dd"]);
}
if (empty($_POST["employee_id"])) {
$employeeErr = "আপনি কর্মীর আইডি দিতে ভুলে গেছেন";
} else {
$employee_id = test_input($_POST["employee_id"]);
}
if (empty($_POST["paid_installment"]) and empty($_POST["savings_deposit"]) and empty($_POST["late_fee"])) {
$blankfieldErr = "আপনি installment/savings/late_fee দিতে ভুলে গেছেন";
} else {
$paid_installment = test_input($_POST["paid_installment"]);
$savings_deposit = test_input($_POST["savings_deposit"]);
$late_fee = test_input($_POST["late_fee"]);
}
$servername = "localhost";
$username = "xxxxx";
$password = "yyyyy";
$dbname = "zzzzz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to UPDATE a record
$sql1 = "UPDATE daily_collection set date='$dd', member_id='$mmid', employee_id='$employee_id', paid_installment='$paid_installment', savings_deposit='$savings_deposit', late_fee='$late_fee' where member_id='$member_id' and date='$today'";
if ($result1=mysqli_query($conn,$sql1)) {
echo "<h2>". "সাবাস আপনি ঠিকভাবে তথ্য রেকর্ড করেছেন!". "</h2>";
} else {
echo "<h2>"."প্রোগ্রামে কিছু একটা সমস্যা হয়েছে, সুদিন স্যার-এর সাথে যোগাযোগ করুন ". "</h2>";
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
সদস্যর আইডি <input type="text" name="member_id" value="<?php echo $member_id;?>" size="50">
<span class="error"> <?php echo $memberErr;?></span>
<br><br>
তারিখ দিন <input type="text" name="dayx" value="<?php echo $dayx;?>" size="10"> মাস <input type="text" name="monthx" value="<?php echo $monthx;?>" size="10"> বছর <input type="text" name="yearx" value="<?php echo $yearx;?>" size="10">
<span class="error"> <?php echo $dateErr;?></span>
<br><br>
<center><input type="submit" name="SubmitFirst" value="SubmitFirst"></center><br>
</form>
<?php
if(isset($_POST['SubmitFirst']) and $member_id!="" and $today!="")
{
$servername = "localhost";
$username = "xxxxx";
$password = "yyyyy";
$dbname = "zzzzz";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql="select * from daily_collection where member_id='$member_id' and date='$today'";
if ($result=mysqli_query($conn,$sql))
{
while ($row=mysqli_fetch_row($result))
{
$dd=$row["0"];
$mmid=$row["1"];
$employee_id=$row["2"];
$paid_installment=$row[3];
$savings_deposit=$row[4];
$late_fee=$row[5];
}
echo $member_id;
echo " ";
echo $today;
}
else { echo "no such entry found";}
?>
<center><h2>দৈনিক কালেকশন এন্ট্রি ফর্ম</h2></center>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
সদস্যর আইডি <input type="text" name="mmid" value="<?php echo $mmid;?>" size="50">
<span class="error"> <?php echo $memberErr;?></span>
<br><br>
কর্মীর আইডি <input type="text" name="employee_id" value="<?php echo $employee_id;?>" size="50">
<span class="error"> <?php echo $employeeErr;?></span>
<br><br>
কিস্তির টাকা <input type="text" name="paid_installment" value="<?php echo $paid_installment;?>" size="50">
<br><br>
সঞ্চয় <input type="text" name="savings_deposit" value="<?php echo $savings_deposit;?>" size="50">
<br><br>
লেট ফী <input type="text" name="late_fee" value="<?php echo $late_fee;?>" size="50">
<span class="error"> <?php echo $blankfieldErr;?></span>
<br><br>
তারিখ <input type="text" name="dd" value="<?php echo $dd;?>" size="10">
<span class="error"> <?php echo $dateErr;?></span>
<br><br>
<center><input type="submit" name="Submit" value="Submit"></center><br>
</form>
<?php
}
if(!empty($_POST['Submit']))
{
}
?>
Inside if (isset($_POST['Submit']))
{ this block you have print $mmid, As $mmid is not set here so it will not print anything. To get the exact update query please echo $sql1
Update below part by
while ($row=mysqli_fetch_row($result))
{
$dd=$row["0"];
$mmid=$row["1"];
$employee_id=$row["2"];
$paid_installment=$row[3];
$savings_deposit=$row[4];
$late_fee=$row[5];
}
**while ($row=mysqli_fetch_assoc($result))** or instead of $row["0"] put $row[0] or exact column name like $row['date']

HTML form disappears upon submission

I am working on a project for school and I can't seem to figure out what is wrong with my html/php page.
For the record, I am making an html page with php and it is connected to an Oracle database.
I am trying to add a Person to the Person table but when I type in the information and click submit the form (the entire body of the page) completely disappears and the record is not added to the table. I have been looking online all day for an answer and it still does not work.
My code:
<DOCTYPE HTML>
<html>
<head>
<font size="6">Schedules</font> <font size="6">Passengers</font> <font size="6">Add Passenger</font> <font size="6">Remove Passenger</font><br>
______________________________________________________________________________________________________________________________________________
<h1>Add Passenger</h1>
</head>
<body>
<br><br>
<?php
$passengerID = $passengerFName = $passengerLName = $carNo = $seatNo = $trainID = $tName = "";
$passengerIDErr = $passengerFNameErr = $passengerLNameErr = $carNoErr = $seatNoErr = $trainIDErr = $tNameErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["passengerFName"])) {
$passengerFNameErr = "First Name is required";
} else {
$passengerFName = test_inpit($_POST["passengerFName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$passengerFName)) {
$passengerFNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["passengerLName"])) {
$passengerLNameErr = "Last Name is required";
} else {
$passengerLName = test_inpit($_POST["passengerLName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$passengerLName)) {
$passengerLNameErr = "Only letters and white space allowed";
}
}
if (empty($_POST["carNo"])) {
$carNoErr = "Car Number is required";
} else {
$carNo = test_inpit($_POST["carNo"]);
if (!is_numeric($carNo)) {
$carNoErr = "Only numbers allowed";
}
}
if (empty($_POST["seatNo"])) {
$seatNoErr = "Seat Number is required";
} else {
$seatNo = test_inpit($_POST["seatNo"]);
if (!is_numeric($seatNo)) {
$seatNoErr = "Only numbers allowed";
}
}
if (empty($_POST["tName"])) {
$tNameErr = "Train Name is required";
} else {
$tName = test_inpit($_POST["tName"]);
if (!preg_match("/^[a-zA-Z ]*$/",$tName)) {
$tNameErr = "Only letters and white space allowed";
}
}
$passengerID = test_input($_POST["passengerID"]);
if (!is_numeric($passengerID)) {
$passengerIDErr = "Only letters and white space allowed";
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Enter all information for the passenger<br>
<b>First Name:</b> <input type="text" name="passengerFName" value="<?php echo $passengerFName;?>">
<span class="error">* <?php echo $passengerFNameErr;?></span>
<br><br>
<b>Last Name:</b> <input type="text" name="passengerLName" value="<?php echo $passengerLName;?>">
<span class="error">* <?php echo $passengerLNameErr;?></span>
<br><br>
<b>Car Number:</b> <input type="text" name="carNo" value="<?php echo $carNo;?>">
<span class="error">* <?php echo $carNoErr;?></span>
<br><br>
<b>Seat Number:</b> <input type="text" name="seatNo" value="<?php echo $seatNo"?>">
<span class="error">* <?php echo $seatNoErr;?></span>
<br><br>
<b>Train Name:</b> <input type="text" name="tName" value="<?php echo $tName"?>">
<span class="error">* <?php echo $tNameErr;?></span>
<br><br>
<input type="submit">
<br><br><br>
<?php
$conn = oci_connect('username', 'password', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=db1.chpc.ndsu.nodak.edu)(Port=1521)))(CONNECT_DATA=(SID=cs)))');
$query = 'SELECT MAX(personID)
FROM Person';
$stid = oci_parse($conn,$query);
oci_execute($stid,OCI_DEFAULT);
//iterate through each row
while ($row = oci_fetch_array($stid,OCI_ASSOC))
{
//iterate through each item in the row and echo it
foreach ($row as $item)
{
$passengerID = $item + 1;
}
}
oci_free_statement($stid);
oci_close($conn);
?>
<?php
$conn = oci_connect('username', 'password', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=db1.chpc.ndsu.nodak.edu)(Port=1521)))(CONNECT_DATA=(SID=cs)))');
$query = 'SELECT trainID
FROM Train
WHERE tName = \''. $tName. '\'';
$stid = oci_parse($conn,$query);
$c1 = oci_execute($stid,OCI_DEFAULT);
if ($c1 === FALSE) {
Echo "Error! Train name does not exist";
}
//iterate through each row
while ($row = oci_fetch_array($stid,OCI_ASSOC))
{
//iterate through each item in the row and echo it
foreach ($row as $item)
{
$trainID = $item;
}
}
oci_free_statement($stid);
oci_close($conn);
?>
<?php
$conn = oci_connect('username', 'password', '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(Host=db1.chpc.ndsu.nodak.edu)(Port=1521)))(CONNECT_DATA=(SID=cs)))');
$query = 'INSERT INTO Person (personID, fname, lname, carNo, seatNo, trainID)
VALUES (\''. $passengerID. '\', \''. $passengerFName. '\', \''. $passengerLName. '\', \''. $carNo. '\', \''. $seatNo. '\', \''. $trainID. '\')';
$stid = oci_parse($conn,$query);
$c2 = oci_execute($stid,OCI_COMMIT_ON_SUCCESS);
if ($c2 === FALSE) {
Echo "Error! Record was not added. Please check the information and try again";
}
elseif ($c2 === TRUE) {
Echo "Success! Passenger was added to the system";
}
oci_free_statement($stid);
oci_close($conn);
?>
</form>
</body>
</html>
Any help would be great. Thanks.

undefined values as error

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

php - preg_match issue with empty form fields on update query

The following flags an error if a form field is empty and also flags an error if anything other than letters are entered in the form input.
if (empty($_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter feed title";
} elseif (preg_match('/[^a-zA-Z]/i',$_POST["feedtitle"])) {
$has_errors = false;
$feedtitleErr = "Enter text only";
} else {
$feedtitle = validate_input($_POST["feedtitle"]);
}
When created the form this works fine. When editing the form data however is the input is left empty the empty field error "Enter feed title" does not fire and if I enter anything other than letters e.g. numbers no value is passed i.e. the variable $feedtitle is blank. If I enter text however it saves.
I don't think the query is the issue.
$Query = "UPDATE ccregisterfeed SET author='$author', category='$category',
copyright='$copyright', feeddescription='$feeddescription', feedtitle='$feedtitle',
websitelink='$websitelink', imagelink='$imagelink', imagetitle='$imagetitle',
subtitle='$subtitle' WHERE id='$feedid' AND username ='$user'";
FULL SCRIPT
<?php
include "connect.php";
require "authenticate.php";
error_reporting(E_ERROR);
$message = $_GET['message'];
$user = $_SESSION['UserName'];
//declare form field and form field error variables
$authorErr = $categoryErr = $copyrightErr = $feeddescriptionErr = $feedlinkErr = $feedtitleErr = $websitelinkErr = $imagelinkErr = $imagetitleErr = $subtitleErr = "";
$author = $category = $copyright = $feeddescription = $feedlink = $feedtitle = $websitelink = $imagelink = $imagetitle = $subtitle = "";
//form field validation
function validate_input($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['Submit']))
{
$has_errors = false;
if (empty($_POST["author"])) {
$has_errors = true;
$authorErr = "Enter your name";
}else{
$author = validate_input($_POST["author"]);
}
if (empty($_POST["category"])) {
$has_errors = true;
$categoryErr = "Enter a category";
}else {
$category = validate_input($_POST["category"]);
}
if (empty($_POST["copyright"])) {
$has_errors = true;
$copyrightErr = "Enter copyright details";
} else {
$copyright = validate_input($_POST["copyright"]);
}
if (empty($_POST["feeddescription"])) {
$has_errors = true;
$feeddescriptionErr = "Enter feed description";
} else {
$feeddescription = validate_input($_POST["feeddescription"]);
}
if (empty($_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter feed title";
} elseif (preg_match('/[^a-zA-Z]/i',$_POST["feedtitle"])) {
$has_errors = true;
$feedtitleErr = "Enter text only";
} else {
$feedtitle = validate_input($_POST["feedtitle"]);
}
if (empty($_POST["websitelink"])) {
$has_errors = true;
$websitelinkErr = "Enter link to website";
} else {
$websitelink = validate_input($_POST["websitelink"]);
}
if (empty($_POST["imagelink"])) {
$has_errors = true;
$imagelinkErr = "Enter link to image";
} else {
$imagelink = validate_input($_POST["imagelink"]);
}
if (empty($_POST["imagetitle"])) {
$has_errors = true;
$imagetitleErr = "Enter image name";
} else {
$imagetitle = validate_input($_POST["imagetitle"]);
}
if (empty($_POST["subtitle"])) {
$has_errors = true;
$subtitleErr = "Enter feed subtitle";
} else {
$subtitle = validate_input($_POST["subtitle"]);
}
// var_dump ($date);
// var_dump ($feedlink);
// var_dump ($feeddescription);
//write edited data into tables matching logged in user with their data
$feedid = mysql_real_escape_string($_POST['feedid']);
$date = date("Y-m-d H:i:s");
$feeddescription = str_replace("_", "", $feeddescription);
$feeddescription = str_replace("-", "", $feeddescription);
$feeddescription = str_replace("!", "", $feeddescription);
$feeddescription = str_replace("#", "", $feeddescription);
$feeddescription = str_replace("'", "", $feeddescription);
$Query = "UPDATE ccregisterfeed SET author='$author', category='$category', copyright='$copyright', feeddescription='$feeddescription', feedtitle='$feedtitle', websitelink='$websitelink', imagelink='$imagelink', imagetitle='$imagetitle', subtitle='$subtitle' WHERE id='$feedid' AND username ='$user'";
if($sql = mysql_query($Query)) {
header("location: rss.php");
// header("location: feededit.php");
} else {
die("Query was: $Query. Error: ".mysql_error());
}
}
//show logged in user their updated data
$user = $_SESSION['UserName'];
$result = mysql_query("SELECT * FROM ccregisterfeed WHERE username = '$user'") or die(mysql_error());
while($row = mysql_fetch_array($result)){
$id=$row['id'];
$author = $row['author'];
$category = $row['category'];
$copyright = $row['copyright'];
$feeddescription = $row['feeddescription'];
$feedtitle = $row['feedtitle'];
$websitelink = $row['websitelink'];
$imagelink = $row['imagelink'];
$imagetitle = $row['imagetitle'];
$subtitle = $row['subtitle'];
}
//delete form and image data when users clicks delete button
if (isset($_POST['Delete'])){
$deleteuser = $_POST['Delete'];
mysql_query("DELETE FROM ccregisterfeed WHERE id = '$deleteuser'");
mysql_query("ALTER TABLE ccregisterfeed AUTO_INCREMENT = 1");
$message = 'Feed Deleted';
header("Location: feededit.php?&message=".urlencode($message));
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<form action="feededit.php" method="post" enctype="multipart/form-data" name="edit" id="editfeed">
<fieldset>
<div class="legendcreate">Feed Edit</div>
<div class="feedcontainer">
<div class="feedcontainerinner">
<div><label class="labelshow">Author</label><input id="author" class="insetfeed" name="author" type="text" placeholder="Author" value="<?PHP print $author ; ?>"/><p class="errorinput"><?php echo $authorErr;?></p></div>
<?php if(isset($_GET['message']) && !empty($message)): ?>
<div class="messagebox">
<?php echo $message ?>
</div>
<?php endif; ?>
<div><label class="labelshow">Category</label><input id="category" class="insetfeed" name="category" type="text" placeholder="Category" value="<?PHP print $category; ?>"/><p class="errorinput"><?php echo $categoryErr;?></p></div>
<div><label class="labelshow">Copyright</label><input id="copyright" class="insetfeed" name="copyright" type="text" placeholder="Copyright" value="<?PHP print $copyright; ?>"/><p class="errorinput"><?php echo $copyrightErr;?></p></div>
<div><label class="labelshow">Feed Title</label><input id="feedtitle" class="insetfeed" name="feedtitle" type="text" placeholder="Feed Title" value="<?PHP print $feedtitle; ?>"/><p class="errorinput"><?php echo $feedtitleErr;?></p></div>
<div><label class="labelshow">Website Link</label><input id="websitelink" class="insetfeed" name="websitelink" type="text" placeholder="Website Link" value="<?PHP print $websitelink; ?>"/><p class="errorinput"><?php echo $websitelinkErr;?></p></div>
<div><label class="labelshow">Image Link</label><input id="imagelink" class="insetfeed" name="imagelink" type="text" placeholder="Image Link" value="<?PHP print $imagelink; ?>"/><p class="errorinput"><?php echo $imagelinkErr;?></p></div>
<div><label class="labelshow">Image Title</label><input id="imagetitle" class="insetfeed" name="imagetitle" type="text" placeholder="Image Title" value="<?PHP print $imagetitle; ?>"/><p class="errorinput"><?php echo $imagetitleErr;?></p></div>
<div><label class="labelshow">Subtitle</label><input id="subtitle" class="insetfeed" name="subtitle" type="text" placeholder="Subtitle" value="<?PHP print $subtitle; ?>"/><p class="errorinput"><?php echo $subtitleErr;?></p></div>
<div><textarea id="description" name="feeddescription" class="textareadescription" placeholder="Enter feed description"><?php
$out = htmlspecialchars_decode($feeddescription);
$out = str_replace( '\n', '<br />', $out );
echo $out;
?></textarea>
<div class="submit"><input name="Submit" type="submit" class="submitbtn" value="Save"/></div>
<div class="delete"><input name="deletebtn" type="submit" class="resetbtn" value="Delete"/></div>
<input type="hidden" name="feedid" value="<?phpecho $id;?>"/>
</div>
</div>
</div>
</form>
</fieldset>

Categories