i am a little new to php and although i have managed to pass values of session variables before this piece of code is leaving me puzzled
<form action="team_reg2.php" method="post" name="form1" class="cent" id="form1">
<p><strong>Team Registration</strong></p>
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db("databolism",$con);
$result=mysql_query("select * from events where id=$_POST[event]",$con);
$row=mysql_fetch_assoc($result);
$num=$row['max_team'];
$_SESSION['max_team']=$num;
$_SESSION['event_id']=$_POST['event'];
for($i=1;$i<=$num;$i++)
{
print "<p><span id=\"sprytextfield$i\"\n>";
print "<label>member$i";
print "<input type=\"text\" name=\"mem$i\" id=\"mem$i\" />\n";
print "</label>\n";
print "<span class=\"textfieldInvalidFormatMsg\">Please enter only id</span></span></p>\n";
}
?>
now this will pass via post to team_reg2.php
<?php
$con=mysql_connect("localhost","root","");
if(!$con)
die("could not connect to db");
$db=mysql_select_db("databolism",$con);
$num=6;
$event=14;
$result=mysql_query("select * from events where id=$event",$con) or die(mysql_error());
$row=mysql_fetch_assoc($result);
$query='fantasia1_'.$row['name'];
$query2="select max(t_id) from $query";
$que=mysql_query($query2,$con);
$result=mysql_fetch_array($que) or die(mysql_error());
$chk3=$result['max(t_id)'];
if($chk3==NULL)
{
for($i=1;$i<=$num;$i++)
{
$name='mem'.$i;
if($_POST["$name"]!="")
{
$query2="insert into $query values(1,'$_POST[$name]')";
$que=mysql_query($query2,$con);
}
}
echo " please note your team id is 1 <br>";
echo " your team members are : <br>";
for($i=1;$i<=$num;$i++)
{
$name='mem'.$i;
echo "$_POST[$name]<br>";
}
}
else
{
$str="select * from $query where (";
for($i=1;$i<=$num;$i++)
{
$name='mem'.$i;
$text="p_id='$_POST[$name]'";
if($i==1)
$str=$str.$text;
else
$str=$str.' or '.$text;
}
$str=$str.')';
$query2=$str;
echo "$str<br>";
// echo "$query2</br>";
$que=mysql_query($query2,$con) or die(mysql_error());
$num=mysql_num_rows($que);
if($num!=0)
{
while($result=mysql_fetch_array($que))
{
echo "$result[p_id] is already registered in team $result[t_id]<br>";
}
//include("reg_team.html");
}
else if($num==0)
{
//echo $query;
$query2="select max(t_id) from $query";
$que=mysql_query($query2,$con) or die(mysql_error());
//echo "$que<br>";
$result=mysql_fetch_array($que);
$max=$result['max(t_id)'];
$max++;
$num=$_SESSION['max_team'];
for($i=1;$i<=$num;$i++)
{
$name='mem'.$i;
if($_POST[$name]!="")
{
$query2="insert into $query values($max,'$_POST[$name]')";
$que=mysql_query($query2,$con);
}
}
echo " please note your team id is $max <br>";
echo " your team members are : <br>";
for($i=1;$i<=$num;$i++)
{
$name='mem'.$i;
echo "$_POST[$name]<br>";
}
}
}
?>
i have done session_start(); at the beginning of the page itself. The problem is that echoing $_SESSION variables in second file is not printing anything.
someone please explain me whats going on.
thank you
You need session_start() in the second file, too.
Related
I have problem in retrieving one question on one page for online examination system from database. Currently I am retrieving with session variable. But problem in that is if we refresh page then session variable is increment and question is change with next serial number. Currently I am increment retrieving session variable from other page. So my question is how to solve change of question problem while refreshing page? Below is my code. and remaining code is in image file.
include("database.php");
$query="select * from ctip_question";
if($submit=='Next Question' && isset($ans))
{
mysql_data_seek($rs,$_SESSION[qn]);
$row= mysql_fetch_row($rs);
$question = $_SESSION[question];
$time = date('Y-m-d h:i:s');
mysql_query("insert into ctip_answer(test_id, q_no, qtype, answer,time) values ('1', '$_SESSION[qn]','$question','$ans','$time')") or die(mysql_error());
if($ans==$row[7])
{
$_SESSION[trueans]=$_SESSION[trueans]+1;
}
$_SESSION[qn]=$_SESSION[qn]+1;
$initialize_qn_no++;
}
else if($submit=='Get Result' && isset($ans))
{
mysql_data_seek($rs,$_SESSION[qn]);
$row= mysql_fetch_row($rs);
$time = date('Y-m-d h:i:s');
$question = $_SESSION[question];
mysql_query("insert into ctip_answer(test_id, q_no, qtype, answer,time) values ('1', '$_SESSION[qn]','$question','$ans','$time')") or die(mysql_error());
if($ans==$row[7])
{
$_SESSION[trueans]=$_SESSION[trueans]+1;
}
echo "<h1 class=head1> Result</h1>";
$_SESSION[qn]=$_SESSION[qn]+1;
echo "<Table align=center><tr class=tot><td>Total Question<td> $_SESSION[qn]";
echo "<tr class=tans><td>True Answer<td>".$_SESSION[trueans];
$w=$_SESSION[qn]-$_SESSION[trueans];
echo "<tr class=fans><td>Wrong Answer<td> ". $w;
echo "</table>";
mysql_query("insert into mst_result(login,test_id,test_date,score) values('$login',$tid,'".date("d/m/Y")."',$_SESSION[trueans])") or die(mysql_error());
echo "<h1 align=center><a href=review.php> Review Question</a> </h1>";
unset($_SESSION[qn]);
unset($_SESSION[sid]);
unset($_SESSION[tid]);
unset($_SESSION[trueans]);
exit;
}
$sql = "select * from ctip_test_question where test_id='$_SESSION[testid]' && sr_no=$_SESSION[qn]";
$result = mysql_query($sql);
while ($row1 = mysql_fetch_array($result)) {
{
$question = $row1['que_no'];
$_SESSION[question]=$question;
$rs=mysql_query("select * from ctip_question where que_id=$question",$cn) or die(mysql_error());
mysql_data_seek($rs,$_SESSION[qn]);
$row= mysql_fetch_row($rs);
echo "action=self_page";
$n=$_SESSION[qn]+1;
echo "here is my question";
echo "option1";
echo "option2";
echo "option3";
echo "option4";
if($_SESSION[qn]<20)
echo "next question";
else
echo "get result";
}
}
I am new at designing websites and I recently wanted to add login/registration forms to my website I have a database and have coded all of the forms but when I attempt to register I am unable to because my information is not added to the database. I have been working on this for a while any advice on how to better my forms and registration system would be more than helpful. Thanks in advance!
Here are my forms:
Registration:
<?php
session_start();
include "dbConfig.php";
if (isset($_GET["op"]) == "login") {
if (!$_POST["username"] || !$_POST["password"]) {
die("You need to provide a username and password.");
}
// Create query
$q = "SELECT * FROM `gd_database` "
."WHERE `username`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
if ( $obj = #mysql_fetch_object($r) ) {
// Login good, create session variables
$_SESSION["valid_id"] = $obj->id;
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["valid_time"] = time();
// Redirect to member page
Header("Location: members.php");
} else {
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
}
} else {
echo "<form action=\"?op=login\" method=\"POST\">";
echo "Username: <input name=\"username\" size=\"15\">";
echo "Password: <input type=\"password\" name=\"password\" size=\"8\">";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
}
?>
Login:
<?php
session_start();
include "dbConfig.php";
if (isset($_GET["op"]) == "login") {
if (!$_POST["username"] || !$_POST["password"]) {
die("You need to provide a username and password.");
}
// Create query
$q = "SELECT * FROM `gd_database` "
."WHERE `username`='".$_POST["username"]."' "
."AND `password`=PASSWORD('".$_POST["password"]."') "
."LIMIT 1";
// Run query
$r = mysql_query($q);
if ( $obj = #mysql_fetch_object($r) ) {
// Login good, create session variables
$_SESSION["valid_id"] = $obj->id;
$_SESSION["valid_user"] = $_POST["username"];
$_SESSION["valid_time"] = time();
// Redirect to member page
Header("Location: members.php");
} else {
// Login not successful
die("Sorry, could not log you in. Wrong login information.");
}
}
else
{
echo "<form action=\"?op=login\" method=\"POST\">";
echo "Username: <input name=\"username\" size=\"15\">";
echo "Password: <input type=\"password\" name=\"password\" size=\"8\">";
echo "<input type=\"submit\" value=\"Login\">";
echo "</form>";
}
?>
Your login and registration scripts are the same code and they assume that you already have an account are trying to verify the credentials. You'll need to insert the data from the form into the database with an INSERT statement before anything else. Right now, you're just checking for accounts in an empty table.
Look up some tutorials for registering users. Tutsplus is nice.
here is a code for registration
register.php
<?php
include ("dbConfig.php");
if ( $_GET["op"] == "reg" )
{
$bInputFlag = false;
foreach ( $_POST as $field )
{
if ($field == "")
{
$bInputFlag = false;
}
else
{
$bInputFlag = true;
}
}
if ($bInputFlag == false)
{
die( "Problem with your registration info. "
."Please go back and try again.");
}
$q = "INSERT INTO `dbUsers` (`username`,`password`,`email`) "
."VALUES ('".$_POST["username"]."', "
."PASSWORD('".$_POST["password"]."'), "
."'".$_POST["email"]."')";
$r = mysql_query($q);
if ( !mysql_insert_id() )
{
die("Error: User not added to database.");
}
else
{
Header("Location: register.php?op=thanks");
}
}
elseif ( $_GET["op"] == "thanks" )
{
echo "<h2>Thankyou for registering!</h2>";
}
else
{
echo "<form action=\"?op=reg\" method=\"POST\">\n";
echo "Username: <input name=\"username\" MAXLENGTH=\"16\"><br />\n";
echo "Password: <input type=\"password\" name=\"password\" MAXLENGTH=\"16
\">\n";
echo "Email Address: <input name=\"email\" MAXLENGTH=\"25\"><br />\n";
echo "<input type=\"submit\">\n";
echo "</form>\n";
}
?>
inorder to add data into your database you need to use a query INSERT.hope this code would help you in solving your problem.
i create php files that check user login in. If the user and password is correct, user can visit the catalog page. However there are some problems with the session. After reopening browser it still display the hidden data. I know the session will be closed when i close the browser but this case seems weird. This is the login form:
<html>
<body>
<?php
$LabelLogin=array("login"=>"login",
"password"=>"password",
);
echo "<h1> Login and Register Page </h1>";
echo "<form action='CheckLoginDetail.php' method=POST>";
foreach($LabelLogin as $keys =>$values)
{
if($keys=='password')
{
echo "$values <input type='password' name='$keys' /><br/>";
}
else
{
echo "$values <input type='text' name='$keys' /><br/>";
}
}
echo "<input type='submit' value='submit' />";
echo "<br/>click <a href='register.php'>here<a/> to register if you don't have an accout <br/>";
echo "</form>";
?>
</body>
2nd CheckLoginDetail.php
<?php
session_start();
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die ("can't connect to server");
$labels=array("login"=>"login",
"password"=>"password");
foreach($_POST as $keys =>$values)
{
if(empty($values))
{
$empty_values[]=$keys;
}
elseif(!preg_match("/^[A-Za-z0-9_]+$/",$values))
{
$invalid_values[]=$keys;
}
else
{
$data[$keys]=$values;
}
}
if(#sizeof($empty_values)>0 or #sizeof($invalid_values)>0)
{
if(#sizeof($empty_values)>0)
{
echo "login name or password or both can not be empty !";
}
if(#sizeof($invalid_values)>0)
{
echo "values contain invalid characters";
}
include("FrontPage.php");
exit();
}
else
{
foreach($data as $keys =>$values)
{
$clean_data[$keys]=mysqli_real_escape_string($connect,strip_tags(trim($values)));
}
$query="SELECT LoginName and Password FROM yugimemberinfo WHERE LoginName='";
foreach($clean_data as $keys =>$values)
{
if($keys=="login")
{
$query.="$values'";
}
if($keys=="password")
{
$values=md5($values);
$query.=" AND Password='$values'";
}
}
$result=mysqli_query($connect,$query) or die("can't execute query ".mysqli_error($connect));
if(mysqli_num_rows($result)==0)
{
echo "login fail";
include("FrontPage.php");
exit();
}
else
{
$_SESSION['access']="yes";
echo "login succesfully !<br/>";
echo "Here are two options for you :<br/>";
echo "<ul>
<li><a href='ShowCatalog.php'>Go to Card Catalog</a></li>
<li><a href='search_form.php'>Searching for your cards</a></li>
</ul>";
$query_insert="INSERT INTO yugimember (LoginName,LoginTime) VALUES(";
foreach($clean_data as $keys =>$values)
{
//echo "$keys =>$values<br/>";
if($keys=="login")
{
$query_insert.="'$values',";
}
}
//insert login name and time to yugimember
$query_insert.="'".date("Y-m-d H:i:s")."')";
$result=mysqli_query($connect,$query_insert) or die ("can't execute query line 62");
}
}
?>
if users login successfully, they can lick to the link that take them to another site called "ShowCatalog.php"
<?php
session_start();
include("connect.inc");
$connect=mysqli_connect($host,$username,$password,$dbname) or die ("can't connect to server");
if(#$_SESSION['access'] != 'yes')
{
include("FrontPage.php");
exit();
}
$query="SELECT * FROM dragon ";
$result=mysqli_query($connect,$query) or die("can't execute query");
echo "<hr/>";
while($row=mysqli_fetch_assoc($result))
{
extract($row);
echo $type."<br/>";
echo $CardName."<br/>";
echo $atk." \ ".$def."<br/>";
echo $Description;
echo "<br/>".$picture."<br/>";
echo "<br/>";
echo "<a href='../dragon/{$picture}'><img src='../dragon/{$picture}' height='300' width='300'></a>";
echo "<hr/>";
}
?>
I make the ShowCatalog.php only display data for user logining in. However when i login in and close the browser then reopen it the ShowCatalog.php the data is stilled appear.
Not sure but when you do this :
if(#$_SESSION['access'] != 'yes')
If the session does not exist (because you closed your browser), maybe it will bypass this condition.
Try :
if (!isset($_SESSION['access']) | $_SESSION['access'] != 'yes')
I created a PHP Drop Down which is populated from a MySql Database and works just fine, the problem occurs when I want to post the selected in another script. The question is how to post the data to the other script?
This is the source code of the script that implements the drop downs. Please Help!!!!
<?php
$conn = mysql_connect("localhost", "admin", "admin");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekupuvac")) {
echo "Unable to select EKupuvac: " . mysql_error();
exit;
}
$query = "SELECT ImeK, KupuvacID FROM kupuvac ORDER BY Saldo DESC";
$result = mysql_query($query) or die(mysql_error());
if (!$result) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so I am exiting";
exit;
}
$dropdown = "<select name='ImeK'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown.= "\r\n<option value='{$row['KupuvacID']}'>{$row['ImeK']}</option>";
}
$dropdown .= "\r\n</select>";
echo"Izberi Kupuvac:";
echo $dropdown;
// Second Combo
$conn = mysql_connect("localhost", "admin", "admin");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
if (!mysql_select_db("ekupuvac")) {
echo "Unable to select EKupuvac: " . mysql_error();
exit;
}
$query2 = "SELECT ImeP, ProzivodID FROM proizvod ORDER BY ImeP";
$result2 = mysql_query($query2) or die(mysql_error());
if (!$result2) {
echo "Could not successfully run query ($query2) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result2) == 0) {
echo "No rows found, nothing to print so I am exiting";
exit;
}
$dropdown2 = "<select name='ImeP'>";
while($row = mysql_fetch_assoc($result2)) {
$dropdown2.= "\r\n<option value='{$row['ProzivodID']}'>{$row['ImeP']}</option>";
}
$dropdown2.= "\r\n</select>";
echo"<br> Izberi Proizvod:";
echo $dropdown2;
echo"<br>";
mysql_free_result($result);
?>
A <select> box is not enough, you need to enclose it in a form
?>
<form method="post" action="somescript.php">
<?
//your controls go here
?>
</form>
then create somescript.php and access your form variables using $_POST
Also use PDO not mysql_ functions as these arent safe
My first page to delete queries selected by user query.php which is working absolutely fine:
<form method=post action="delete.php">
List of queries<br/>
<?php
$ebits = ini_get('error_reporting');
error_reporting($ebits ^ E_NOTICE);
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("testdb") or die(mysql_error());
echo "<br />";
$query = "select * from queries ";
$result = mysql_query($query) or die(mysql_error());
$count=mysql_num_rows($result);
while($row = mysql_fetch_array($result))
{
print "<input type='checkbox' name='Query[]' value=\"".$row['queryId']."\"> ";
echo " ". $row['name']." ". $row["address"]." ". $row["contactNo"]."
". $row["query"];
echo "<br />";
}
?>
<input type="submit" value="Delete" name="Delete">
<br/>
</form>
I've tried with following codes for second page delete.php but nothing seems to work.
Code1:
<?php
if($_POST['Delete'])
{
if(count($_POST['checkbox']) > 0) {
foreach($_POST['checkbox'] as $checkbox)
{
$del_id=$checkbox;
$sql = "DELETE * FROM queries WHERE `queryId`= '$del_id'";
$result = mysql_query($sql);
mysql_error();
}
echo "Selected Rows deleted";
} else {
$NEW="Nothing to Delete";
}
}
?>
Code2:
<?php
if(($_POST['Delete']))
{
$count=array();
$count=$_POST['checkbox'];
for($i=0;$i<count($count);$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM queries WHERE queryId='$del_id' ";
$result = mysql_query($sql);
}
$NEW="Selected records Deleted";
}
var_dump($_POST['checkbox']);
var_dump($count);
?>
Your checkbox names are "Query", but you're accessing it as $_POST['checkbox']. This should be $_POST['Query'] instead.
EDIT checking from your updated code:
if($_POST['Delete']) {
if(count($_POST['Query']) > 0) {
foreach($_POST['Query'] as $checkbox) {
$del_id=$checkbox;
$sql = "DELETE * FROM queries WHERE queryId= '$del_id'";
$result = mysql_query($sql);
mysql_error();
}
echo "Selected Rows deleted";
}
else {
$NEW="Nothing to Delete";
}
}
Instead of this:
$del_id=$checkbox;
do this:
// if queryId is numeric
$del_id=intval($checkbox);
This makes sure that the value you're working with is numeric, instead of potential malicious input from your user. I'm going under the assumption that queryId is numeric. If it's not, then you need to do this:
// if queryId is not numeric:
$del_id = mysql_real_escape_string($checkbox);
Your DELETE syntax is incorrect:
$sql = "DELETE * FROM queries WHERE queryId= '$del_id'";
You want just DELETE FROM. Also if the value for queryId is numeric, you don't need the quotes around it:
$sql = "DELETE FROM `queries` WHERE `queryId` = $del_id";
Finally, your MySQL error call doesn't do anything useful as is:
mysql_error();
Here's how you should do this, along with the rest of the code:
if($_POST['Delete']) {
if(count($_POST['Query']) > 0) {
foreach($_POST['Query'] as $checkbox) {
$del_id= intval($checkbox);
$sql = "DELETE FROM `queries` WHERE `queryId` = $del_id";
$result = mysql_query($sql);
if(!$result) {
echo "There was an error in the query: " . mysql_error();
}
}
echo "Selected Rows deleted";
}
else {
$NEW="Nothing to Delete";
}
}