can't upload multiple files in a form - php

I'm sorry if this is a repost. But I have seen many questions without finding the right answer
i'm trying to upload multiple files + some information , but if i submit my form with 2 images it goes ok and the script runs perfect when i upload more then 2 or 3 files i get undefined indexs of all the form elements .
up.php
/////// Random name generator ////////
function random_name($length) {
$key = '';
$keys = array_merge(range(0, 9), range('a', 'z'));
for ($i = 0; $i < $length; $i++) {
$key .= $keys[array_rand($keys)];
}
return $key;
}
//sql//
require("sql.php");
//////////
//!!! some vars !!!//
//
$total = count($_FILES['pimages']['name']);
//
$foldername = random_name(15);
$target_dir = "../images/projects/".$foldername."/";
$target_file = $target_dir . basename($_FILES["icon"]["name"]);
$uploadyes = 1;
$imageType = pathinfo($target_file,PATHINFO_EXTENSION);
$saveicon = $target_dir . "icon." .$imageType;
/////submited form vars /////
$linkedid = $_POST['lid'];
$date = date("y.m.d H:i:s");
$name = $_POST['projectname'];
$loc = $_POST['location'];
$type = $_POST['type'];
$des = $_POST['des'];
$precara = $_POST['cara'];
$client = $_POST['client'];
$col = $_POST['cost'];
$bua = $_POST['builtup'];
////////////////cara slice /////////////
$caraxarray = explode("," , $precara);
$cara = base64_encode(serialize($caraxarray));
echo $imageType ;
///////////////////////// Start of the upload check ////////////////////
if(isset($_POST['submit']) && !empty($name)) {
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
}
// Check if $uploadyes is set to 0 by an error
if (!isset($_POST['submit'])) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
mkdir($target_dir);
if (move_uploaded_file($_FILES["icon"]["tmp_name"], $saveicon)) {
//////////////////////////..........................//////////////////
// Loop through each file
$imgext = array();
for($i=0; $i<=$total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['pimages']['tmp_name'][$i];
$x = $i + 1 ;
if ($tmpFilePath != ""){
//Setup our new file path
$pimgex = $_FILES['pimages']['name'][$i];
$pimageType = pathinfo($pimgex,PATHINFO_EXTENSION);
$newFilePath = $target_dir ."img".$x.".".$pimageType;
array_push($imgext , "$newFilePath");
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
echo "yeaaaaaah";
}
}
}
$str = serialize($imgext);
$sql1 = "INSERT INTO projects (date, name, type, location, icon, imgext, folder, linkedid)
VALUES ('$date', '$name','$type', '$loc', '$saveicon' , '$str', '$foldername', '$linkedid')";
$sql2 = "INSERT INTO projectdetails (proname, prolocation, prodes, procara, client, col, builtarea, linkedid)
VALUES ('$name', '$loc','$des', '$cara', '$client' , '$col', '$bua', '$linkedid')";
mysqli_query($conn ,$sql1);
mysqli_query($conn ,$sql2);
mysqli_close($conn);
/////////////////...........................////////////////////////
header("location:cp.php");
} else {
echo "Sorry, there was an error uploading your file.";
}
}
projectsuploader.php
$lkid = random_name(8);
$tlink = random_name(6);
require("sql.php");
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql1 = "SELECT id, date, name, type, location FROM projects";
$sql2 = "SELECT id, titleen FROM projectsnav";
$result = mysqli_query($conn, $sql1);
$types = mysqli_query($conn, $sql2);
//mysqli_close($conn);
?>
<!DOCTYPE html>
<html>
<h2>Projects Page</h2>
<h5>projects</h5>
<table>
<tr>
<td>#</td>
<td>Date & Time</td>
<td>Project name</td>
<td>Project type</td>
<td>Project location</td>
<!--<td>View</td>
<td>Edit</td>-->
<td>Remove</td>
</tr>
<?php
if (mysqli_num_rows($result) > 0) {
// output data of each row .$row["id"]
while($row = mysqli_fetch_assoc($result)) {
echo "<tr><td>".$row["id"]."</td>";
echo "<td>".$row["date"]."</td>";
echo "<td>".$row["name"]."</td>";
echo "<td>".$row["type"]."</td>";
echo "<td>".$row["location"]."</td>";
echo "<td><a href='../del.php?id=".$row['id']."'>Remove</a></td> </tr>";
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
</table>
<h4 id="addproject">Add Project</h3>
<h4 id="addtype">Add Type </h4>
<div id="frontlayer">
<div id="addpro">
<h2 style="text-align:center;"> add project </h2>
<form method="POST" action="up.php" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="50000000">
id:<input type="text" name="lid" value="<?php echo $lkid ; ?>" readonly> <br>
project name:<input type="text" name="projectname"><br>
Type:<select name="type">
<?php
if (mysqli_num_rows($types) > 0){
while($navrow = mysqli_fetch_assoc($types)) {
echo "<option value='".$navrow['titleen']."'>".$navrow['titleen']." </option>";
}
}else{
echo "<option>PLEASE ADD TYPES TO DATABASE FIRST!!!!ERROR 0 TYPES IN DATABASE</option>";
}
mysqli_close($conn);
?>
</select>
<br>
location:<input type="text" name="location"><br>
icon:<input type="file" name="icon" id="icon"><br>
images:<input type="file" name="pimages[]" id="pimages" multiple><br>
<input type="hidden" name="sendfiles" value="Send Files" />
<!--
------//////////////------
------//////////////------
------//////////////------
-->
description:<input type="text" name="des"><br>
caracteristic:<input type="text" name="cara" data-role="tagsinput"><br>
client:<input type="text" name="client"><br>
Collaborator:<input type="text" name="cost"><br>
Gross Area:<input type="text" name="builtup"><br>
<input type="submit" value="Upload" name="submit">
</form>
</div>
Sorry if it is bad writed i\m begginer , Thanks in advance for anyhelp

The problem were that there was a big file (4mb image) and php was not able to post this size of an image so you have to resize your image before upload ..
and big thanks for Felippe Duarte.

Related

Display BLOB data from SQLITE database using PHP

Hope You all have a Great Day, I new with SQLITE DB and so I'm little confused about handling BLOB data.I tried lot of things ,but nothing get in to favor of me.
Here is My Code
INSERTING DATA
insert.php
<form method="POST" enctype="multipart/form-data">
model no:<input type="text" name="model_no"\><span style="color: red"><?php echo $messages["model_no"]; ?></span>
image:<input type="file" name="image" id="image"\><span style="color: red">
<input type="submit" value="save" id="save" name="save"/>
<input type="reset" value="Clear"/>
</form>
include.php
<?php
$flag = 0;
class MyDB extends SQLite3
{
function __construct()
{
$this->open('../database.db');
}
}
//checking save button is clicked
if(isset($_POST["save"])){
$model_no = $_POST['model_no'];
$image = $_FILES['image']['name'];
if($model_no != '' && $image != ''){
$flag = 1;
}
if($flag == '1'){
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
}
else{
$dbb = new MyDB();
$sql = 'SELECT COUNT(*) as count FROM fisfis WHERE model_no = "'.$model_no.'"';
//echo $sql;
$rows = $dbb->query($sql);
$row = $rows->fetchArray();
$numRows = $row['count'];
//echo $numRows;
if($numRows != 0){
$flag = 0;
echo "error:this model no is already taken";
}else{
$sqlp = "INSERT INTO fisfis(model_no, image) values('$model_no','$image')";
if($dbb->exec($sqlp)){
echo "data inserted successfully\n";
}
else{
echo"error:\n";
echo "data not inserted \n";
echo"contact admin for details\n";
}
}
}
}
else{
echo"error:\n";
echo "data not inserted : data fields cannot be empty\n";
}
}
?>
this is very successfully inserting data in to my table (table name:fisfis)
DISPLAYING DATA
display.php
<form method="POST" enctype="multipart/form-data">
<p>Enter Barcode : <input type="text" name="search_model" id="search_model" /></p>
<!--<p><img src='image.php?id=<?php //echo $row['model_no'];?>'/></p>-->
<p><input type="submit" value="search" name="search" id="search"/></p>
</form>
display_include.php
<?php
$flag2 = 0;
$flag3 = 0;
class MyDB extends SQLite3
{
function __construct()
{
$this->open('../database.db');
}
}
$db = new MyDB();
if(isset($_POST["search"])){
$model_no = '';
$model_no = $_POST['search_model'];
if($model_no != ''){
$flag2 = 1;
}
if($flag2 == '1'){
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
}
else{
$dbb = new MyDB();
$sql = 'SELECT COUNT(*) as count FROM fisfis WHERE model_no = "'.$model_no.'"';
$rows = $dbb->query($sql);
$row = $rows->fetchArray();
$numRows = $row['count'];
echo $numRows;
if($numRows == 0){
echo 'sorry this model no is not exists';
echo '<br/>';
echo 'create new';
$flag2 = 1;
}else{
echo "this is exisists";
$flag3 = 1;
}
if($flag3 == 1){
$sqla = 'SELECT * FROM fisfis WHERE model_no = "'.$model_no.'"';
$result = $dbb->query($sqla);
while($row = $result->fetchArray(SQLITE3_ASSOC) ) {
echo "MODEL NO = ". $row['model_no'] ."\n";
$img = '\'<img src="'. $row['image'] .'" width="100" height="100"/>\'';
echo $img;
}
}
}
}
}
?>
the display part displaying all data other than blob ,what i have tried
1.try to echo the image inside the php script
$img = '\'<img src="'. $row['image'] .'" width="100" height="100"/>\'';
try to display image inside html tag
but this is not working,please help me to fix this,thanks in advance
My explaining is not good, so here is a show-and-tell. I made a repro so I wouldn't forget any necessary bits.
The database table is defined:
CREATE TABLE `imgrepro` (
`id` INTEGER NOT NULL,
`photo` BLOB,
PRIMARY KEY(`id`)
);
It is seeded with one row, id = 1, photo is NULL.
The POST block will insert the image into the BLOB column in the db. The rest of the script will fetch the image and the html will display it.
<?php
$db = new SQLite3("***********\stacktest.db");
if ($_SERVER['REQUEST_METHOD'] == "POST") {
// insert photo
$photo = file_get_contents($_FILES['fname']['tmp_name']);
$query = $db->prepare("UPDATE imgrepro set photo = :photo where id = 1");
$query->bindValue(':photo',$photo,SQLITE3_BLOB);
$result = $query->execute();
}
// get photo if there is one
$rows = $db->query("SELECT * from imgrepro")->fetchArray(SQLITE3_ASSOC);
$showphoto="";
if (count($rows) > 0) {
$showphoto=base64_encode($rows['photo']);
}
$db->close();
?>
<!DOCTYPE html>
<head>
<title>Say Cheese!</title>
</head>
<!-- show the photo -->
<img alt="no photo yet" src="data:image/jpeg;base64,<?= $showphoto ?>" >
<form action="imgrepro.php" method="post" enctype="multipart/form-data">
<input type="file" name="fname" accept=".jpg">
<input type="submit">
</form>

save image in xampp and show it in web php

The HTML upload form:
<form action="InformationData.php" method="post" enctype="multipart/form-data">
<label >Barangay Certification</label>
<input name="BarangayCertification" type="file" id="exampleInputFile1">
<button type="Submit" name="Submit" value="Upload">Submit</button>
</form>
The InformationData.php:
<?php
$conn = mysqli_connect("localhost", "root", "", "registration");
if($_POST['BarangayCertification']){
$BarangayCertification = $_POST['BarangayCertification'];
} else {
$BarangayCertification = "";
}
$sql = "INSERT INTO stakeholdersform (BarangayCertification) VALUES ($BarangayCertification);
?>
Code to show the image:
<?php
$conn = mysqli_connect("localhost", "root", "", "registration");
$informations = "SELECT * FROM stakeholderinformations";
$result = $conn->query($informations);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$BarangayCertification = $row['BarangayCertification'];
echo $BarangayCertification;
}
}
?>
I tried to echo it but nothing happens, but I can see the image in the database.
From PHP documentation
echo — Output one or more strings
So, no, you can not echo image.
What you could do is
echo '<img src="data:image/jpeg;base64,' . $BarangayCertification . '">'
Although there's an upper limit about the size of $BarangayCertification and I do not recommend storing image in your database.
If connection to databases is set correctly.this below code work.But at first you must create a directory upload in the root
form
<form action="InformationData.php" method="post" enctype="multipart/form-data">
<label >Barangay Certification</label>
<input name="BarangayCertification" type="file" id="exampleInputFile1">
<button type="Submit" name="Submit" value="Upload">Submit</button>
</form>
The InformationData.php:
<?php
$conn = mysqli_connect("localhost", "root", "", "registration");
if (isset($_POST("Submit"))){
if($_POST['BarangayCertification']){
// $BarangayCertification = $_POST['BarangayCertification'];
if (file_exists("upload/" . $_FILES["BarangayCertification"]["name"])) {
echo $_FILES["BarangayCertification"]["name"] . " <b>already exists.</b> ";
} else {
///creat upload in root
move_uploaded_file($_FILES["BarangayCertification"]["tmp_name"], "upload/" . $_FILES["BarangayCertification"]["name"]);
$BarangayCertification = "//".$_SERVER['HTTP_HOST'].'//'. "upload/" . $_FILES["file"]["name"];
}
} else {
$BarangayCertification = "";
}
}
$sql = "INSERT INTO stakeholdersform (BarangayCertification) VALUES ($BarangayCertification)";
?>
Code to show the image:
<?php
$conn = mysqli_connect("localhost", "root", "", "registration");
$informations = "SELECT * FROM stakeholderinformations";
$result = $conn->query($informations);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$BarangayCertification = $row['BarangayCertification'];
echo "<img src=".$BarangayCertification.">";
}
}
?>

PHP use session to select dropdown option

I've got this upload form and would like to keep the selected option from the dropdown in the session in order to show the last selection after submitting, e.g. i choose the option 'colour' und after submitting colour is still selected in the dropdown.
I echo $_SESSION['testname'] (just before the first radio button) and it gives me back "colour", but in the option-tag where i'd like to echo 'selected' if "colour" was the last selection, it returns nothing! what am i missing?
<?php
session_start();
if(isset($_POST['kategorie'])) {
$_SESSION['testname']=$_POST['kategorie']; }
?>
<?php
$con = mysqli_connect("localhost","Melvin","") or die ("could not connect to server: " . mysqli_connect_error($con));
mysqli_select_db($con, "galerie") or die ("Could not connect to database: " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = $_FILES['file']['name'];
$sub_name = substr($name, 0, -4);
$img_ext = ".jpg";
$tmp_name = $_FILES['file']['tmp_name'];
$location = '_images/_galerie/';
$target = '_images/_galerie/' .$name;
if(move_uploaded_file($tmp_name,$location.$name)){
echo "file uploaded";
$nam = $_POST['nam'];
$kategorie = $_POST['kategorie'];
$size = $_POST['size'];
if ($size == 'thumb') {
// add "thumb" between filename and extension
$extension_pos = strrpos($target, '.'); // find position of the last dot, so where the extension starts
$thumb = substr($target, 0, $extension_pos) . '_thumb' . substr($target, $extension_pos);
$query = mysqli_query($con , "INSERT INTO images(img_name,img_title,img_cat,img_size)VALUES('".$thumb."','$nam','$kategorie','$size')");
} else {
$query = mysqli_query($con , "INSERT INTO images(img_name,img_title,img_cat,img_size)VALUES('".$target."','$nam','$kategorie','$size')");
}
function renameImg() {
$name = $_FILES['file']['name'];
$target = '_images/_galerie/' .$name;
$extension_pos = strrpos($target, '.');
$thumb = substr($target, 0, $extension_pos) . '_thumb' . substr($target, $extension_pos);
rename($target, $thumb);
//echo $name . " replaced with " . $thumb;
};
renameImg();
} else {
echo "file not uploaded";
}
}
?>
<div style="margin:20px 0 40px 0;">
<form action="upload.php" method="POST" enctype="multipart/form-data">
Upload: <input type="file" name="file">
Title: <input type="text" name="nam" value="Tattoo Gallery">
Category: <select name="kategorie" id="selectKat">
<option value="black" <?php if(isset($_SESSION['kategorie']) == "black") { echo ' selected';} ?>>Black and white</option>
<option value="colour" <?php if(isset($_SESSION['kategorie']) == "colour") { echo ' selected';} ?>>Colour</option>
</select>
<br>
<?php
echo $_SESSION['testname'];
?>
<input type="radio" name="size" value="full" id="regularRadio" checked="checked">
<label for="regularRadio">Full size</label>
<br>
<input type="radio" name="size" value="thumb" id="thumbRadio">
<label for="thumbRadio">Thumbnail</label>
<br>
<input type="submit" name="submit">
</form>
</div>
<?php
$result = mysqli_query($con, "SELECT * FROM images WHERE img_size='thumb'");
while($row = mysqli_fetch_array($result)){
echo "<img src=".$row['img_name'] . " class='thumbnails' style='display:inline;float:left;'>";
}
?>
You must not use the isset() function. This function return True or False.
You only have to compare the value of $_POST['kategorie'] or $_SESSION['testname'] (as I see) with your text ("color" or "black"), like this :
if ($_SESSION['kategorie'] == "black") { echo ' selected'; }

Second form submit button seems to be skipped(?) PHP / HTML

I need help about this, I have a PHP page, which searches for records, based on their first and last names, if sql finds the data then the second form comes out, which has lots of textboxes, to update the 'searched'information. And when I click the submit button of the second form , it does nothing, and even if I have syntax or whatever errors I have put on condition if(isset($_POST['submit'])), they end up being disregarded (no error messages will come up), after clicking the submit button, it just goes back to the page's original state, when it has to update the record I have searched for that was just edited. What exactly is the mistake on this part?
class.php - .php file that contains the operations for sql
<? php
$months = array('January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December');
class EmployeeProfile {
public
function openConnection() {
$conn = mysqli_connect("localhost", "root", "", "db_employee");
if (mysqli_connect_errno()) {
echo "Failed to connect to database server";
}
return $conn;
}
public
function insert($query) {
if (mysqli_query($this - > openConnection(), $query) == 1) {
echo "Profile successfully registered!";
} else {
echo "Register failed";
}
}
public
function display($query) {
$result = mysqli_query($this - > openConnection(), $query);
echo "<br><br>";
if ($result - > num_rows == 1) {
while ($row = $result - > fetch_assoc()) {
echo "<table>";
echo "<tr><td><b>First Name</b>: ".$row["firstname"]."</td></tr>";
echo "<tr><td><b>Middle Name</b>: ".$row["middlename"]."</td></tr>";
echo "<tr><td><b>Last Name: </b>".$row["lastname"]."</td></tr>";
echo "<tr><td><b>Date of Birth: </b>".$row["dateofbirth"]."</td></tr>";
echo "<tr><td><b>Age: </b>".$row["age"]."</td></tr>";
echo "<tr><td><b>School: </b>".$row["school"]."</td></tr>";
echo "<tr><td><b>Highest Educational Attainment: </b>".$row["educ"]."</td></tr>";
echo "<tr><td><b>Year Last Attended: </b>".$row["yearattended"]."</td></tr>";
echo "<tr><td><b>Skills: </b>".$row["skills"]."</td></tr>";
echo "<tr><td><b>Previous Company: </b>".$row["prevcompany"]."</td></tr>";
echo "<tr><td><b>Position: </b>".$row["position"]."</td></tr>";
echo "<tr><td><b>Date of Employment:</b> ".$row["dateofemployment"]."</td></tr>";
echo "</table>";
}
} else
{
echo "Profile not found";
}
}
public
function edit($query) {
$result = mysqli_query($this - > openConnection(), $query);
}
}
?>
edit.php - the page itself.
<html>
<title> Edit Profile</title>
<body>
<form method="post" action="?" name="searchform">
<center>
<table>
<tr><td>Enter first or last name</td><td><input type = "text" name="search"><td><td><input type = "submit" value="Search" name="search2"></td></tr>
</form>
</table>
<?php
include("class.php");
if(isset($_POST['search2'])):
$status = "hidden";
$query = "select * from employee WHERE firstname='".$_POST['search']."' OR lastname='".$_POST['search']."' ";
$emp = new EmployeeProfile();
$emp->openConnection();
$result = mysqli_query($emp->openConnection(), $query);
if($result->num_rows == 1):
?>
<form method="post" action="?" enctype="multipart/form-data" name="updateform">
<table>
<tr></tr>
<tr><td></td><td>Edit your profile:</td></tr>
<tr></tr>
<tr><td>*Enter first name:</td><td><input type="text" name="firstname"></td></tr>
<tr><td>Enter middle name:</td><td><input type="text" name="middlename"></td></tr>
<tr><td>*Enter last name:</td><td><input type="text" name="lastname"></td></tr>
<tr>
<td>*Date of Birth:</td><td><select name="month"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="days"><?php for($i = 1; $i <= 31; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
<td><select name="year"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td>*Age:</td><td><input type="text" name="age"></td></tr>
<tr><td>*School:</td><td><input type="text" name="school"></td></tr>
<tr><td>*Highest Educational Attainment:</td><td><input type="text" name="educ"></td></tr>
<tr><td>*Year Last Attended:</td><td><input type="text" name="yearattended"></td></tr>
<tr><td>*Skill(s):</td><td><input type="text" name="skills"></td></tr>
<tr><td>Previous Company:</td><td><input type="text" name="prevcompany"></td></tr>
<tr><td>Position:</td><td><input type="text" name="position"></td></tr>
<tr><td>*Date of Employment:</td><td><select name="empmonth"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="empyear"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td></td><td><input type="submit" value="Register" name="submit"></td></tr>
<tr><td>* - Required</td></tr>
</form>
<?php
if(isset($_POST['submit'])):
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];
$row = $result->fetch_assoc();
$usr = $row["firstname"];
$query2 = "UPDATE employee SET firstname='$firstname', middlename='$middlename', lastname='$lastname', dateofbirth='$dateofbirth', age='$age', school='$school',
educ='$educ', yearattended='$yearattended', skills='$skills', prevcompany='$prevcompany', position='$position', dateofemployment='$dateofemployment',
WHERE firstname='$usr'";
mysqli_query($emp->openConnection(), $query2);
endif;
else:
echo "Profile not found";
endif;
endif;
?>
</table>
</center>
</body>
</html>
and I do really think that this line and beyond gets ignored.
This is part of the edit.php file that is shown above.
<?php
if(isset($_POST['submit'])):
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];
$row = $result->fetch_assoc();
$usr = $row["firstname"];
$query2 = "UPDATE employee SET firstname='$firstname', middlename='$middlename', lastname='$lastname', dateofbirth='$dateofbirth', age='$age', school='$school',
educ='$educ', yearattended='$yearattended', skills='$skills', prevcompany='$prevcompany', position='$position', dateofemployment='$dateofemployment',
WHERE firstname='$usr'";
mysqli_query($emp->openConnection(), $query2);
endif;
In general, there are two kinds of errors present.
HTML tag order errors, which are extensive
Syntax errors.
- > must be -> to be properly parsed
<? php must be <?php to be properly parsed
The syntax errors are present in both files.
Note: the following code contains some debug statements.
<html>
<head>
<?php
echo "<p>In myquery.php header </p>";
error_reporting(E_ALL);
//echo "<p>" . var_dump($_POST); . "</p>";
//echo "<p>" . var_dump($_GET); . "</p>";
?>
<?php
include("class.php");
?>
<title> Edit Profile</title>
</head>
<body>
<?php
echo "<p>In myquery.php body</p>";
?>
<form method="post" action="?" name="searchform">
<table>
<tr>
<td>Enter first or last name</td>
<td><input type = "text" name="search"><td>
<td><input type = "submit" value="Search" name="search2"></td>
</tr>
</table>
</form>
<?php
echo "<p>about to check _post for search2</p>";
if(isset($_POST['search2'])):
echo "<p>found _post for search2</p>";
$status = "hidden";
$query = "select * from employee WHERE firstname='".$_POST['search']."' OR lastname='".$_POST['search']."' ";
echo "<p>about to open DB</p>";
$emp = new EmployeeProfile();
$emp->openConnection();
echo "<p>about to place find query</p>";
$result = mysqli_query($emp->openConnection(), $query);
echo "<p>about to check for successful query</p>";
if($result->num_rows == 1):
echo "<p>successful search query</p>";
?>
<form method="post" action="?" enctype="multipart/form-data" name="updateform">
<table>
<tr></tr>
<tr><td></td><td>Edit your profile:</td></tr>
<tr></tr>
<tr><td>*Enter first name:</td><td><input type="text" name="firstname"></td></tr>
<tr><td>Enter middle name:</td><td><input type="text" name="middlename"></td></tr>
<tr><td>*Enter last name:</td><td><input type="text" name="lastname"></td></tr>
<tr>
<td>*Date of Birth:</td><td><select name="month"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="days"><?php for($i = 1; $i <= 31; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
<td><select name="year"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td>*Age:</td><td><input type="text" name="age"></td></tr>
<tr><td>*School:</td><td><input type="text" name="school"></td></tr>
<tr><td>*Highest Educational Attainment:</td><td><input type="text" name="educ"></td></tr>
<tr><td>*Year Last Attended:</td><td><input type="text" name="yearattended"></td></tr>
<tr><td>*Skill(s):</td><td><input type="text" name="skills"></td></tr>
<tr><td>Previous Company:</td><td><input type="text" name="prevcompany"></td></tr>
<tr><td>Position:</td><td><input type="text" name="position"></td></tr>
<tr><td>*Date of Employment:</td><td><select name="empmonth"><?php for($i = 0; $i < count($months); $i++) { echo "<option value=".$months[$i]." >".$months[$i]."</option>" ; }?></select></td>
<td><select name="empyear"><?php for($i = 1950; $i <= 2014; $i++) { echo "<option value"."=".$i.">".$i."</option>"; } ?> </select></td>
</tr>
<tr><td></td><td><input type="submit" value="Register" name="submit"></td></tr>
<tr><td>* - Required</td></tr>
</table>
</form>
<?php
echo "<p>about to check for submit second form</p>";
if(isset($_POST['submit'])):
echo "<p>found submit for second form</p>";
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$lastname = $_POST['lastname'];
$dateofbirth = $_POST['month']. " ".$_POST['days']. ", ".$_POST['year'];
$age = $_POST['age'];
$school = $_POST['school'];
$educ = $_POST['educ'];
$yearattended = $_POST['yearattended'];
$skills = $_POST['skills'];
$prevcompany = $_POST['prevcompany'];
$position = $_POST['position'];
$dateofemployment = $_POST['empmonth']. " ".$_POST['empyear'];
$row = $result->fetch_assoc();
$usr = $row["firstname"];
$query2 =
"UPDATE employee
SET firstname='$firstname',
middlename='$middlename',
lastname='$lastname',
dateofbirth='$dateofbirth',
age='$age',
school='$school',
educ='$educ',
yearattended='$yearattended',
skills='$skills',
prevcompany='$prevcompany',
position='$position',
dateofemployment='$dateofemployment',
WHERE firstname='$usr'";
echo "<p>about to update DB</p>";
mysqli_query($emp->openConnection(), $query2);
endif;
else:
echo "<p>search query failed</p>";
echo "Profile not found";
endif;
endif;
?>
</body>
</html>

Adding comments to a database based on id

I am making a recipe site at the moment and am struggling to get my comment function to work, I previously had it working until but now I keep getting an error which tells me I cannot access the database when I try and submit a comment
I know this might seem quite simple but I'm completely stuck I've been trying to figure out a way round this for weeks but really am not making any headway..
Here the PHP process:
if (!$db_server){
die("unable to Connect to MYSQL: " . mysqli_connect_error($db_server));
$db_status = "not connected";
}else{
if(trim($_POST['submit']) =="submit"){
}else{
if (isset($_POST['dropoption']) && ($_POST['dropoption'] != '')){
if (isset($_POST['meal']) && ($_POST['meal'] != '')) {
$dropoption = clean_string($db_server, $_POST['dropoption']);
$meal = clean_string($db_server, $_POST['meal']);
$quer = "SELECT * FROM `recipename` WHERE `cuisine_type` ='$dropoption' AND `b_l_d` ='$meal'LIMIT 0,1";
mysqli_select_db($db_server, $db_database);
$querya= mysqli_query($db_server, $quer);
if (!$querya) die("database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($querya)){
$recipeid .= $row['recipeid'];
$recipename .="<h1>". "Why dont you have ".$row['mealname']."</h1>";
$ingredients .="<p>".$row['ingredients']."</p>";
$recipe .="<p>" .$row['recipe']."</p>";
$cookingtime .="<h4>" .$row['hours']." Hours".$row['minutes']." Minutes </h4>";
$mealpic .="<img src='http://ml11maj.icsnewmedia.net/Workshops/Week%207/".$row['imagepath']."'/>";
}
if ($comment != ''){
$userid = trim($_SESSION['userid']);
$comment = trim($_POST['comment']);
$userid = clean_string($db_server, $_SESSION['userid']);
$comment = clean_string($db_server, $_POST['comment']);
$query = "INSERT INTO Comments (comment,userid,recipeid) VALUES ('$comment','$userid','$receipeid')";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
}
}//if(meal)//
}//if(cuisine)//
} //if(trim)//
}
$query = "SELECT * FROM Comments";
$result = mysqli_query($db_server, $query);
if (!$result) die ("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)) {
$str_comments .= "<p>" . $row['comment'] . "</p>";
}
and here is the html form:
<?php echo $recipename;
echo $mealpic;
?>
<h2>Ingredients</h2>
<?php
$ingredientchunks = (explode(",",$ingredients));
for($i = 1; $i < count($ingredientchunks); $i++){
echo "$i.$ingredientchunks[$i] <br/>";}
echo $cookingtime;
?>
<h2>Recipe</h2>
<?php
$recipechunks = (explode(",",$recipe));
for($i = 1; $i < count($recipechunks); $i++){
echo "$i.$recipechunks[$i] </br>";}
?>
<form id="results" form method="post" action="results.php">
<input type="submit" id="Like" name="Like" value="Like" />
<input type="submit" id="Next" name="Next" value="Next" />
</form>
<div id=Comments>
<form id="comments" form method="post" action='results.php?cuisine_type=" . $dropoption ."b_l_d=" . $meal . "'>
Comment: <textarea rows="2" cols="30" name="comment" id="comment" placeholder="Anything to say??"></textarea>
<input type="submit" id="comments" name="comments" value="comments" />
</form>
<?php
echo $str_comments;
require_once "db_close.php";
?>
</div>
</p>
<? require_once ('home_stop.php')?>

Categories