Using Sessions in PHP with Oracle 11g R2 (11.0.2) - php

I have a form like this: The file name is "main.php"
<html>
<form action = "options.php" method = "POST" />
<p> <h3> Enter Phone Number: </h3> <input type = "text" name =
"cust_phone" />
<p> <input type = "submit" value = "Submit" />
</form>
</html>
The "options.php" looks like this:
<html>
<body> Details of: <?php session_start();
echo htmlentities($_POST["cust_phone"]) . "<br>";
$link = oci_connect('hd','hd', 'localhost/mydb');
if(!$link) {
$e = oci_error();
exit('Connection error ' . $e['message']);
}
$_SESSION['var'] = $_POST["cust_phone"];
echo $_SESSION['var'];
$ph = htmlentities($_POST["cust_phone"]);
$q1 = "select CUST_ID from customer where CUST_PHONE = :bv_ph";
$q1parse = oci_parse($link, $q1);
oci_bind_by_name($q1parse, ':bv_ph', $ph);
oci_execute($q1parse);
oci_fetch($q1parse);
$res = oci_result($q1parse, 'CUST_ID');
if(!$res) {
echo "No Order found. New Order?";
}
?>
<form action = "" method = "POST" >
<input type = "radio" name = "option" value = "Yes" checked> Yes
<br>
<input type = "radio" name = "option" value ="No"> No <br>
<input type = "submit" value = "submit">
</form>
<?php
if(isset($_POST['option']) && ($_POST['option']) == "Yes") {
header("Location: newcustomer.php");
}
elseif(isset($_POST['option']) && ($_POST['option']) == "No") {
header("location: main.php");
}
?>
</body>
The "newcustomer.php" looks like this:
<!DOCTYPE HTML>
<html>
<body>
<form action = "order.php" method = "POST" >
<p> Phone Number: </p>
<p> Enter Address: <input type = "text" name = "address" /></p>
<p> Enter Area: <input type = "text" name = "area" /></p>
</form>
<?php
session_start();
echo $_SESSION ['var'];
?>
</body>
</html>
I want the value of the number entered by the user in "main.php" to be used in "newcustomer.php" which I am not able to achieve. Am i using the session variable correctly? The result when I run "newcustomer.php" does not show any error but does not echo the "$_SESSION['var']".

You should write session_start() every page topper ...
<?php
session_start();
?>
<html>
.....
......

Related

PHP Insert into MySQL Database doesn't work

I'm trying to input data into MySQL Database. I can log into database. However, whenever I run, the error "Error Querying Database 2" keeps appearing.
I'm suspecting my SQL Query having problems. However, I have checked my SQL query several times but I can't find any errors. (not yet)
Any help is appreciated!
<!DOCTYPE HTML>
<html>
<head>
<title>Create Events</title>
<link rel="stylesheet" href="RegisterLogin.css">
</head>
<?php
session_start();
if (isset($_SESSION['Username'])) {
$Username=$_SESSION['Username'];
}
?>
<body>
<?php
//define variables and set to empty values
$EventNameErr = $MembersAttending_Err = $EventDateErr = $LocationErr = $websiteErr = "";
$EventName = $MembersAttending = $EventDate = $Location = $website = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["EventName"])) {
$EventNameErr = "A name for the event is required";
} else {
$EventName = test_input($_POST["EventName"]);
}
if (empty($_POST["MembersAttending"])) {
$MembersAttendingErr = "How many members are attending";
} else {
$MembersAttending = test_input($_POST["MembersAttending"]);
}
if (empty($_POST["EventDate"])) {
$EventDateErr = "The date of the event is required";
} else {
$EventDate = test_input($_POST["EventDate"]);
}
if (empty($_POST["Location"])) {
$LocationErr = "Location of the event is required";
} else {
$Location = test_input($_POST["Location"]);
}
//continues to target page if all validation is passed
if ( $EventNameErr ==""&& $MembersAttendingErr ==""&& $EventDateErr ==""&& $LocationErr == ""){
// check if exists in database
$dbc=mysqli_connect('localhost','testuser','password','Project')
or die("Could not Connect!\n");
$sql="SELECT * from Events WHERE EventName ='$EventName';";
$result =mysqli_Query($dbc,$sql) or die (" Error querying database 1");
$a=mysqli_num_rows($result);
if ($a>0){
$EventNameErr="Event Name already exists".$a;
} else {
$sql1="INSERT INTO Events VALUES(NULL,'$EventName','$MembersAttending','$EventDate','$Location');";
$result =mysqli_Query($dbc,$sql1) or die (" Error querying database 2");
mysqli_close();
header('Location: /EventCreated.php');
}
}
}
// clears spaces etc to prep data for testing
function test_input($data){
$data=trim ($data); // gets rid of extra spaces befor and after
$data=stripslashes($data); //gets rid of any slashes
$data=htmlspecialchars($data); //converts any symbols usch as < and > to special characters
return $data;
}
?>
<h2 style="color:yellow" align="center"> Event Creation </h2>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" align="center" style="color:#40ff00">
EventName:
<input type="text" name="EventName" value="<?php echo $EventName;?>"/>
<span class="error">* <?php echo $EventNameErr;?></span>
<br/><br/>
Members:
<input type="text" name="MembersAttending" value="<?php echo $MembersAttending;?>"/>
<span class="error">* <?php echo $MembersAttendingErr;?></span>
<br/><br/>
Date:
<input type="text" name="EventDate" value="<?php echo $EventDate;?>"/>
<span class="error">* <?php echo $EventDateErr;?></span>
<br/><br/>
Location:
<input type="text" name="Location" value="<?php echo $Location;?>"/>
<span class="error">* <?php echo $LocationErr;?></span>
<br/><br/>
<input type="Reset" name="Reset" value="Reset">
<input type="submit" name="submit" value="Submit"/> 
</form>
</body>
</html>
I'm not sure what are the column name available in your table, but try with the following query,
I got the column name form your code, I'm not sure it's right or wrong. just try it.
$sql1="INSERT INTO Events (EventName,MembersAttending,EventDate,Location)
VALUES('$EventName','$MembersAttending','$EventDate','$Location');";

How to create add value to array everytime i click submit button? in php (with session)

How to create add value to array everytime i click submit button? in php (with session)
Below are the working code, but in Javascript:
<html>
<body>
New array element:<br>
<input id="age" type="text" name="firstname" value="">
<br>
<br>
<input
type="button" value="Submit" onclick="myFunction()">
<p id="demo">gg</p>
<script>
var fruits = [];
function myFunction()
{
var newArray = document.getElementById("age").value;
fruits.push(newArray);
document.getElementById("age").value = "";
document.getElementById("demo").innerHTML = fruits;
}
</script>
</body> </html>
Can someone plz convert the javascript above into php, with session and other?
First, to be able to submit your values through PHP, you have to use the <form> tag.
Try the below code:
<?php
session_start() ;
if (isset($_POST["firstname"])) {
if ($_SESSION["array"] != "") {
$_SESSION["array"] .= "," ;
}
$_SESSION["array"] .= $_POST["firstname"] ;
}
else {
$_SESSION["array"] = "" ;
}
$demo = $_SESSION["array"] == "" ? "gg" : $_SESSION["array"] ;
?>
<html>
<body>
<form action="" method="post">
New array element:<br>
<input id="age" type="text" name="firstname" value="" />
<br>
<br>
<button>Submit</button>
<p id="demo"><?php echo $demo ?></p>
</form>
</body>
</html>
On click of Submit button send data to this php file :index.php
And here is the code for index.php file:
<?php
$sessionArray = $_SESSION['ageArray'];
$age = $_REQUEST['age'];
if(isset($age) && $age != ""){
array_push($sessionArray,$age);
$_SESSION['ageArray'] = $sessionArray;
}
?>
<?php
session_start();
if (isset($_POST['firstname'])){
if (!isset($_SESSION['myArray'])){
$_SESSION['myArray'] = array();
}
$_SESSION['myArray'][] = $_POST['firstname'];
}
?>

How to print or echo some text in new page if the if statement is true in php

Hello Every One i am new to coding and now i am learning php and html below i submited the code and i want to print Hello World in a new page if the given user name and password is correct but it is printing in the same page can any one help me Thanks in Advance
<!doctype html>
<html>
<body>
<form action="#" method="post">
<input type="text" name="username" placeholder="Enter The Username"><br>
<input type="password" name="password" placeholder="Enter Password"><br>
<input type="submit" name="submit" value="Login">
<input type="reset" value="Cancel">
</form>
<?php
$a = 123;
$b = 234;
$c = $_POST["username"];
$d = $_POST["password"];
$e = "Hello World!!";
$f = "Error 404 Page Not Found";
if(isset($_POST['submit'])){
if ($a == $c && $b == $d )
{
print "$e";
}
else
{
echo "$f";
}
}
?>
</body>
</html>
you could use the header function and it would look like this:
if ($a == $c && $b == $d )
{
header("location: newpage.php");
exit;
}
else
{
echo "$f";
}
or indeed as stated above me redirect the form to the new page
First of all this will be the html part in a separate part like login.html:-
<!doctype html>
<html>
<body>
<form action="login.php" method="post"><!-- if you will not give action then form will posted to the same page -->
<input type="text" name="username" placeholder="Enter The Username"><br>
<input type="password" name="password" placeholder="Enter Password"><br>
<input type="submit" name="submit" value="Login">
<input type="reset" value="Cancel"><!-- about this i cannot say anything -->
</form>
</body>
</html>
Now in login.php:-
<?php
$original_user_name = 123; // take variable name that are self descriptive
$original_user_password = 234;
$form_username = $_POST["username"];
$form_password = $_POST["password"];
// $e = "Hello World!!"; no need of extra variable
// $f = "Error 404 Page Not Found"; no need of extra variable
if(isset($_POST['username']) && isset($_POST['password'])){ // check with POSTED values not with button value
if ($original_user_name == $form_username && $original_user_password == $form_password){
echo "hello World!";
}else{
echo "Error 404 Page Not Found!";
}
}else{
echo "please fill both user name and password!";
}
?>
Note:- both files must be in the same working directory.
Create a new .php file where you can put your PHP code & in the html file, change form tag to < form action="path of that php file" method="post">

Keep text in text field after submit

I'm building a form, and I want that all the inserted values will be kept, in case of form submit failure. This is my code:
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value=""/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
} else {
// Update name in DB
}
?>
</body>
</html>
I would like that name field keeps the inserted input text, after submit. I tried to do with php code in input value but doesn't work. Any ideas?
Solved. This is the solution that I was looking for.
I added in value tag of input the following:
<?php if (isset($_POST['name'])) echo $_POST['name']; ?>
Therefore input field would look like:
<input type="text" placeholder="Name" id="name" name="name" value="<?php if (isset($_POST['name'])) echo $_POST['name']; ?>"/>
Thanks for your responses, helped me.
<?php
$error = "";
$name = isset($_POST["name"])?$_POST["name"]:""; //Added condition
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST["name"];
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
} else {
// Update name in DB
}
?>
</body>
</html>
You can just echo $_POST['name'] in the value attribute of the input.
Make sure you check POST values to avoid XSS.
I also put up the update DB function, as you don't need to show the form to the user if the name in longer the 4 chars!
<?php
$error = "";
$name = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['name'])){ //change name content only if the post value is set!
$name = filter_input (INPUT_POST, 'name', FILTER_SANITIZE_STRING); //filter value
}
// Verify $_POST['name'] greater than 4 chars
if ( strlen($name) < 4 ){
$error= 'Name too short!';
} else {
// Update name in DB
// Redirect
}
}
?>
<html>
<head>
</head>
<body>
<form method="post" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" name="myForm" id="idForm">
<input type="text" placeholder="Name" id="name" name="name" value="<?php echo $name; ?>"/>
<input type="submit" value="submit"/>
</form>
<?php
echo "<h2>Input:</h2>";
echo $name;
if($error) {
// No Update AND refresh page with $name in text field
echo "<br/>" . $error;
};
?>
</body>
</html>
If you want to keep all values/inputs for further use you could achieve that with php session values.
Besides - you should use $_SERVER['SCRIPT_NAME'] instead of $_SERVER['PHP_SELF']
Mars

Database error doesn't get values inserted phpMyAdmin

ctimings.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="cstyle.css">
// <script type="text/javascript">
// function validate(form)
// {
// if(document.myForm.sno.value == "")
// {
// alert("Please Complete Serial NUmber");
// return false;
// }
// if(document.myForm.ssign.value == "")
// {
// alert("Please Complete Signature");
// return false;
// }
// if(document.myForm.empName.value == "")
// {
// alert("Please Complete Employee Name");
// return false;
// }
// if(document.myForm.empSign.value == "")
// {
// alert("Please Complete Employee Signature");
// return false;
// }
// if(document.myForm.empCode.value == "")
// {
// alert("Please Complete Employee Code");
// return false;
// }
// }
// </script>
<title>Conference Room Timings</title>
</head>
<body>
<form action = "ctimings.php" method = "post" name = "myForm" onsubmit="return validate(this);">
<legend>ADD DETAILS</legend>
<fieldset>
<label>Serial Number <input type = "int" name = "sno" size="20" class = "required" /></label><br/>
<label>Security Signature <input type = "text" name = "ssign" size="20" class = "required" /></label><br/>
<legend>Employee Details</legend>
<fieldset>
<label>Employee Name <input type = "text" name = "empName" size="20" class = "required" /></label><br/>
<label>Employee Signature <input type = "text" name = "empSign" size="20" class = "required"/></label><br/>
<label>Employee Code <input type = "int" name = "empCode" size="20" class = "required" /></label><br/>
</fieldset>
<legend>Date & Time</legend>
<fieldset>
<label>Date <input type = "int" name = "date" size="20" class = "required"/></label><br/>
<label>In - Time <input type = "int" name = "inTime" size="20" class = "required"/></label><br/>
<label>In - Time <input type = "int" name = "outTime" size="20" class = "required"/></label><br/>
</fieldset>
<legend>Usage</legend>
<fieldset>
<label>
Phone Set Usage
<input type = "radio" name = "radio1" value = "YES" />
<input type = "radio" name = "radio1" value = "NO" /><br/>
</label>
<label>
Projector Usage
<input type = "radio" name = "radio2" value = "YES" />
<input type = "radio" name = "radio2" value = "NO" /><br/>
</label>
</fieldset>
<input type = "submit" value = "SUBMIT" class = "" name = "SUBMIT"/>
</fieldset>
</form>
</body>
</html>
ctimings.php
<html>
<body>
<?php
if(isset($_POST['SUBMIT']))
{
echo "pressed";
$db_host = "localhost";
$db_username = "root";
$db_pass = "";
$db_name = "ibm";
$con=mysql_connect("localhost","root","","ibm");
// Check connection
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Not connected : ' . mysql_error());
}
else
{
echo 'Connection was OK';
}
$db_selected = mysql_select_db($db_name, $link);
if (!$db_selected) {
die ('Can\'t use ibm : ' . mysql_error());
}
else
{
echo "Database was OK!\n";
}
$sql = "INSERT INTO ctimings(sno,ssign,empName,empSign,date,intime,outtime,empCode,Proj.Use,Ph.Use) VALUES('$_POST[sno]','$_POST[ssign]','$_POST[empName]','$_POST[empSign]','$_POST[date]','$_POST[inTime]','$_POST[outTime]','$_POST[empCode]','$_POST[radio1]','$_POST[radio2]')";
mysql_query($sql,$link);
mysql_close($link);
}
else
echo 'error';
?>
</body>
</html>
It is a simple proceedure but i am not able to narrow down as to why is not the data being sent to the database as the phpmyadmin table "ctimings" shows that it has no record.After the submit button has been pressed it should post the data to the database but in vain.The database name and table names in the database are correct.
Your sql string is incorrect, it needs to be;
$sql = "INSERT INTO ctimings(sno,ssign,empName,empSign,date,intime,outtime,empCode,Proj.Use,Ph.Use) VALUES('".$_POST[sno]."','".$_POST[ssign]."','".$_POST[empName]."','".$_POST[empSign]."','".$_POST[date]."','".$_POST[inTime]."','".$_POST[outTime]."','".$_POST[empCode]."','".$_POST[radio1]."','".$_POST[radio2]."')";
To add onto the answers above, it might be an idea to sanitise your data.
$_POST = array_map('mysql_real_escape_string', $_POST);
your query would be like
$sql = "INSERT INTO ctimings(sno,ssign,empName,empSign,date,intime,outtime,empCode,Proj.Use,Ph.Use) VALUES
('".$_POST[sno]."','".$_POST[ssign]."','".$_POST[empName]."','".$_POST[empSign]."','".$_POST[date]."',
'".$_POST[inTime]."','".$_POST[outTime]."','".$_POST[empCode]."','".$_POST[radio1]."'
,'".$_POST[radio2]."')";
And you need to escape the post variables using mysql_real_escape_string
And main reason is due to Proj.Use,Ph.Use you are using insert into two tables at a time I think,
$_POST is a Global Array you have to use it like this $_POST["field_name"];

Categories