I'm working on a login/registration form for a school assignment, and I can't get the forms to retain any information when submitted. Whether the information is correct or incorrect, the form returns with blank values after being submitted. Here is the form code:
<?php
ini_set("display_errors","on");
error_reporting(E_ALL | E_STRICT);
$labels = array("email" => "Email Address:",
"password" => "Password:");
$submit = "Log In";
?>
<?php
echo "<form method='post'>";
foreach($labels as $field => $label)
{
if($field != "password")
{
echo "<div><label for='$field'>$label</label>
<input type='text' name='$field' id='$field' width='40%' maxlength='40' value='".#$$value."'></div>";
}
else
{
echo "<div><label for='$field'>$label</label>
<input type='password' name='$field' id='$field' width='40%' maxlength='20' value='".#$$value."'</div>";
}
}
echo "<div><input type='hidden' name='submitted' value='yes'>
<input type='submit' value='$submit' name='submit'></div>";
?>
The following is the validation code:
<?php
if(isset($_POST['submitted']) and $_POST['submitted'] == 'yes')
{
foreach($_POST as $field => $value)
{
if(empty($value))
{
$error_array[] = $field;
}
else
{
$good_data[$field] = strip_tags(trim($value));
}
}
if(#sizeof($error_array) > 0)
{
$message = "<p class='error'>Login information is incorrect</p>";
echo $message;
extract($good_data);
include('login.php');
exit();
}
else
{
foreach($good_data as $field => $value)
{
$clean_data[$field] = mysqli_real_escape_string($cxn,$value);
}
$sql = "select * from customerdata where email='$clean_data[email]' and password='$clean_data[password]'";
$result = mysqli_query($cxn,$sql) or die("<p class='error'>Couldn't connect to server.</p>");
$row = mysqli_fetch_assoc($result);
if ($row > 0)
{
$sql2 = "update user_login set login_time=CURRENT_TIMESTAMP where email='$clean_data[email]'";
$result2 = mysqli_query($cxn,$sql2) or die("<p class='error'>Couldn't connect to server.</p>");
$_SESSION['auth'] = "yes";
header("Location: catalog.php");
}
else
{
echo $message;
extract($clean_data);
include('login.php');
exit();
}
}
}
else
{
include("login.php");
}
Where you have #$$value in your input forms, you are firstly silencing the error in php saying that the $value isn't set in some of your include instances.
What would be advisable would be to save the username and password into their own distinct variables if received in the POST request and then echo these out into the value of the field, also by putting $$ you are trying to find a dynamically named variable, with the name of the value of $value, as opposed to the variable $value.
I think you want something like this -
foreach($labels as $field => $label)
{
$value = '';
if(!empty($_POST[$field ]) {
$value = $_POST[$field];
}
if($field != "password")
{
echo "<div><label for='$field'>$label</label>
<input type='text' name='$field' id='$field' width='40%' maxlength='40' value='".$value."'></div>";
}
else
{
echo "<div><label for='$field'>$label</label>
<input type='password' name='$field' id='$field' width='40%' maxlength='20' value='".$value."'</div>";
}
}
Related
i created an upload card name, type ,description and picture.
Here are the files
<?php
$labels=array("type"=>"type",
"CardName"=>"Card Name",
"Description"=>"Description",
"atk"=>"Attack",
"def"=>"Defend");
echo "<form enctype='multipart/form-data' action='InsertCard.php' method='POST'>";
echo "<h2>Insert new card </h2>";
foreach($labels as $keys =>$values)
{
echo "$values <input type='text' name='$keys'/><br/>";
}
//echo "<input type='hidden' name='MAX_FILE_SIZE' value='80000'/>";
echo "Insert card <input type='file' name='pix' /><br/>";
echo "<input type='submit' value='insert new cards'/>";
echo "<input type='submit' name='return' value='return'/>";
echo "</form>";
?>
<?php
$labels=array("type"=>"type",
"CardName"=>"Card Name",
"Description"=>"Description",
"atk"=>"Attack",
"def"=>"Defend");
if(#isset($_POST['return']))
{
header("Location:ShowCatalog.php");
}
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die("can't connect to server");
foreach($_POST as $keys =>$values)
{
if(empty($values))
{
if($keys=='type' or $keys=='CardName' or $keys=='Description' or $keys=='picture')
{
$empty_values[]=$keys;
}
}
else
{
if($keys=='type')
{
if(!preg_match("/^[A-Za-z -]{4,15}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=='CardName')
{
if(!preg_match("/^[A-Za-z '-]{4,30}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=='Description')
{
if(!preg_match("/^[\"\:\(\);A-Za-z0-9., '-]{4,1000}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=="atk" or $keys=="def")
{
if(!preg_match("/^[0-9]{3,5}$/",$values))
{
$invalid_data[]=$keys;
}
}
elseif($keys=='picture')
{
if(!preg_match("/^[A-Za-z0-9., '-]{4,30}(.jpg)$/",$values))
{
$invalid_data[]=$keys;
}
}
}
}
// i think i did something wrong here.
foreach($_FILES['pix'] as $keys =>$values)
{
//if there is no file uploaded
if($keys=='tmp_name')
{
if($value="")
{
$invalid_pix[]="can not find picture<br/>";
}
}
//if the file is not jpeg format
if($keys=='type')
{
if(!preg_match("/^image\/jpeg$/",$values))
{
$invalid_pix[]="only jpeg files are allowed<br/>";
}
}
// if the file size is over 80000
if($keys=='size')
{
if($values>=80000)
{
$invalid_pix[]="size is over than allowed";
}
}
}
if(#sizeof($empty_values)>0 or #sizeof($invalid_data)>0 or #sizeof($invalid_pix)>0)
{
if(#sizeof($empty_values)>0)
{
$join=join(", ",$empty_values);
$msg="You forgot to input: $join<br/>";
echo $msg;
}
if(#sizeof($invalid_data)>0)
{
$join=join(", ",$invalid_data);
$msg="Invalid data: $join";
echo $msg;
}
if(#sizeof($invalid_pix)>0)
{
foreach($invalid_pix as $values)
{
echo $values."<br/>";
}
}
echo "<form enctype='multipart/form-data' action='$_SERVER[PHP_SELF]' method='POST'>";
echo "<h2>Insert new card </h2>";
foreach($labels as $keys =>$values)
{
echo "$values <input type='text' name='$keys'/><br/>";
}
//echo "<input type='hidden' name='MAX_FILE_SIZE' value='80000'/>";
echo "Insert card <input type='file' name='pix' /><br/>";
echo "<input type='submit' value='insert new cards'/>";
echo "<input type='submit' name='return' value='return'/>";
echo "</form>";
exit();
}
else
{
echo 'ok';
}
However, I'm getting a problem that i can not out put the value "can not find picture". I mean when user doesn't insert the card and press submit i always showed up "only jpeg files are allowed" but now "can not find picture". How to fix that
Spelling mistake
you used $value instead of $values in if condition
Check it out,.
//if there is no file uploaded
if($keys=='tmp_name')
{
if($value="")
{
$invalid_pix[]="can not find picture<br/>";
}
}
I have a form contaning Full name, email, phone when inserting values into the database the phone number was change to 2147483647 (Full name and email are ok). Here are my PHP file
register.php
<h1>register form</h1>
<?php
$labels=array("full_name"=>"Full Name",
"email"=>"Email",
"phone"=>"Phone");
echo "<form action='check_register.php' method='POST'>";
foreach($labels as $key =>$value)
{
echo "$value <input type='text' name='$key'/><br/>";
}
echo "<input type='submit' value='submit'/>";
echo "</form>";
?>
check_register.php
<?php
$labels=array("full_name"=>"Full Name",
"email"=>"Email",
"phone"=>"Phone");
foreach($_POST as $key =>$value)
{
if(empty($value))
{
$empty_value[]=$key;
}
elseif($key=="full_name")
{
if(!preg_match("/^[A-Za-z '-]{2,50}$/",$value))
{
$invalid_value[]=$key;
}
}
elseif($key=="email")
{
if(!preg_match("/^[A-Za-z0-9]{5,20}+(#)[A-Za-z0-9]{5,20}(\.com)$/",$value))
{
$invalid_value[]=$key;
}
}
elseif($key=="phone")
{
if(!preg_match("/^(\(\d+\)|\d+\-)?\d{10,20}$/",$value))
{
$invalid_value[]=$key;
}
}
}
if(#sizeof($empty_value)>0 or #sizeof($invalid_value)>0)
{
if(#sizeof($empty_value)>0)
{
echo "input ";
foreach($empty_value as $key) //loop empty value
{
echo " $labels[$key] ";
}
}
if(#sizeof($invalid_value)>0)
{
echo "<br/>invalid data ";
foreach($invalid_value as $key) //loop invalid_value
{
echo " $labels[$key] ";
}
}
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>";
foreach($labels as $key =>$value)
{
echo "$value <input type='text' name='$key'/><br/>";
}
echo "<input type='submit' value='submit'/>";
echo "</form>";
}
else
{
$user='root';
$host='localhost';
$password='root';
$dbname='pet';
$connect=mysqli_connect($host,$user,$password,$dbname) or die("can't connect to server");
foreach($labels as $key =>$value)
{
$good_data[$key]=strip_tags(trim($_POST[$key]));
if($key=="phone")
{
$good_data[$key]=preg_replace("/[)( .-]/","",$good_data[$key]);
}
$good_data[$key]=mysqli_real_escape_string($connect,$good_data[$key]);
}
$query="INSERT INTO register (";
foreach($good_data as $key =>$value)
{
$query.="$key,";
}
$query.= ") VALUES (";
$query=preg_replace("/,\)/",")",$query);
foreach($good_data as $key =>$value)
{
$query.="'$value',";
}
$query.=")";
$query=preg_replace("/,\)/",")",$query);
$query=preg_replace("/(\(\d+\)|\d+\-)/",")",$query);
$result=mysqli_query($connect,$query) or die ("can't execute query.".mysqli_error($connect));
echo "$query";
echo "<h4>member inserted $query </h4>";
}
?>
Your phone number is stored as an integer and you are storing a number that is larger than an integer field.
Your options are to alter the table to make this field a bigint or a varchar.
Data insertion is not happening when user is entering through a form.i am trying to ask user for firstname , lastname and phone number through 3 fields checking pattern side by side but data is not being inserted in db.
The code is as ->
main page i.e. allinfo.php:
<html>
<head></head>
<body>
<?php
$labels=array("firstname"=>"FirstName" , "lastname"=>"LastName" ,"phone"=>"PhoneNumber");
?>
<form action='blank.php' method='POST'>
<?php
foreach ($labels as $field => $value)
{
echo "<label for='$field'>$value</label>";
echo "<input type='text' name='$field'>";
}
echo "<input type='submit' value='Submit'>";
?>
</form>
</body>
Other page:
<html>
<head></head>
<body>
<?php
/*foreach($_POST as $field=>$value)
{
echo "$field = $value<br />";
}*/
/*foreach($_POST as $field)
{
echo "$field <br />";
}*/
$labels=array("firstname"=>"FirstName" , "lastname"=>"LastName" ,"phone"=>"PhoneNumber");
foreach ($_POST as $field => $name)
{
if($field!='lastname')
{
if(empty($name))
{
$blank_array[]=$field;
}
}
elseif($field=="phone")
{
if(!preg_match("/^ [0-9 ) ( -] {7-20} $/" , $name))
{
$bad_array[]=$field;
}
}
}
if(#sizeof($blank_array) > 0 or #sizeof($bad_array) > 0)
{
if(#sizeof($blank_array) > 0)
{
echo "<p>You have missed some of the values</p>";
foreach($blank_array as $name)
{
echo "{$labels[$name]}<br />";
}
}
if(#sizeof($bad_array) > 0)
{
echo "Please enter in correct format";
foreach($bad_array as $name)
{
echo "{$labels[$name]}";
}
}
echo "<form action='$_SERVER[PHP_SELF]' method='POST'>"; /* re-display the form*/
foreach($labels as $field=>$name)
{
$good_data[$field]=strip_tags(trim($_POST[$field]));
echo "<label for='$field'>$name</label>";
echo "<input type='text' name='$field' value='{$good_data[$field]}'>";
}
echo "<input type='submit' value='Submit'>";
echo "</form>";
}
else
{
$host="localhost";
$acc="root";
$password="*******";
$database="member";
$cxn=mysqli_connect($host,$acc,$password,$database) or die("can not found");
foreach($labels as $field=> $name)
{
$good_data[$field]=strip_tags(trim($_POST[$field]));
if($field=="phone")
{
$good_data[$field]=preg_replace("/ [) ( . -] / " , " " , $good_data[$field]);
}
$good_data[$field]=mysqli_real_escape_string($cxn,$good_data[$field]);
}
$query="insert into user (";
foreach($good_data as $field =>$name)
{
$query.="$field";
}
$query.=") VALUES (";
$query=preg_replace("/,\)/",")",$query) ;
foreach($good_data as $field =>$name)
{
$query.="'$name',";
}
$query.=")";
$query=preg_replace("/,\)/",")",$query) ;
$result=mysqli_query($cxn,$query);
echo "new entry";
}
echo "<p>All the information is available ♥ </p>" ;
?>
</body>
Please help.
Change the loop where you build the query string
foreach($good_data as $field =>$name)
{
$query.="$field";
}
To
foreach($good_data as $field =>$name)
{
$query.="$field,";
}
Notice you missed the coma.
The code below is the program that i have written.
The problem is, even if i press submit, reply or delete, none of the button works.
Can you help me what is wrong with the code that i have written below.
Thank you so much.
<?php
/*共通処理*/
//データベースへの接続
try{
$GLOBALS['db'] = new PDO("mysql:host=localhost; dbname=bbs", "root", "test");
} catch (PDOException $e) {
echo 'connection failed: '.$e->getMessage();
}
//action取得
$action = (isset($_GET['action']) ? $_GET['action'] : $_POST['action']);
//action振り分け
switch($action)
{
//書き込み処理
case "regist":
proc_regist();
break;
//削除処理
case "delete":
proc_delete();
break;
//返信処理
case "res":
proc_res();
break;
//表示処理
default:
proc_default();
break;
}
// 終了処理
/* ここで処理は終了 あとは個別の関数へ */
// 基本の掲示板表示処理
function proc_default()
{
$db = $GLOBALS['db'];
$page_max = 15;
$offset = ( isset($_GET['offset']) ? $_GET['offset'] : 0 );
$limit = $page_max +1;
$stmd = $db->query("select * from message order by no desc limit $limit offset $offset");
$rows = $stmd->fetchAll();
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html lang = "ja">
<head>
<meta http-equiv = "Content-Type" content="text/html; charset = UTF-8">
<title>
</title>
</head>
<body>
<form method = "POST" action = "bbs_new.php">
<input type = "hidden" name = "action" value= "regist">
お名前:<input type="text" name="name"><br>
メール:<input type="text" name="mail"><br>
題 名:<input type="text" name="title"><br>
削除キー:<input type="password" name="delkey" value="<?php print $delkey ?>"><br>
<textarea name="contents" cols="60" rows="5"></textarea><br>
<?php
print "<input type='submit' name='write' value='送信'>\n";
print "<hr>\n";
print "記事番号:<input type='text' name='delno'>\n";
print "削除キー: <input type='password' name='delkey'>\n";
print "<input type='submit' name='delete' value='記事削除'>\n";
print "<input type = 'hidden' name = 'action' value = 'delete'>\n";
?>
</form>
<?php
//ここからデータ表示処理
$sql = 'select * from message order by no desc';
foreach ($db->query($sql) as $row) {
if ($_GET['resno']) {
if ($row['resno'] != $_GET['resno']) continue;
}
if ($_POST['resno']) $resno = $_POST['resno'];
else $resno = $no;
if ($row['no'] != $row['resno']) $res = true; else $res = false;
if ($res) print "<blockquote>";
else print "<hr>";
print "<p>No.".$row['no']." ";
print "<b>{$row['title']}</b> 投稿者:";
if ($row['mail']) print "<a href='mailto:{$row['mail']}'>";
print $row['name'];
if ($row['mail']) print "</a>";
$row['time'] = date("Y/m/d H:i:s");
print " 投稿時間:{$row['time']}";
if (!$res && !$_GET['resno']) {
print " <a href='bbs_new.php?resno={$row['no']}'>返信</a>";
}
print "<br><br>{$row['contents']}</p>";
if ($res) print "</blockquote>";
print "\n";
}
//改ページ
if(count($rows)>$page_max){
$next = $offset+$page_max;
print "[<a href='bbs_new.php?offset=$next'>前のページ</a>]";
}
if ($offset>0){
$prev = $offset-$page_max;
print "[<a href='bbs_new.php?offset=$prev'>次のページ</a>]";
}
//rowに1行ずつ取得したデータが入る
//返信データの有無
$sql2 = 'select * from message order by no desc';
foreach ($db->query($sql2) as $row2) {
//入力フォームの書き出し
if ($_GET['resno']) {
print "<input type='submit' name='write' value='No.{$_GET['resno']} に返信'>\n";
print "<input type='hidden' name='resno' value='{$_GET['resno']}'>\n";
} else {
print "<input type='submit' name='write' value='送信'>\n";
print "<hr>\n";
print "記事番号:<input type='text' name='delno'>\n";
print " 削除キー: <input type='password' name='delkey2'>\n";
print " <input type='submit' name='delete' value='記事削除'>\n";
}
}
}
//header("Location: bbs_new.php");
//データベースへ書き込みを行う処理
function proc_regist(){
// グローバル変数から取り出す
$db = $GLOBALS['db'];
//記事番号
$sql = 'select no from message order by no desc';
$maxno = 0;
$no = $maxno + 1;
$_POST['no'] = $no;
if(!$_POST['resno']){
$_POST['resno'] = $_POST['no'];
}
//データベースへインサート
$sql = 'insert into message values(?,?,?,?,?,?,?,?)';
$st = $db->prepare($sql);
$result = $st->execute(array($_POST['no'], $_POST['resno'],$_POST['name'], $_POST['mail'],$_POST['title'], $_POST['contents'],$_POST['delkey'], $_POST['time']));
}
header("Location: bbs_new.php");
//データベースから削除を行う処理
function proc_delete(){
$db = $GLOBALS['db'];
$sql = 'delete from message where no = ? and delkey = ? ';
$sth = $db->prepare($sql);
$ret = $sth->execute(array($_POST['no'],$_POST['delkey']));
header("Location: bbs_new.php");
}
?>
</body>
</html>
What if you try this?
print "<input type='submit' name='action' value='write'>\n";
print "<hr>\n";
print "記事番号:<input type='text' name='delno'>\n";
print "削除キー: <input type='password' name='delkey'>\n";
print "<input type='submit' name='action' value='delete'>\n";
print "<input type = 'hidden' name = 'action' value = 'delete'>\n"; (remove this line)
I'm trying to validate a form of a test. I get an error in answer.php Basically I want to validate that each question has been answered.
The form:
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' ORDER BY q_nr";
$result1=mysql_query($sql1);
echo "<form method='post' name='form1' action='answer.php'>";
while($row1 = mysql_fetch_array($result1))
{
$q_nr=$row1['q_nr'];
$q_type=$row1['q_type'];
$question=$row1['question'];
$option1=$row1['option1'];
$option2=$row1['option2'];
$option3=$row1['option3'];
echo "<P><strong>$q_nr $question</strong><BR>";
echo "<BR>";
echo "</p>";
if ($q_type != 'mr') {
if($option1!="") {
echo "<input type='radio' name='question[$q_nr]' value='A'>$option1<BR>";
} else {
echo ''; }
if($option2!="") {
echo "<input type='radio' name='question[$q_nr]' value='B'>$option2<BR>";
} else {
echo ''; }
if($option3!="") {
echo "<input type='radio' name='question[$q_nr]' value='C'>$option3<BR>";
} else {
echo ''; }
} else { // else if not <> mr
if($option1!="") {
echo "<input type='checkbox' name='question[$q_nr][]' value='A'>$option1<BR>";
} else {
echo ''; }
if($option2!="") {
echo "<input type='checkbox' name='question[$q_nr][]' value='B'>$option2<BR>";
} else {
echo ''; }
if($option3!="") {
echo "<input type='checkbox' name='question[$q_nr][]' value='C'>$option3<BR>";
} else {
echo ''; }
} //end else if q_type <> mr
echo "<BR>";
echo "</p>";
} //end while row1
echo "<input type='submit' value='Submit' name='Submit'>";
echo "</form>";
answer.php
foreach($_POST['question'] as $key => $ans) {
if ($ans[] = '') {
echo "answer is empty";
}
}
I get the error: Warning: Invalid argument supplied for foreach() in ......
One thing is that you are assigning the answer rather than checking it, use ==
foreach($_POST as $key => $ans) {
if ($ans == '') {
echo "answer is empty";
}
}
and instead of using
name='question[$q_nr]'
I would use for the radio fields
name='question_{$q_nr}'
and for the checkboxes
name='question_{$q_nr}[]'
On answer.php you should be able to do a print_r($_POST) to check what you are getting.
This is probably because your $_POST['question'] is empty. This is what happens when you try to do this with an empty array.
Whereas your HTML says: name='question[$q_nr]'.
Print the values in the array to see what it contains, use print_r.
Edit: $_POST['question'] IS NOT an array! While $_POST IS an array...
Maybe you should try to do something like this:
foreach ($_POST as $key => $value)
Or do it however you want the result to be displayed.