Radio Button not working [closed] - php

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Looking at some tutorials I have added the radio button but for some reasons it is not working. When i submit the form the values are not entered into the database
Here is my code
case 'add':
if( $_POST['addbtn'] == 'Save' )
{
$name = '';
if(isset($_REQUEST['name']))
{
$name = $_REQUEST['name'];
}
$imageName = '';
$field = 'banner_images';
if($_FILES[$field ]['error'] == 0)
{
if($_FILES[$field]['tmp_name'] != '')
{
$uploaddir = "../inner_page_banner_images/";
$banner_images = $_FILES[$field]['name'];
$tag = "";
$Twidth = 980;
$Theight = 420;
#move_uploaded_file($_FILES[$field]['tmp_name'],$uploaddir.$_FILES[$field]['name']);
}
$site = '';
if(isset($_REQUEST['site']) == 'hino')
{
$site = $_REQUEST['checked'];
}
elseif(isset($_REQUEST['site']) == 'storm')
{
$site = $_REQUEST['checked'];
}
}
//--------------------------------------------------------------------------------------------------------
$Query = "INSERT INTO inner_banner SET ";
$Query .= "name = '".$name."',";
$Query .= "banner_images = '".$banner_images."'";
$Query .= "site = '".$site."'";
//echo $Query; die();
mysql_query($Query);
$_SESSION['msg'] = " New banner image uploaded successfully ";
#header("Location: inner_banner.php? module=inner_banner&action=view");
die();
}
include "add_banner.php";
break;
My Html Code
<form method="post" name="frm1" id="frm1" action="" autocomplete="off" enctype="multipart/form-data" onsubmit="return ValidateForm(this);" >
<table cellspacing="0" cellpadding="3" border="0" align="center" width="100%">
<tr>
<td width="18%">Banner Title</td>
<td width="1%">:</td>
<td><input type="text" name="name" id="name" size="40" value="" />
<span class="required">*</span> </td>
</tr>
<tr>
<td colspan="3" style=" background-color: #FFFFFF;"> </td>
</tr>
<tr>
<td valign="top">Banner Image </td>
<td valign="top">:</td>
<td><input type="file" name="banner_images" id="banner_images" size="20" />
</td>
</tr>
<tr>
<td colspan="3" style=" background-color: #FFFFFF;"> </td>
</tr>
<tr>
<td valign="top">Select:</td>
<td valign="top">:</td>
<td><input type="radio" value="hino" name="site" id="site" />
HINO
<input type="radio" value="storm" name="site" id="site" />
Storm
<span class="required">*</span>
</td>
</tr>
<tr>
<td colspan="3" style=" background-color: #FFFFFF;"> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="addbtn" value="Save" />
<input type='button' value='Cancel' onclick="document.location.href='inner_banner.php?module=inner_banner'" />
<input type="hidden" name="Validation" id="Validation" value="
Field=name|Alias=Banner Title|Validate=BLANK^
Field=banner_images|Alias=Banner Image|Validate=BLANK" />
can somebosy pls look into it why the values are not getting entered in the database

This line is missing a comma:
$Query .= "banner_images = '".$banner_images."'";
should be
$Query .= "banner_images = '".$banner_images."',";
As a sidenote, you are vulnerable to sql injection with your code, you might want to use prepared statements or at least mysql_real_escape_string

Shouldn't this:
if(isset($_REQUEST['site']) == 'hino')
{
$site = $_REQUEST['checked'];
}
elseif(isset($_REQUEST['site']) == 'storm')
{
$site = $_REQUEST['checked'];
}
be:
if(isset($_REQUEST['site']) == 'hino')
{
$site = $_REQUEST['site'];
}
elseif(isset($_REQUEST['site']) == 'storm')
{
$site = $_REQUEST['site'];
}
if so, a better way to code this is:
if(isset($_REQUEST['site']) && ($_REQUEST['site'] == 'hino' || isset($_REQUEST['site']) == 'storm') {
$site = $_REQUEST['site'];
}
Also:
$Query .= "name = '".$name."',";
$Query .= "banner_images = '".$banner_images."',";
$Query .= "site = '".$site."'";

Related

Cannot read my attributes in database

<?php
header("Content-type: text/html; charset=utf-8");
require('db_connect.php');
mysql_query("SET NAMES 'utf8'");
$food_name = $_POST['food_name'];
$restaurant_name = $_POST['restaurant_name'];
$food_type = $_POST['food_type'];
$food_price = $_POST['food_price'];
$food_description = $_POST['food_description'];
$uploadfile;
$dest_folder = "picture/";
$arr = array();
$count = 0;
if(!file_exists($dest_folder)){
mkdir($dest_folder);
}
foreach($_FILES["pictures"]["error"] as $key=> $error){
if($error == UPLOAD_ERR_OK){
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
$uploadfile = $dest_folder.$name;
move_uploaded_file($tmp_name,$uploadfile);
$arr[$count] = $uploadfile;
$count++;
}
}
$s2 = implode(',',$arr);
$sql = "insert into foodmenu
(food_name,restaurant_name,food_type,food_price,food_description,food_img)
values
('$food_name','$restaurant_name','$food_type','$food_price','$food_description','$s2',now())";
$result = mysql_query($sql);
if($result){
echo"<script>alert('Success')</script>";
echo"<script>location.href='admin.php'</script>";
} else {
echo"<script>alert('Failure')</script>";
echo"<script>history.back();</script>";
}
?>
May I know what is the error?
Because it cannot read my $food_name till $food_description.....and foreach($_FILES["pictures"]["error"] as &key=>$error).....
Can provide any solution for it?
<form action="add_action.php" method="post" name="send" onSubmit="return Check()" enctype="multipart/form-data">
Food Name :
Food Description :
Food Price :
$
Food Type :
---
appertizers
main courses
desserts
Restaurant Name :
Images :
<input name="btnSubmit" type="submit" class="inputButton" id="btnSubmit" value=" ADD " align="middle">
</form>
<div class="listbox">
<div class="menu">
<br><br>
<form action="add_action.php" method="post" name="send" onSubmit="return Check()" enctype="multipart/form-data">
<table border="0" cellpadding="2" cellspacing="0" width="100%">
<tr>
<td width="180" align="right">Food Name :</td>
<td width="150">
<input name="food_name" type="text" class="food_namelist" style="width:300px;">
</td>
</tr>
<tr>
<td width="100" align="right">Food Description :</td>
<td width="222">
<textarea name="food_description" class="food_namelist" rows="3" style="height:100px; width:500px;"></textarea>
</td>
</tr>
<tr>
<td width="100" align="right">Food Price :</td>
<td width="222">
$
<tr>
<td width="100" align="right">Food Type :</td>
<td width="222">
<select name="food_type">
<option value="" selected>---</option>
<option value="appertizers">appertizers</option>
<option value="main courses">main courses</option>
<option value="desserts">desserts</option>
</select>
</td>
</tr>
<tr>
<td width="180" align="right">Restaurant Name :</td>
<td width="222">
<input name="restaurant_name" type="text" class="food_namelist" style="width:300px;">
</td>
</tr>
<tr>
<td align="right">Images :</td>
<td style=" ">
<input type="uploadfile" name="pictures[]" />
</td>
</tr>
</table>
<input name="btnSubmit" type="submit" class="inputButton" id="btnSubmit" value=" ADD " align="middle">
</form>
</div>
</div>
There's lot of things that may happen wrong in your form.
First one is, It is possible that your form input name and your &_POST['xyz'] names are not matching.
Second one is, Please never forget to wrap your post values in htmlspecialchars like $food_name = htmlspecialchars($_POST['food_name']);
Neither your values are thrown for injection threats.
So after two above mentioned modifications, if you still face the problem, please attach your form html.
i'm excluding your db_connect.php. Please edit the details as your own.
sql code::'
<?php
define("DB_DSN","mysql:hostname=localhost;dbname=tumy");
define("DB_USR","root");
define("DB_PASS","");
$conn = new PDO(DB_DSN,DB_USR,DB_PASS);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$food_name = htmlspecialchars($_POST['food_name']);
$restaurant_name = htmlspecialchars($_POST['restaurant_name']);
$food_type = htmlspecialchars($_POST['food_type']);
$food_price = htmlspecialchars($_POST['food_price']);
$food_description = htmlspecialchars($_POST['food_description']);
$date = now();//create a column in your database named "date(or as wish)
$dest_folder = "picture/";
$arr = array();
$count = 0;
if(!file_exists($dest_folder)){
mkdir($dest_folder);
}
foreach($_FILES["pictures"]["error"] as $key=> $error){
if($error == UPLOAD_ERR_OK){
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
$name = $_FILES["pictures"]["name"][$key];
$uploadfile = $dest_folder.$name;
move_uploaded_file($tmp_name,$uploadfile);
$arr[$count] = $uploadfile;
$count++;
}
}
$s2 = implode(',',$arr);
$sql = "INSERT INTO foodmenu
(food_name,restaurant_name,food_type,food_price,food_description,food_img,date)
VALUES
('$food_name','$restaurant_name','$food_type','$food_price','$food_description','$s2','$date')";
$st = $conn->prepare($sql);
if($st->execute()){
echo"<script>alert('Success')</script>";
echo"<script>location.href='admin.php'</script>";
} else {
echo"<script>alert('Failure')</script>";
echo"<script>history.back();</script>";
}
$conn = null;
?>`

Dealing with POST variables

I have a problem with my PHP-Fusion infusion (plugin). I created a POST form, but when I try to call those POST variables they do not echo (I plan adding them to a database). My code:
$id_ucznia = $_GET["id"];
$result2 = dbquery("SELECT id,imiona,nazwiska,dom,punkty FROM ".DB_ZAPISY." WHERE (funkcja = 'Student') AND (id = '".$id_ucznia."')");
if (dbrows($result2)) {
while ($data2 = dbarray($result2)) {
echo '<form method="POST" action="">
<input type="hidden" name="uczen_id" value="'.$id_ucznia.'">
<table border="0" align="center">
<tr><td align="right">Imiona ucznia: </td> <td align="left"><input type="text" class="input" name="imiona" value="'.$data2["imiona"].'" disabled></td></tr>
<tr><td align="right">Nazwiska ucznia: </td> <td align="left"><input type="text" class="input" name="nazwiska" value="'.$data2["nazwiska"].'" disabled></td></tr>
<tr><td align="right">Dom ucznia: </td> <td align="left"><input type="text" class="input" name="dom" value="'.$data2["dom"].'" disabled></td></tr>
<tr><td align="right">Aktualne punkty: </td> <td align="left"><input type="text" class="input" name="punkty_start" value="'.$data2["punkty"].'" disabled></td></tr>
<tr><td align="right">Punkty do dodania: </td> <td align="left"><input type="text" class="input" name="ile"></td></tr>
<tr><td align="right">Uzasadnienie: </td> <td align="left"><input type="text" class="input" name="zaco" maxlength="500"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" class="button" name="dodaj_punkty" value="Dodaj punkty"></td></tr>
</table>
</form>
';
}
}
if (isset($_POST['dodaj_punkty'])) {
$imiona = $_POST["imiona"];
$nazwiska = $_POST['nazwiska'];
$dom = $_POST['dom'];
$punkty_start = $_POST['punkty_start'];
$ile = $_POST['ile'];
$zaco = $_POST['zaco'];
$punkty_uczen_end = $punkty_start + $ile;
$kto_akcja = $userdata['user_name'];
$kto_id = $userdata['user_id'];
$komu = ''.$imiona.' '.$nazwiska.'';
$dzis = date("Y-m-d H:i:s");
$result3 = dbquery("SELECT id,nazwa,punkty FROM ".DB_DOMY." WHERE `nazwa` = '".$dom."'");
if (dbrows($result3)) {
while ($data3 = dbarray($result3)) {
$id_domu = $data3["id"];
$nazwa = $data3["nazwa"];
$punkty_dom_start = $data3["punkty"];
}
}
$punkty_dom_end = $punkty_dom_start + $ile;
echo 'Dla ucznia ('.$imiona.$nazwiska.') dodano: '.$punkty_uczen_end.' a dla domu ('.$id_domu.$nazwa.'): '.$punkty_domu_end.' ';
$resulta = dbquery("UPDATE ".DB_DOMY." SET punkty = '{$punkty_dom_end}' WHERE id = '{$id_domu}';");
$resultb = dbquery("INSERT INTO ".DB_RANKING_DOMOW." (ile, akcja, kto, komu, opis) VALUES ('{$ile}','+','{$kto_akcja}','{$komu}','{$zaco}');");
$resultc = dbquery("UPDATE ".DB_ZAPISY." SET punkty = '{$punkty_uczen_end}' WHERE id = '{$uczen_id}';");
$resultd = dbquery("INSERT INTO ".DB_RU." (kiedy, kto_dane, kto_id, komu, ile, zaco, co) VALUES ('{$dzis}','{$kto_akcja}','{$kto_id}','{$komu}','{$ile}', '{$zaco}', '+');");
redirect(FUSION_SELF.$aidlink."&wykonane");
}
HTML form input elements are set to disabled thus their values will not be submitted. Maybe a readonly or hidden -attribute was intended.
Provided code has some variables (redundantly) copied before use. Concerning content management system uses this practice to save a sanitized copy of form-posted data (to prevent SQL injection).

php stop of statement in form validation

i am a beginner and am trying to make a form validation with PHP. i want to check if one of the inputs is empty, the form says that the empty input is required.
I show the php script behind.
<?php
$titleErr = $authorErr = $keywordsErr = $contentErr = "";
$title = $author = $keywords = $content = "";
if (empty($_POST["submit"])) {
if(empty($_POST["title"])){
$titleErr = "title is required";
}
if(empty($_POST["author"])){
$authorErr = "author name is required";
}
if(empty($_POST["keywords"])){
$keywordsErr = "keywords are required";
}
if(empty($_POST["content"])){
$contentErr = "This field is required";
}
}
?>
<form method="post" action="insert_post.php">
<table width="600" align="center" border="10">
<tr>
<td align="center" bgcolor="yellow" colspan="6"><h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="38">
<span style="color:red;"><?php echo $titleErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author" size="38">
<span style="color:red;"><?php echo $authorErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Keywords:</td>
<td><input type="text" name="keywords" size="38">
<span style="color:red;"><?php echo $keywordsErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Image:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td align="right">Post Content</td>
<td><textarea name="content" cols="30" rows="15"></textarea>
<span style="color:red;"><?php echo $contentErr; ?></span>
</td>
</tr>
<tr>
<td align="center" colspan="6"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
<?php
include("includes/connect.php");
if(isset($_POST['submit'])){
$title = $_POST['title'];
$date = date('d-m-Y');
$author = $_POST['author'];
$keywords = $_POST['keywords'];
$content = $_POST['content'];
$image = $_FILES['image'] ['name'];
$image_tmp = $_FILES['image'] ['tmp_name'];
move_uploaded_file($image_tmp, "../images/$image");
$query = "INSERT INTO posts (post_title, post_date, post_author, post_keywords, post_image, post_content) VALUES('$title', '$date', '$author', '$keywords', '$image', '$content')";
$result = mysqli_query($conn, $query);
if($query){
echo"<center><h1>Post Published Succesfully!</h1></center>";
}
}
?>
The problem is i want to stop the scrit if the inputs are empty but i can't use functions like: exit() and break;.
and if i submit, the form sends empty values to the database :C.
how can i solve this problem?
We make use of session variables which temporarily stores data locally. To use sessions we must always start sessions by session_start() at the start of every page to be able to access the variables. Now we can store data and pass it to whatever page we want to without having to send it - we just store it and then grab it.
index.php
<?php
session_start();
$titleErr = $authorErr = $keywordsErr = $contentErr = "";
$title = $author = $keywords = $content = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["title"])){
$titleErr = "title is required";
}
if(empty($_POST["author"])){
$authorErr = "author name is required";
}
if(empty($_POST["keywords"])){
$keywordsErr = "keywords are required";
}
if(empty($_POST["content"])){
$contentErr = "This field is required";
}
if(!empty($_POST["title"]) && !empty($_POST["author"]) && !empty($_POST["keywords"]) && !empty($_POST["content"])){
$_SESSION["title"] = $_POST["title"];
$_SESSION["author"] = $_POST["author"];
$_SESSION["keywords"] = $_POST["keywords"];
$_SESSION["content"] = $_POST["content"];
$_SESSION["image"] = $_FILES["image"];
header("location: insert_post.php");
exit();
}
}
?>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<table width="600" align="center" border="10">
<tr>
<td align="center" bgcolor="yellow" colspan="6"><h1>Insert New Post Here</h1></td>
</tr>
<tr>
<td align="right">Post Title:</td>
<td><input type="text" name="title" size="38" value="<?php if(isset($_POST['title'])){ echo $_POST['title']; }; ?>">
<span style="color:red;"><?php echo $titleErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Author:</td>
<td><input type="text" name="author" size="38" value="<?php if(isset($_POST['author'])){echo $_POST['author']; }; ?>">
<span style="color:red;"><?php echo $authorErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Keywords:</td>
<td><input type="text" name="keywords" size="38" value="<?php if(isset($_POST['keywords'])){echo $_POST['keywords']; }; ?>">
<span style="color:red;"><?php echo $keywordsErr; ?></span>
</td>
</tr>
<tr>
<td align="right">Post Image:</td>
<td><input type="file" name="image"></td>
</tr>
<tr>
<td align="right">Post Content</td>
<td><textarea name="content" cols="30" rows="15" value="<?php if(isset($_POST['content'])){echo $_POST['content']; }; ?>"></textarea>
<span style="color:red;"><?php echo $contentErr; ?></span>
</td>
</tr>
<tr>
<td align="center" colspan="6"><input type="submit" name="submit" value="Publish Now"></td>
</tr>
</table>
</form>
</body>
</html>
insert_post.php
<?php
session_start();
include("includes/connect.php");
$title = $_SESSION['title'];
$author = $_SESSION['author'];
$keywords = $_SESSION['keywords'];
$content = $_SESSION['content'];
$date = date('d-m-Y');
$image = $_SESSION['image']['name'];
$image_tmp = $_SESSION['image']['tmp_name'];
move_uploaded_file($image_tmp, "../images/$image");
$query = "INSERT INTO posts (post_title, post_date, post_author, post_keywords, post_image, post_content) VALUES('$title', '$date', '$author', '$keywords', '$image', '$content')";
$result = mysqli_query($conn, $query);
if($query){
echo"<center><h1>Post Published Succesfully!</h1></center>";
}
else{
echo "<center><h1>Error! Post was not published!</h1></center>";
}
echo $title . " " . $author . " " . $keywords . " " . $content;
?>
Btw, you should be using prepared statements for your database inserts to prevent SQL-injections. Read more about it here.
You don't hAve to Break the Script using the Exit Funktion. Just prove if the error variables aren't empty and only in the Case when they aren't empty send a dB-request.
Chenge these lines:
include("includes/connect.php");
if(isset($_POST['submit'])){
to
include("includes/connect.php");
if( isset($_POST['submit']) //Fix here, it will only insert if all error message
&& empty($titleErr) //are empty.
&& empty($authorErr)
&& empty($keywordsErr)
&& empty($contentErr) ){
Edit
And also change this line
if (empty($_POST["submit"])) {
To
if (isset($_POST["submit"])) {
On the init of your script. The empty function will return true if you did not submit the page, that's why you are hving the error messages.

How to keep input in fields after form submitted for further update

I wonder is it possible to keep the user input inside form field after form submitted, so that the user can update the entry. I've a html registration form [with some JS validation], then a php file to insert data to sql & meanwhile display back the inserted data in a table view. i also include the form's html code in php file so i can see the form after being submitted. but i couldn't keep the data in the field after form submitted! 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>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="insert.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Submit" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
</body>
</html>
here is the insert.php file:
<!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>
<script type="text/javascript">
<!--
function validateNum(evt) {
var theEvent = evt;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
function validate(evt){
if( document.myForm.ic.value == ""){
alert( "IC Number cann't be empty!" );
document.myForm.ic.focus() ;
return false;}
else if(isNaN( document.myForm.ic.value ) || document.myForm.ic.value.length != 12){
evt.preventDefault();
alert( "Please provide your correct IC Number!" );
document.myForm.ic.focus() ;
return false;}
if( document.myForm.name.value == "") {
alert( "Name cann't be empty!" );
document.myForm.name.focus() ;
return false;
}
if( document.myForm.contact.value == ""){
alert( "Contact number cann't be empty!");
document.myForm.contact.focus() ;
return false;
} else if(isNaN( document.myForm.contact.value ))
{
evt.preventDefault();
alert( "Please provide your correct Contact Number!" );
document.myForm.contact.focus() ;
return false;
}
if( document.myForm.address.value == "" ){
alert( "Please provide your Address!" );
document.myForm.address.focus() ;
return false;
}
}
//-->
</script>
</head>
<style type="text/css">
h2 {
color: #06C;
}
body {
background-color: #FFC;
}
</style>
<body>
<form name="myForm" method="post" action="update.php" onsubmit="return(validate(event));">
<div align="center"><br>
<table width="453" border="0">
<tr>
<th colspan="4" bgcolor="#99FFFF" scope="col">
<h3>Workshop Name: PHP! </h3></th>
</tr>
<tr bgcolor="#99FF99">
<td width="142"> IC Number</td>
<td width="15"><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="ic" type="text" id="ic" maxlength="12" size="45" onkeypress='validateNum(event)'/>
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Full Name</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="name" type="text" id="name" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td>Contact No.</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="contact" type="text" id="contact" size="45" onkeypress='validateNum(event)' />
</div></td>
</tr>
<tr bgcolor="#99FFFF">
<td>Email</td>
<td><div align="center">:</div></td>
<td colspan="2"><div align="right">
<input
name="mail" type="text" id="mail" size="45"/>
</div></td>
</tr>
<tr bgcolor="#99FF99">
<td height="60">Address</td>
<td><div align="center">:</div></td>
<td colspan="2">
<div align="right">
<textarea name="address" id="address" cols="35" rows="3"></textarea>
</div>
</td>
</tr>
<tr bgcolor="#99FFFF">
<td colspan="2"> </td>
<td width="231"><input type="reset" value="Clear" /></td>
<td width="47"><div align="right">
<input type="submit" value="Update" />
</div></td>
</tr>
</table>
<br>
</div>
</form>
<br>
</div>
</form>
<div align="center">
<?php
if (!mysql_connect('localhost', 'root', '')) {
echo "Connected";
}
mysql_select_db("workshop");
// Get values from form
$ic = mysql_real_escape_string($_POST['ic']);
$name = mysql_real_escape_string($_POST['name']);
$contact = mysql_real_escape_string($_POST['contact']);
$mail = mysql_real_escape_string($_POST['mail']);
$address = mysql_real_escape_string($_POST['address']);
if (staff_detail_exist($ic) == "available") {
insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype);
echo "<p style='text-align:center; color:green;'>" . "Workshop application successful! You will be notified shortly via E-mail after confirmation! Thank You!";
} else if (staff_detail_exist($ic) == "exist") {
echo "<p style='text-align:center; color:red;'>" . "Record already exists! Please enter another Staff ID. Thank You!" . "</p>";
}
function insert_staff_detail($ic, $name, $contact, $mail, $address, $paytype) {
$sql = "INSERT INTO apply (staffid, staffname, staffno, staffemail, staffaddress, paytype) VALUES ('$ic', '$name', '$contact', '$mail', '$address','$paytype')";
mysql_query($sql);
}
function staff_detail_exist($ic) {
$result = null;
$sql = "SELECT * FROM apply WHERE staffid = '$ic'";
$data = mysql_query($sql);
if (mysql_num_rows($data) == 0) {
$result = "available";
} else {
$result = "exist";
}
return $result;
}
$staffid = $_POST['ic'];
$con = mysql_connect("localhost", "root", "");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("workshop", $con);
$result = mysql_query("SELECT * FROM apply where staffid = '$ic'");
echo "<table width=400 border=1 cellpadding=0 align=center>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<th>Staff/IC Number: </th><td>" . "<center>" . $row['staffid'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Name: </th><td>" . "<center>" . $row['staffname'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Email: </th><td>" . "<center>" . $row['staffemail'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Contact No.: </th><td>" . "<center>" . $row['staffno'] . "</center>" . "</td>";
echo "</tr>";
echo "<th>Address: </th><td>" . "<center>" . $row['staffaddress'] . "</center>" . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
</body>
</html>
I've tried to add like value="<? echo "$row['staffid']"?>" in the form's field at php file but no luck! I've only basic in php. So, any help? thank you!
thanks all, its finally working :) i've used value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" inside the input tag. so, its like: <input type="text" name="myField" value="<?php echo isset($_POST['myField']) ? $_POST['myField'] : 'myField_db' ?>" /> where myField is input name & myField_db is the column name from database.
Take the form posted values just above your html code like this
<?php
if (isset($_POST["submit"]) && $_POST["submit"]=='Submit') {
$name=$_POST["name"];
}
?>
And echo it in your html form.
<input name="name" type="text" id="name" size="45" value="<? echo $name?>"/>
I've used this function a few times; quite handy
function getPost($field){
return (isset($_POST[$field]) && $_POST[$field] != "" ? $_POST[$field] : "");
}
Usage
<input type="text" name="contact" value="<?php echo getPost("contact"); ?>" />
This is for the cases where a user submits information and is for some reason sent back to the form again - perhaps their entries didn't pass PHP validation, for example.

You have an error in your SQL syntax;

G'Day
I have a php page that I want to edit an entry but for the life of me I can not figure out why it is coming up with this erro.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= po_postcode = '4060', email ='-', phone = '732997688', fax = '' WHERE id='1'' at line 1
HELP I am desperate and going insane. (Similar Code works on another page but not this one)....
Can someone PLEASE HELP.
{
<?php
/*
EDIT.PHP
Allows user to edit specific entry in database
*/
// creates the edit record form
// since this form is used multiple times in this file, I have made it a function that is easily reusable
function renderForm($id, $name, $po_street, $po_suburb, $po_state, $po_postcode, $email, $phone, $fax, $error)
{
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Edit Record</title>
</head>
<body>
<table width="347" border="0" align="center">
<tr valign="baseline">
<td align="right" nowrap="nowrap"><p align="center"><img src="hartwell_banner.JPG" width="624" height="134" /></p>
</tr>
</table>
<table align="center">
<tr valign="baseline">
<td width="290" align="right" nowrap="nowrap"><div align="left"><h2 align="left"><p align="left">Enter a New Contact</p></h2></div></td>
<td width="290" align="center" nowrap="nowrap"><div align="left"><h2 align="center"><p align="center">Return to Index</p>
</h2>
</div></td>
</tr>
</table>
<form action="" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<table align="center">
<tr valign="baseline">
<td width="98" align="right" nowrap="nowrap"><div align="left">ID:</div></td>
<td width="329"><input type="text" name="id" value="<?php echo $id; ?>" size="40" readonly = "readonly" /> * </td>
</tr>
<tr valign="baseline">
<td width="98" align="right" nowrap="nowrap"><div align="left">Name:</div></td>
<td width="329"><input type="text" name="name" value="<?php echo $name; ?>" size="40" /> * </td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"><div align="left">Postal Street </div></td>
<td><input type="text" name="po_street" value="<?php echo $po_street; ?>" size="40" /> * </td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"><div align="left">Postal Suburb</div></td>
<td><Input type ="text" name="po_suburb" value="<?php echo $po_suburb; ?> " size="30" maxlength="50" >*</td>
<tr valign="baseline">
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"><div align="left">State</div></td>
<td><Input type ="text" name="po_state" value="<?php echo $po_state; ?>" size="5" maxlength="3" /> * </td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"><div align="left">Postal Postcode</div></td>
<td><Input type ="text" name="po_postcode" value="<?php echo $po_postcode; ?>" size="5" maxlength="4"/> * </td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"><div align="left">Email:</div></td>
<td><input type="text" name="email" value="<?php echo $email; ?>" size="40" /> * </td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"><div align="left">Phone:</div></td>
<td><input name="phone" type="text" value="<?php echo $phone; ?>" size="12" maxlength="10" /> * </td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"><div align="left">Fax:</div></td>
<td><input name="fax" type="text" value="<?php echo $fax; ?>" size="12" maxlength="10" /></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right"> </td>
<td> <input type="submit" name="submit" value="Submit"> * Denotes Required Field<?php
// if there are any errors, display them
if ($error != '')
{
echo '<div style="padding:4px; border:1px solid red; color:red;">'.$error.'</div>';
}
?> </td>
</tr>
<tr valign="baseline">
<td colspan="2" align="right" nowrap="nowrap"><div align="center"><img src="hartwell_costs.JPG" alt="" width="340" height="147" /></div></td>
</tr>
</table>
</form>
</body>
</html>
<?php
}
// check if the form has been submitted. If it has, process the form and save it to the database
if (isset($_POST['submit']))
{
// confirm that the 'id' value is a valid integer before getting the form data
if (isset($_POST['id']))
{
// get form data, making sure it is valid
$id = mysql_real_escape_string(htmlspecialchars($_POST['id']));
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$po_street = mysql_real_escape_string(htmlspecialchars($_POST['po_street']));
$po_suburb = mysql_real_escape_string(htmlspecialchars($_POST['po_suburb']));
$po_state = mysql_real_escape_string(htmlspecialchars($_POST['po_state']));
$po_postcode = mysql_real_escape_string(htmlspecialchars($_POST['po_postcode']));
$email = mysql_real_escape_string(htmlspecialchars($_POST['email']));
$phone = mysql_real_escape_string(htmlspecialchars($_POST['phone']));
// check that firstname/lastname fields are both filled in
if ($id == '' || $name == '' || $po_street == '' || $po_suburb == ''|| $po_state == '' || $po_postcode == ''|| $email == '' || $phone == '')
{
// generate error message
$error = 'ERROR: Please fill in all required fields!';
//error, display form
renderForm($id, $name, $po_street, $po_suburb, $po_state, $po_postcode, $email, $phone, $fax, $error);
}
else
{
// save the data to the database
mysql_select_db($database_hartwell, $hartwell);
mysql_query("UPDATE contact SET id= '$id', name='$name', po_street ='$po_street', po_suburb = '$po_suburb', po_state = '$po_state', = po_postcode = '$po_postcode', email ='$email', phone = '$phone', fax = '$fax' WHERE id='$id'")
or die(mysql_error());
// once saved, redirect back to the view page
header("Location: view.php");
}
}
else
{
//if the 'id' isn't valid, display an error
echo 'ID Not Valid!';
}
}
else
// if the form hasn't been submitted, get the data from the db and display the form
{
// get the 'id' value from the URL (if it exists), making sure that it is valid (checing that it is numeric/larger than 0)
if (isset($_GET['id']) && is_numeric($_GET['id']) && $_GET['id'] > 0)
{
// query db
$id = $_GET['id'];
mysql_select_db($database_hartwell, $hartwell);
$result = mysql_query("SELECT * FROM contact WHERE id=$id")
or die(mysql_error());
$row = mysql_fetch_array($result);
// check that the 'id' matches up with a row in the databse
if($row)
{
// get data from db
$id = $row['id'];
$name = $row['name'];
$po_street = $row['po_street'];
$po_suburb = $row['po_suburb'];
$po_state = $row['po_state'];
$po_postcode = $row['po_postcode'];
$email = $row['email'];
$phone = $row['phone'];
$fax = $row['fax'];
// show form
renderForm($id, $name, $po_street, $po_suburb, $po_state, $po_postcode, $email, $phone, $fax,'');
}
else
// if no match, display result
{
echo "No results!";
}
}
else
// if the 'id' in the URL isn't valid, or if there is no 'id' value, display an error
{
echo 'No ID Value!';
}
}
?>
The error is right there in your query, just like the error message says:
, = po_postcode = '$po_postcode',
^
|
+ this doesn't belong here
remove the equal sign here:
'$po_state', = po_postcode
mysql_query("UPDATE contact SET id= '$id', name='$name', po_street ='$po_street', po_suburb = '$po_suburb', po_state = '$po_state', po_postcode = '$po_postcode', email ='$email', phone = '$phone', fax = '$fax' WHERE id='$id'")
So the problem is here = po_postcode = '$po_postcode',

Categories