using php and pdo i was able to make a sign up page but with out saving image
$firstname = trim($_POST['fn']); //at a minimus clear whitespace.
$lastname = trim($_POST['ln']);
$username = trim($_POST['un']);
$password = trim($_POST['pw']);
$confirmpassword= trim($_POST['cp']);
$stmt = $dbh->prepare("INSERT INTO registration (fname,lname,username,password) VALUES (?,?,?,?)");
$stmt->bindValue(1,$firstname,PDO::PARAM_STR);
$stmt->bindValue(2,$lastname,PDO::PARAM_STR);
$stmt->bindValue(3,$username,PDO::PARAM_STR);
$stmt->bindValue(4,$password,PDO::PARAM_STR);
if($stmt->execute()){
echo "YOUR REGISTRATION IS COMPLETED...";
}
i found this tutorial but its too complicated for me to understand and it was not explained clearly i am looking for ideas or tutorial that is easy to understand on how to upload image..any idea is appreaciated
form
<form method="POST" action="crud.php">
<tr>
<td>
</td>
<td>
<input type="file" name="image" />
</td>
</tr>
<tr>
<td>First Name</td>
<td>
<input type="text" name="fn">
</td>
</tr>
<tr>
<td>Last Name</td>
<td>
<input type="text" name="ln">
</td>
</tr>
<tr>
<td>User Name</td>
<td>
<input type="text" name="un">
</td>
</tr>
<tr>
<td>Password</td>
<td>
<input type="password" name="pw">
</td>
</tr>
<tr>
<td>Confirm Password</td>
<td>
<input type="password" name="cp">
</td>
</tr>
<tr>
<td>
<input id="button" type="submit" value="Back" name="back"/>
</td>
<td>
<input id="button" type="submit" value="SignUp" name="signup"/>
</td>
</tr>
<tr><td><div style="font-size:11px; color:#cc0000; margin-top:10px"><?php echo $error; ?></div></td></tr>
</form>
Here is a simple example of how to achieve that:
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$folder = "upload/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) {
echo "succesful upload, we have an image!";
$firstname = trim($_POST['fn']);
$lastname = trim($_POST['ln']);
$username = trim($_POST['un']);
$password = trim($_POST['pw']);
$confirmpassword= trim($_POST['cp']);
$stmt = $dbh->prepare("INSERT INTO registration (fname,lname,username,password, img_url) VALUES (?,?,?,?,?)");
$stmt->bindValue(1,$firstname,PDO::PARAM_STR);
$stmt->bindValue(2,$lastname,PDO::PARAM_STR);
$stmt->bindValue(3,$username,PDO::PARAM_STR);
$stmt->bindValue(4,$password,PDO::PARAM_STR);
$stmt->bindValue(5,$full_path,PDO::PARAM_STR);
if($stmt->execute()){
echo "YOUR REGISTRATION IS COMPLETED...";
}else{
echo 'YOUR REGISTRATION COULD NOT BE COMPLETED...';
}
} else {
echo "upload received! but process failed";
}
}else{
echo "upload failure ! Nothing was uploaded";
}
In the query I have included a field called img_url.
The PDO insert query is executed once the image is uploaded successfully.
You could just use a simple PHP upload() function. Here's an example http://www.w3schools.com/php/php_file_upload.asp
Related
i have some code that controls duplicate entries in particular the USER ID. it checks in the database at submit and if that USER ID exists already it gives that notification. now the problem is when i submit and if that USER ID entered already exists in the database, all the other entries on the form are cleared, prompting me to re_enter all the other details again. i find this annoying and retrogressive. i want some help on how better i can do it such that only the USER ID text box returns empty, keeping other details safe/unchanged or indeed alternatively keeping/buffering/caching all details previously entered so that i can also review the duplicate USER ID before changing it.
new_user.php
<h1 align="center">Create New User</h1>
<p align="center" style="color:#F00"><?php if(isset($_GET['dup'])){ echo "That User ID Already Exists!"; } ?> </p>
<form id="form1" method="post" action="add_user.php">
<table width="100%">
<tr>
<td width="204"><div align="right">User ID:</div></td>
<td width="286">
<input type="text" name="user_id" id="user_id" />
</td>
</tr>
<tr>
<td><div align="right">Full Names:</div></td>
<td>
<input type="text" name="fname" id="fname" />
</td>
</tr>
<tr>
<td><div align="right">Gender:</div></td>
<td><select id="sex" name="sex">
<option selected="selected" value="male">Male</option>
<option name="female">Female</option>
</select></td>
</tr>
<tr>
<td><div align="right">NRC Number:</div></td>
<td>
<input type="number" name="nrcno" id="nrcno" min="1" />
</td>
</tr>
<tr>
<td><div align="right">Phone Number:</div></td>
<td>
<input type="number" name="cellno" id="cellno" />
</td>
</tr>
<tr>
<td><div align="right">Email Address:</div></td>
<td>
<input type="email" name="emailad" id="emailad" />
</td>
</tr>
<tr>
<td><div align="right">Position Held:</div></td>
<td>
<input type="text" name="posh" id="posh" />
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="create" id="create" value="Add User" /></td>
</tr>
</table>
</form>
add_user.php
<?php
$user_id=$_POST['user_id'];
$fname = $_POST['fname'];
$sex= $_POST['sex'];
$name= $_POST['name'];
$nrcno = $_POST['nrcno'];
$cellno= $_POST['cellno'];
$emailad = $_POST['emailad'];
$posh = $_POST['posh'];
require("get_func.php");
checkID($id);
include("connect.php");
mysql_select_db("ceec", $con);
$query = "INSERT INTO user VALUES ('$user_id', '$fname', '$sex','$name', '$nrcno', '$cellno', '$emailad', '$posh')";
if (mysql_query($query)){
header("Location: success.php");
}
else {echo "Nada" . mysql_error(); }
mysql_close($con);
?>
get_func.php
<?php
function checkID($id){
include_once("connect.php");
mysql_select_db("ceec",$con);
$query = "SELECT * FROM user WHERE user_id = '$id'";
$result= mysql_query($query);
if($row = mysql_fetch_array($result))
{
header("Location: new_user.php?dup=true");
break;
}
else {}
}
?>
<input type="text" name="user_id" id="user_id"
<?php if(isset($_POST['user_id'])){echo htmlentities($_POST['user_id'];} ?>/>
I'm trying to upload 2 images at time. AVATAR and COVER IMG
When I select both avatar and cover and hit confirm, only avatar uploads
When I select only cover, cover uploads
Note that in mysql the name of the second image is displayed correctly. But missing in upload folder
My code:
<?php
define("_VALID_PHP", true);
require("../lib/config.ini.php");
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASS, DB_DATABASE);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$ID = $_GET['id'];
$name = $_POST['name'];
$category = $_POST['category'];
$sort = $_POST['sort'];
$tagline = $_POST['tagline'];
$exp = $_POST['exp'];
$company = $_POST['company'];
$country = $_POST['country'];
$links = $_POST['links'];
$created = $_POST['created'];
$add1 = $_POST['add1'];
$add2 = $_POST['add2'];
$add3 = $_POST['add3'];
$add4 = $_POST['add4'];
$add3 = $_POST['add5'];
$add4 = $_POST['add6'];
$notes = $_POST['notes'];
$uploaddir = '/data/web/creattium.com/sub/dir/admin/upload/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
$thegfi = $_FILES['userfile']['name'];
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
$uploadfile2 = $uploaddir . basename($_FILES['userfile2']['name']);
$thegfi2 = $_FILES['userfile2']['name'];
if (move_uploaded_file($_FILES['userfile2']['tmp_name'], $uploadfile2)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Upload failed";
}
mysqli_query($mysqli, "UPDATE yees SET name='$name',category='$category',sort='$sort',tagline='$tagline',exp='$exp',company='$company',country='$country',links='$links',created='$created',add1='$add1',add2='$add2',add3='$add3',add4='$add4',add5='$add5',add6='$add6',notes='$notes' WHERE id='$ID'");
if(!empty($_FILES['userfile']['name'])){
mysqli_query($mysqli, "UPDATE yees SET avatar='$thegfi' WHERE id='$ID'");
}else if(!empty($_FILES['userfile2']['name'])){
mysqli_query($mysqli, "UPDATE yees SET cover='$thegfi2' WHERE id='$ID'");
}
header("location: editemploy.php?id=".$ID."");
ADDED html
<form method="post" action="edit_yee.php?id=<?php echo $id;?>" enctype="multipart/form-data">
<?php
$a = mysql_query("SELECT * FROM yees WHERE id='$id'");
while($r = mysql_fetch_object($a)){
?>
<table cellpadding="0" cellspacing="0" class="forms">
<thead>
<tr>
<th colspan="2" class="left">Editing New Employee </th>
</tr>
</thead>
<tfoot>
<tr>
<td><input type="submit" class="button" value="Edit Employee"></td>
<td>Cancel</td>
</tr>
</tfoot>
<tbody>
<tr>
<th>Name:</th>
<td><input type="text" name="name" class="inputbox" size="55" value="<?php echo $r->name;?>"></td>
</tr>
<tr>
<th>Avatar:</th>
<td><input type="file" name="userfile" class="inputbox" style="width:337px;"></td>
</tr>
<tr>
<th>Cover:</th>
<td><input type="file" name="userfile2" class="inputbox" style="width:337px;"></td>
</tr>
<tr>
<th>Category:</th>
<td><input type="text" name="category"class="inputbox" size="55" value="<?php echo $r->category;?>"></td>
</tr>
<tr>
<th>Sort:</th>
<td><input type="text" name="sort"class="inputbox" size="55" value="<?php echo $r->sort;?>"></td>
</tr>
<tr>
<th>Tagline:</th>
<td><input type="text" name="tagline"class="inputbox" size="55" value="<?php echo $r->tagline;?>"></td>
</tr>
<tr>
<th>Exp:</th>
<td><input type="text" name="exp"class="inputbox" size="55" value="<?php echo $r->company;?>"></td>
</tr>
<tr>
<th>Company:</th>
<td><input type="text" name="company"class="inputbox" size="55" value="<?php echo $r->exp;?>"></td>
</tr>
<tr>
<th>Country:</th>
<td><input type="text" name="country"class="inputbox" size="55" value="<?php echo $r->country;?>"></td>
</tr>
<tr>
<th>Links:</th>
<td><input type="text" name="links"class="inputbox" size="55" value="<?php echo $r->links;?>"></td>
</tr>
<tr>
<th>Created:</th>
<td><input type="text" name="created"class="inputbox" size="55" value="<?php echo $r->created;?>"></td>
</tr>
<tr>
<th>Add1:</th>
<td><input type="text" name="add1"class="inputbox" size="55" value="<?php echo $r->add1;?>"></td>
</tr>
<tr>
<th>Add2:</th>
<td><input type="text" name="add2"class="inputbox" size="55" value="<?php echo $r->add2;?>"></td>
</tr>
<tr>
<th>Add3:</th>
<td><input type="text" name="add3"class="inputbox" size="55" value="<?php echo $r->add3;?>"></td>
</tr>
<tr>
<th>Add4:</th>
<td><input type="text" name="add4"class="inputbox" size="55" value="<?php echo $r->add4;?>"></td>
</tr>
<tr>
<th>Add5:</th>
<td><input type="text" name="add5"class="inputbox" size="55" value="<?php echo $r->add5;?>"></td>
</tr>
<tr>
<th>Add6:</th>
<td><input type="text" name="add6"class="inputbox" size="55" value="<?php echo $r->add6;?>"></td>
</tr>
<tr>
<th>Notes:</th>
<td><input type="text" name="notes"class="inputbox" size="55" value="<?php echo $r->notes;?>"></td>
</tr>
</tbody>
</table><br />
<?php }?>
</form>
<input type="file" name="userfile[]" class="inputbox" style="width:337px;">
Instead Of
<input type="file" name="userfile[]" class="inputbox" style="width:337px;" multiple>
Rename your inputs as:
<input type="file" name="userfile[]" class="inputbox" style="width:337px;">
Then, in php use:
$_FILES['userfile']['name'][0]
$_FILES['userfile']['name'][1]
...
More info here: http://www.php.net/manual/en/features.file-upload.multiple.php
Also check this:
Since PHP 5.2.12, the max_file_uploads configuration setting acts as a
limit on the number of files that can be uploaded in one request. You
will need to ensure that your form does not try to upload more files
in one request than this limit.
The problem here is that when I want to submit the form, it will return to its original state (empty form). There are 2 parts in the form where user have to type in the input and also to upload files.
Here is the form..
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Application for Paper Presentation</title>
<script>
function checkFile(grabObj)
{
var sFileName = grabObj.value;
var sFileExt = sFileName.split('.')[sFileName.split('.').length - 1].toLowerCase();
var iFileSize = grabObj.file[0].size;
var iConvert=(iFileSize/1048576).toFixed(2);
if (sFileExt!= "pdf" &&
sFileExt != "doc" &&
sFileExt != "docx") || iFileSize > 1048576)
{
txt="File type : "+ sFileExt +"\n\n";
txt+="Size: " + iConvert + " MB \n\n";
txt+="Please make sure your file is in pdf or doc format and less than 10 MB.\n\n";
alert(txt);
}
}
</script>
</head>
<body><br />
<form action="student_newSubmission.php" method="post" enctype="multipart/form-data">
<center>
<fieldset style="width:500px; background-color: #FFC"><legend align="center" style="font-size:24px">Application for Paper Presentation</legend>
<br>
<?php
$sql=oci_parse($conn,"SELECT * FROM student WHERE matricno='".$_SESSION['id']."'");
$result=oci_execute($sql);
$row=oci_fetch_array($sql,OCI_ASSOC+OCI_RETURN_NULLS);
$stfID=$row['SUPERVISOR'];
$stfID2=$row['COSUPERVISOR'];
//================================
$sql2=oci_parse($conn,"SELECT * FROM staff WHERE staffID='".$stfID."'") or die(oci_error());
$result2=oci_execute($sql2);
$row2=oci_fetch_array($sql2,OCI_ASSOC+OCI_RETURN_NULLS);
$stfname=$row2['STFNAME'];
$sql3=oci_parse($conn,"SELECT * FROM staff WHERE staffID='".$stfID2."'") or die(oci_error());
$result3=oci_execute($sql3);
$row3=oci_fetch_array($sql3,OCI_ASSOC+OCI_RETURN_NULLS);
$stfname2=$row3['STFNAME'];
?>
<table width="1023" cellpadding="2" cellspacing="2">
<tr>
<td width="160"><strong>First Name : </strong></td><td><?php echo $row['FNAME']; ?></td>
<td width="160"><strong>Last Name : </strong></td><td><?php echo $row['LNAME']; ?></td>
</tr>
<tr>
<td><strong>Sponsor : </strong></td><td width="374"><input name="sponsor" type="text" size="50" style="text-transform:uppercase" required value=""></td>
<td><strong>Admission Date : </strong></td><td width="309"><?php echo $row['ADMISSIONDATE']; ?></td>
</tr>
<tr>
<td><strong>Matric No : </strong></td><td width="374"><?php echo $row['MATRICNO']; ?><input type="hidden" name="matricno" value="<?php echo $row['MATRICNO']; ?>" /> </td>
<td><strong>Email Address :</strong></td><td width="309"><?php echo $row['EMAIL']; ?> </td>
</tr>
<tr>
<td><strong>Programme / Sem : </strong></td><td width="374"> <?php echo $row['PROGRAMME']; ?> / <?php echo $row['SEM']; ?>
<td><strong>Phone No.</strong></td><td width="309"><?php echo $row['PHONE']; ?> </td>
</tr>
<tr>
<td width="160"><strong>Field of Study : </strong></td><td colspan="3"><input name="field" type="text" size="140" style="text-transform: uppercase"> </td>
</tr>
<tr>
<td><strong>Supervisor : </strong></td><td width="374"><?php echo $stfname ?></td>
<td><strong>Co-supervisor : </strong></td><td width="309"><?php echo $stfname2; ?></td>
</tr>
</table>
<br />
<fieldset style="width:500px; background-color: #FFC"><legend align="center"> Program Detail </legend>
<table width="833" cellpadding="2" cellspacing="2">
<tr>
<td width="431"><strong> Title of Paper : </strong></td><td width="386"><input name="papertitle" type="text" size="50" style="text-transform: uppercase" required value=""></td>
</tr>
<tr>
<td><strong> Author/ Co. Author : <br />( Please separate using semicolon ' ; ' )</strong></td><td width="386"><textarea name="author" cols="38" rows="3" style="text-transform: uppercase; resize:none" required value=" "></textarea></td>
</tr>
<tr>
<td><strong> Title of Conference : </strong></td><td width="386"><input name="conftitle" type="text" size="50" style="text-transform: uppercase" required value=""></td>
</tr>
<tr>
<td><strong> Organizer : </strong></td><td width="386"><input name="organizer" type="text" size="50" style="text-transform: uppercase"></td>
</tr>
<tr>
<td><strong> Address : </strong></td><td width="386"><textarea name="address" cols="38" id="address" style="text-transform: uppercase; resize:none"></textarea></td>
</tr>
<tr>
<td><strong> Tel/Fax : </strong></td><td width="386"><input name="tel" type="text" size="50"></td>
</tr>
<tr>
<td><strong> Venue : </strong></td><td width="386"><input name="venue" type="text" size="50" style="text-transform: uppercase"></td>
</tr>
<tr>
<td><strong> Date : (dd/mm/YY)</strong></td><td width="386"><input name="confDate" type="text" size="50" style="text-transform: uppercase" ></td>
</tr>
<tr>
<td><strong> Conference / Journal Fees : </strong></td><td width="386"><input name="fee" type="text" size="50" style="text-transform: uppercase"></td>
</tr>
</table>
</fieldset>
<br />
</fieldset>
<br/>
<fieldset style="width:500px; background-color: #FFC"><legend align="center" style="font-size:24px">Upload file</legend>
<p style="color:#F00"> ( Please take note to name your files accordingly and save as .pdf or .doc ) </p>
<table width="809" cellpadding="2" cellspacing="2">
<tr>
<td width="341"><label for="file">Turnitin Similarity Report :</label></td>
<td width="452"><input type="file" name="userfile[]" id="turnitin" onchange="checkFile(this)" required value=""></td>
</tr>
<tr>
<td width="341"><label for="file">Paper Indexing :</label></td>
<td width="452"><input type="file" name="userfile[]" id="paperIndex" onchange="checkFile(this)" > <br />/ Link : <input type="text" name="paperindexurl" size="30" /></td>
</tr>
<tr>
<td width="341"><label for="file">Camera Ready Paper (full) :</label></td>
<td width="452"><input type="file" name="userfile[]" id="cameraReady" onchange="checkFile(this)" required value=""></td>
</tr>
<tr>
<td width="341"><label for="file">Blind Paper (withour author info) :</label></td>
<td width="452"><input type="file" name="userfile[]" id="blindPaper" onchange="checkFile(this)" required value=""></td>
</tr>
<tr><td colspan="2">========================= Extra for Journal Publication =========================</td></tr>
<tr>
<td width="341"><label for="file">Acceptance Letter from Publisher:</label></td>
<td width="452"><input type="file" name="userfile[]" id="acceptLetter" onchange="checkFile(this)"></td>
</tr>
<tr>
<td width="341"><label for="file">Publisher's Reviewers Report :</label></td>
<td width="452"><input type="file" name="userfile[]" id="reviewerReport" onchange="checkFile(this)"></td>
</tr>
<tr>
<td width="341"><label for="file">Paper Submitted Version :</label></td>
<td width="452"><input type="file" name="userfile[]" id="submittedVersion" onchange="checkFile(this)"></td>
</tr>
<tr>
<td width="341"><label for="file">Published Conference Paper :</label></td>
<td width="452">Link : <input type="text" name="confPaperurl" size="30"/></td>
</tr>
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input type="hidden" name="submissionDate" required value="<?php echo date("d-M-Y"); ?>" />
</table>
</fieldset><br />
<input type="submit" value="Submit the form" id="submit" align="center">
</center>
</form>
</body>
</html>
and here is the student_newSubmission.php
<?php
// Inialize session
session_start();
$conn = oci_connect("system","db","localhost/XE")or die(oci_error());
//require_once('connection.php');
?>
<?php
if(isset($_POST['submit']) && !empty($_POST['submit']))
{
$matricNo = $_POST['matricno'];
$submissionDate = $_POST['submissionDate'];
$sponsor = $_POST['sponsor'];
$field = $_POST['field'];
$papertitle = $_POST['papertitle'];
$author = $_POST['author'];
$conftitle = $_POST['conftitle'];
$organizer = $_POST['organizer'];
$address = $_POST['address'];
$tel = $_POST['tel'];
$venue = $_POST['venue'];
$confDate = $_POST['confDate'];
$fee = $_POST['fee'];
$paperIndexUrl = $_POST['paperindexurl'];
$confPaperUrl = $_POST['confPaperurl'];
$query = oci_parse($conn,"INSERT INTO submission(subID, matricNo, submissionDate, sponsor, field, papertitle, author, conftitle, organizer, orgaddress, orgtel, venue, confDate, fee, paperindexurl, confpaperurl) VALUES (seq_subID.nextval, '$matricNo', '$submissionDate', '$sponsor', '$field', '$papertitle', '$author', '$conftitle', '$organizer', '$address', '$tel', '$venue', '$confDate', '$fee', '$paperIndexUrl', '$confPaperUrl')") or die(oci_error());
$exe= oci_execute($query);
if($exe==1)
{
$query2 = oci_parse($conn, "SELECT subID FROM submission WHERE matricNo='".$matricNo."' ORDER BY submissionDate")or die(oci_error());
$exe2 = oci_execute($query2);
$row = oci_fetch_array($query2);
$subID = $row['SUBID'];
}
else
{
echo '<script type="text/javascript">';
echo 'alert("There was an error while uploading your form. Please try again.")';
echo '</script>';
}
if(isset($_POST['submit']) && $_FILES['userfile']['size'] > 0)
{
$count=0;
foreach ($_FILES['userfile']['name'] as $filename)
{
$fileName = $_FILES['userfile']['name'][$count];
$tmpName = $_FILES['userfile']['tmp_name'][$count];
$fileSize = $_FILES['userfile']['size'][$count];
$fileType = $_FILES['userfile']['type'][$count];
$fp = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = addslashes($content);
fclose($fp);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
}
$query3 = oci_parse($conn,"INSERT INTO upload (uploadID, uploadname, uploadtype, uploadsize, content, subID) VALUES (seq_uploadID.nextval, '$fileName', '$fileType', '$fileSize', '$content', '$subID')");
$exe3 = oci_execute($query) or die('Error, query failed');
$count=$count + 1;
}
//echo "<br>File $fileName uploaded<br>";
}
if ($exe3 == 1)
{
header('location:homeStudent.php');
echo '<script type="text/javascript">';
echo 'alert ("Successfully submit your form!")';
echo '</script>';
}
else
{
echo '<script type="text/javascript">';
echo 'alert("There was an error while uploading your form. Please try again.")';
echo '</script>';
}
}
?>
I've try comment the file upload process and just proceed with the type-in process.. but it still return without do anything. I hope it can show some error so I can fix. When it returns empty I also feel empty.
Can someone help me. I really dont know how to proceed.
You're using if(isset($_POST['submit']) and this is looking for a button named "submit", where you have:
<input type="submit" value="Submit the form" id="submit" align="center">
which should read as:
<input type="submit" name="submit" value="Submit the form" id="submit" align="center">
---------------------^^^^^^^^^^^^^
Cant work. If i understood your code right, you send the data via $_POST to student_newSubmission.php. Then you locate via "header" back to your old page, but you dont send the $_POST with it. You have to save the data send to the student_newSubmission and send it back to the other page. $_POST gets deleted after every script, you cant use it so save informations permanently. You have to use either $_COOKIE or $_SESSION for it.
I made a simple editing for to edit data in mysql, everything works fine except when I want to edit an input file type image it doesn't work, it doesn't give an error message it just doesn't edit anything and when I remove the input file type image it works.
and by editing an image I mean entering a new image the will replace the old image.
here is my code:
<?php
require("db.php");
$id = $_REQUEST['theId'];
$result = mysql_query("SELECT * FROM table WHERE id = '$id'");
$test = mysql_fetch_array($result);
$name = $test['Name'] ;
$email = $test['Email'] ;
$image = $test['Image'] ;
if (isset($_POST['submit']))
{
$name_save = $_POST['name'];
$email_save = $_POST['email'];
if (isset($_FILES['image']['tmp_name']))
{
$file = $_FILES['image']['tmp_name'];
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]["name"]);
$image_save ="photos/" . $_FILES["image"]["name"];
mysql_query("UPDATE table SET Name ='$name_save', Email ='$email_save',Image ='$image_save' WHERE id = '$id'") or die(mysql_error());
header("Location: index.php");
}
}
?>
<form method="post">
<table>
<tr>
<td>name:</td>
<td>
<input type="text" name="name" value="<?php echo $name ?>"/>
</td>
</tr>
<tr>
<td>email</td>
<td>
<input type="text" name="email" value="<?php echo $email ?>"/>
</td>
</tr>
<tr>
<td>image</td>
<td>
<input type="file" name="image" value="<?php echo $image ?>"/>
</td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="submit" value="submit" />
</td>
</tr>
</table>
In form enctype="multipart/form-data" is missing and in your form there is no type="file".
Give the below code and try.
<?php
require("db.php");
$id =$_REQUEST['theId'];
$result = mysql_query("SELECT * FROM table WHERE id = '$id'");
$test = mysql_fetch_array($result);
$name=$test['Name'] ;
$email= $test['Email'] ;
$image=$test['Image'] ;
if(isset($_POST['submit'])){
$name_save = $_POST['name'];
$email_save = $_POST['email'];
$image_save=$image //Added if image is not chose from the form post
if (isset($_FILES['image']['tmp_name'])) {
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]["name"]);
$image_save ="photos/" . $_FILES["image"]["name"];
}
mysql_query("UPDATE table SET Name ='$name_save', Email ='$email_save',Image ='$image_save' WHERE id = '$id'")
or die(mysql_error());
header("Location: index.php"); }
?>
<form method="post" enctype="multipart/form-data">
<table>
<tr>
<td>name:</td>
<td><input type="text" name="name" value="<?php echo $name ?>"/></td>
</tr>
<tr>
<td>email</td>
<td><input type="text" name="email" value="<?php echo $email ?>"/></td>
</tr>
<tr>
<td>image</td>
<td><input type="file" name="image" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
Moreover you should get the previous image value through sql and update if image is not chose while updating.
<tr>
<td>image</td>
<td><input type="file" name="image" ></td>
</tr>
You have to use input:type=file element instead of input:type=text in order to handle image file using $_FILES. Or you cannot get the image file. So your if statement returns false and nothing happens.
<form method="post" enctype="multipart/form-data">
<table>
<tr>
<td>name:</td>
<td><input type="text" name="name" value="<?php echo $name ?>"/></td>
</tr>
<tr>
<td>email</td>
<td><input type="text" name="email" value="<?php echo $email ?>"/></td>
</tr>
<tr>
<td>image</td>
<td><input type="file" name="image" /></td>
</tr>
<tr>
<td>image preview</td>
<td><img src="photos/<?php echo $image ?>" /></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="submit" /></td>
</tr>
</table>
</form>
I have a class called contacts. In this class I have a method called addContact(). The first statement execute correct, but it seems like it does not get the $db->lastInsertId(). Need some help please. Here is my code:
public function addContact($addcontactfirstname,$addcontactmiddlename,$addcontactlastname,$addcontactstreetnumber, $addcontactstreetname, $addcontactsuburb, $addcontactcity, $addcontactemailhome, $addcontactemailwork,$addcontacthomephone, $addcontactcellphone, $addcontactworkphone){
$addsuccessfully = true;
$addcontact_id = 0;
try {
$db = database::databaseConnect();
$stmt1 = $db->prepare('INSERT INTO personalinfo (firstname, middlename, lastname) VALUES (:addcontactfirstname, :addcontactmiddlename, :addcontactlastname)');
$stmt1->bindParam(':addcontactfirstname', $addcontactfirstname, PDO::PARAM_STR);
$stmt1->bindParam(':addcontactmiddlename', $addcontactmiddlename, PDO::PARAM_STR);
$stmt1->bindParam(':addcontactlastname', $addcontactlastname, PDO::PARAM_STR);
$successful1 = $stmt1->execute();
$addcontact_id = $db->lastInsertId();
if($successful1){
//$addcontact_id = $db->lastInsertId();
$successful1 = true;
$stmt2 = $db->prepare('INSERT INTO contactinfo (contact_id, streetnumber, streetname, suburbname, cityname, emailhome, emailwork, homephone, cellphone, workphone) VALUES (:addcontact_id, :addcontactstreetnumber, addcontactstreetname, :addcontactsuburb, :addcontactcity, :addcontactemailhome, :addcontactemailwork,:addcontacthomephone, :addcontactcellphone, :addcontactworkphone)');
$stmt2->bindParam(':addcontact_id', $addcontact_id, PDO::PARAM_INT);
$stmt2->bindParam(':addcontactstreetnumber', $addcontactstreetnumber, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactstreetname', $addcontactstreetname, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactsuburb', $addcontactsuburb, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactcity', $addcontactcity, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactemailhome', $addcontactemailhome, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactemailwork', $addcontactemailwork, PDO::PARAM_STR);
$stmt2->bindParam(':addcontacthomephone', $addcontacthomephone, PDO::PARAM_STR);
$stmt2->bindParam(':addcontactcellphone', $addcontactcellphone, PDO::PARAM_STR);
$stmt2->bindParam(':addcontacthomephone', $addcontactworkphone, PDO::PARAM_STR);
$successful2 = $stmt2->execute();
if($successful2){
$successful2 = true;
}
if(!$successful1 && !$successful2){
$addsuccessfully = false;
}
}
if($successful1 === true && $successful2 === true){
$addsuccessfully = true;
}
}
catch (PDOException $e) {
$addsuccessfully = false;
}
return $addsuccessfully;
}
I have a function that I call from my view page. Here is my function:
function addContact($addcontactfirstname,$addcontactmiddlename,$addcontactlastname,$addcontactstreetnumber, $addcontactstreetname, $addcontactsuburb, $addcontactcity, $addcontactemailhome, $addcontactemailwork,$addcontacthomephone, $addcontactcellphone, $addcontactworkphone){
global $addsuccessfully;
contacts::addContact($addcontactfirstname,$addcontactmiddlename,$addcontactlastname,$addcontactstreetnumber, $addcontactstreetname, $addcontactsuburb, $addcontactcity, $addcontactemailhome, $addcontactemailwork,$addcontacthomephone, $addcontactcellphone, $addcontactworkphone);
return $addsuccessfully;
}
And here is my page where I call the function. The page do say that the contact could not be added. I know the first query works as it the contact shows in the database, but it does not add the second bit into the contactinfo table of the database. Here is my view page:
<?php
/*The first thing that need to take place on this page is to ensure that the $admin value = 1.
* If the value is not 1 the user will get redirected to the home page. If the value of
* $admin = null, it then indicates that the user is not logged in. The system will then tell the
* user that he need to logon first, but also warn the user that if he is not an admin user he won't be
* allowed access to this page. This is to ensure that the user don't type the url address in
* his browser to try and access this page. This means that only admin users will be able to
* view this page while logged on and will be able to add new users. This will be an admin
* protected page. Protcted so the user must be logged in and and admin user.
*/
ini_set('display_errors', 1);
error_reporting(E_ALL);
require_once 'functions/functions.php';
checkLoggedIn(page::ADDCONTACT);
echo $message;
if ($pageID == 1){
require_once 'includes/adminmenu.php';
if($_POST){
$addcontactfirstname = $_POST['addcontactfirstname'];
$addcontactmiddlename = $_POST['addcontactmiddlename'];
$addcontactlastname = $_POST['addcontactlastname'];
$addcontactstreetnumber = $_POST['addcontactstreetnumber'];
$addcontactstreetname = $_POST['addcontactstreetname'];
$addcontactsuburb = $_POST['addcontactsuburb'];
$addcontactcity = $_POST['addcontactcity'];
$addcontactemailhome = $_POST['addcontactemailhome'];
$addcontactemailwork = $_POST['addcontactemailwork'];
$addcontacthomephone = $_POST['addcontacthomephone'];
$addcontactcellphone = $_POST['addcontactcellphone'];
$addcontactworkphone = $_POST['addcontactworkphone'];
$errors = array();
$homephonelength = false;
$cellphonelength = false;
$workphonelength = false;
//$addsuccessfully = true;
stripUserInput($addcontactfirstname,$addcontactmiddlename,$addcontactlastname,$addcontactstreetnumber,$addcontactstreetname,$addcontactsuburb,$addcontactcity,$addcontactemailhome,$addcontactemailwork,$addcontacthomephone,$addcontactcellphone,$addcontactworkphone);
if(empty($addcontactfirstname)){
$errors[] = 'First name can\'t be empty!';
}
if(empty($addcontacthomephone) && empty($addcontactcellphone) && empty($addcontactworkphone)){
$errors[] = 'You must enter at least one telephone number!';
}
if(!empty($addcontacthomephone)){
//$phonenumber = $addcontacthomephone;
$homephonelength = chechPhoneLenght($addcontacthomephone);
if($homephonelength === true){
$errors[] = 'The home phone number you entered is too short!';
}
}
if(!empty($addcontactcellphone)){
//$phonenumber = $addcontactcellphone;
$cellphonelength = chechPhoneLenght($addcontactcellphone);
if($cellphonelength === true){
$errors[] = 'The mobile phone number you entered is too short!';
}
}
if(!empty($addcontactworkphone)){
//$phonenumber = $addcontactworkphone;
$workphonelength = chechPhoneLenght($addcontactworkphone);
if($workphonelength === true){
$errors[] = 'The work phone number you entered is too short!';
}
}
if(!empty($addcontactemailhome)){
$email = $addcontactemailhome;
is_valid_email($email);
if (is_valid_email($email) === false){
$errors[] = 'You have entered an invalid home email address!';
}
}
if(!empty($addcontactemailwork)){
$email = $addcontactemailwork;
is_valid_email($email);
if(is_valid_email($email) === false){
$errors[] = 'You have entered an invalid work email address!';
}
}
if(empty($errors)){
//Add the contact
$addsuccessfully = addContact($addcontactfirstname,$addcontactmiddlename,$addcontactlastname,$addcontactstreetnumber, $addcontactstreetname, $addcontactsuburb, $addcontactcity, $addcontactemailhome, $addcontactemailwork,$addcontacthomephone, $addcontactcellphone, $addcontactworkphone);
if($addsuccessfully === true){
echo 'New contact added successfully!';
}else{
echo 'New contact could not be add. Please go back and try again!';
}
}else{
echo '<b>Please fix the following errors and try again!</b><br>';
foreach ($errors as $key => $error_message){
echo '<font color="red"><em>' . $error_message . '</font></em><br>';
}
?>
<h1>Add new contact</h1>
<p><em>Fields marked with <font color="red">*</font> must be completed.</em></p>
<form action="addcontact.php" method="post">
<table cellpadding="5">
<tr>
<td>
<b>First name:</b> <font color="red">*</font>
</td>
<td>
<input type="text" name="addcontactfirstname" value="<?php echo $addcontactfirstname; ?>" />
</td>
</tr>
<tr>
<td>
<b>Middle name:</b>
</td>
<td>
<input type="text" name="addcontactmiddlename" value="<?php echo $addcontactmiddlename; ?>" />
</td>
</tr>
<tr>
<td>
<b>Last name:</b>
</td>
<td>
<input type="text" name="addcontactlastname" value="<?php echo $addcontactlastname; ?>" />
</td>
</tr>
<tr>
<td>
<b>Street number:</b>
</td>
<td>
<input type="text" name="addcontactstreetnumber" value="<?php echo $addcontactstreetnumber; ?>" />
</td>
</tr>
<tr>
<td>
<b>Street name:</b>
</td>
<td>
<input type="text" name="addcontactstreetname" value="<?php echo $addcontactstreetname; ?>" />
</td>
</tr>
<tr>
<td>
<b>Suburb:</b>
</td>
<td>
<input type="text" name="addcontactsuburb" value="<?php echo $addcontactsuburb; ?>" />
</td>
</tr>
<tr>
<td>
<b>City:</b>
</td>
<td>
<input type="text" name="addcontactcity" value="<?php echo $addcontactcity; ?>" />
</td>
</tr>
<tr>
<td>
<b>Email (H):</b>
</td>
<td>
<input type="text" name="addcontactemailhome" value="<?php echo $addcontactemailhome; ?>" />
</td>
</tr>
<tr>
<td>
<b>Email (W):</b>
</td>
<td>
<input type="text" name="addcontactemailwork" value="<?php echo $addcontactemailwork; ?>" />
</td>
</tr>
<tr>
<td colspan="2">
<font color="blue"><em><b>NOTE:</b> You must enter at least one telephone number.</em><br> The number must include the area code e.g 065553322!</font>
</td>
</tr>
<tr>
<td>
<b>Phone (H):</b>
</td>
<td>
<input type="text" name="addcontacthomephone" value="<?php echo $addcontacthomephone; ?>" />
</td>
</tr>
<tr>
<td>
<b>Mobile:</b>
</td>
<td>
<input type="text" name="addcontactcellphone" value="<?php echo $addcontactcellphone; ?>" />
</td>
</tr>
<tr>
<td>
<b>Phone (W):</b>
</td>
<td>
<input type="text" name="addcontactworkphone" value="<?php echo $addcontactworkphone; ?>" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Add contact" value="<?php echo $addcontactfirstname; ?>" />
</td>
</tr>
</table>
</form>
<?php
}
}else{
?>
<h1>Add new contact</h1>
<p><em>Fields marked with <font color="red">*</font> must be completed.</em></p>
<form action="addcontact.php" method="post">
<table cellpadding="5">
<tr>
<td>
<b>First name:</b> <font color="red">*</font>
</td>
<td>
<input type="text" name="addcontactfirstname" />
</td>
</tr>
<tr>
<td>
<b>Middle name:</b>
</td>
<td>
<input type="text" name="addcontactmiddlename" />
</td>
</tr>
<tr>
<td>
<b>Last name:</b>
</td>
<td>
<input type="text" name="addcontactlastname" />
</td>
</tr>
<tr>
<td>
<b>Street number:</b>
</td>
<td>
<input type="text" name="addcontactstreetnumber" />
</td>
</tr>
<tr>
<td>
<b>Street name:</b>
</td>
<td>
<input type="text" name="addcontactstreetname" />
</td>
</tr>
<tr>
<td>
<b>Suburb:</b>
</td>
<td>
<input type="text" name="addcontactsuburb" />
</td>
</tr>
<tr>
<td>
<b>City:</b>
</td>
<td>
<input type="text" name="addcontactcity" />
</td>
</tr>
<tr>
<td>
<b>Email (H):</b>
</td>
<td>
<input type="text" name="addcontactemailhome" />
</td>
</tr>
<tr>
<td>
<b>Email (W):</b>
</td>
<td>
<input type="text" name="addcontactemailwork" />
</td>
</tr>
<tr>
<td colspan="2">
<font color="blue"><em><b>NOTE:</b> You must enter at least one telephone number.</em><br> The number must include the area code e.g 065553322!</font>
</td>
</tr>
<tr>
<td>
<b>Phone (H):</b>
</td>
<td>
<input type="text" name="addcontacthomephone" />
</td>
</tr>
<tr>
<td>
<b>Mobile:</b>
</td>
<td>
<input type="text" name="addcontactcellphone" />
</td>
</tr>
<tr>
<td>
<b>Phone (W):</b>
</td>
<td>
<input type="text" name="addcontactworkphone" />
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Add contact" />
</td>
</tr>
</table>
</form>
<?php
}
}
if ($pageID == 0){
return header('Location: ./');
}
?>
From the docs on PDO
string PDO::lastInsertId ([ string $name = NULL ] ) Returns the ID of
the last inserted row, or the last value from a sequence object,
depending on the underlying driver. For example, PDO_PGSQL() requires
you to specify the name of a sequence object for the name parameter.
Note:
This method may not return a meaningful or consistent result across different PDO drivers, because the underlying database may not even
support the notion of auto-increment fields or sequences.
Without seeing the schema there is no way to know but it is possible that you don't have an auto increment field in your database so the insert ID isn't being returned. In that case your second block of code would fail but the first would succeed.