Using PHP to submit survey-form to database - php

I am setting up a survey to go at the bottom of our FAQ page, I am new to PHP, and this is my first time trying to connect to the database (without a tutorial).
I have the HTML page set up, a PHP set up, and a table set up in MySQL.
The database is creating a new row every time I submit, but all of the rows have "0" instead of the values assigned to the inputs/divs. Please help!
EDIT: I updated the HTML to now be a form, however, when I submit I get a 404 (and the rows do not update at all. What could be wrong?
Here is the HTML:
<?php
//error_reporting(0);
require 'db/connect.php';
?>
<!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">
<html>
<head>
<title>State Requirements Feedback</title>
<!--<link rel='stylesheet' type='text/css' href='stylesheet.css'/>-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script language="javascript">
$(document).ready(function() {
$('.rating').click(function() {
$('.rating').removeClass('selected');
ratingClick(this);
});
});
function ratingClick(that) {
console.log(that.id);
if (that.id == 'rating4' || that.id == 'rating5') {
$('#questions').fadeOut('slow');
$('#thankYou').fadeIn('slow');
} else {
$('#getMore').fadeIn();
$(that).toggleClass('selected');
}
}
$(document).ready(function() {
$('#submit').click(function(){
$('#questions').fadeOut('slow');
$('#thankYou').fadeIn('slow');
});
});
</script>
<style>
.ratings {
float: left;
width: 100%;
}
.rating {
margin: 7px;
font-weight: bold;
background-color: aliceblue;
}
.rating:hover {
background-color:#990000;
color: white;
}
#getMore {
display:none;
clear:both;
background-color:aliceblue;
border:solid black 1px;
padding:0px 5px 5px 10px;
margin:0px 0px 0px 7px;
}
#thankYou {
display:none;
font-weight: bold;
}
.selected {
background-color: #990000;
color: white;
}
textarea {
resize: none;
}
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
}
h2 {
margin-bottom: 5px;
font-size: 12px
}
</style>
</head>
<body>
<form id="questions" action="connect.php" method="post">
<h2>How helpful is this article?</h2>
<div class="ratings">
<input type="radio" name="Q1" class="rating" id="rating1" value="1">Not at all helpful
<input type="radio" name="Q1" class="rating" id="rating2" value="2">Not very helpful
<input type="radio" name="Q1" class="rating" id="rating3" value="3">Somewhat helpful
<input type="radio" name="Q1" class="rating" id="rating4" value="4">Very helpful
<input type="radio" name="Q1" class="rating" id="rating5" value="5">Extremely helpful
</div>
<div id="getMore">
<h2>Please tell us why you didn't find this article helpful:</h2>
<input type='checkbox' name="Q2_1" value="1">Not related to my issue<br/>
<input type='checkbox' name="Q2_2" value="1">Too complicated explanations<br/>
<input type='checkbox' name="Q2_3" value="1">Too much information<br/>
<input type='checkbox' name="Q2_4" value="1">Incorrect information<br/>
<input type='checkbox' name="Q2_5" value="1">Unclear information<br/>
<input type='checkbox' name="Q2_6" value="1">Incomplete information<br/>
<h2>Do you have any other feedback about this article?</h2>
<p><input type="text" name="Q3" /><p>
<div id = "submit"><input type='submit' value="Submit" /></div>
</div>
</form>
<div id="thankYou">
Thanks for your feedback!
</div>
</body>
</html>
Here is the php document:
<?php
define('DB_NAME', 'staterequirements');
define('DB_USER', 'myuser');
define('DB_PASSWORD', 'mypass');
define('DB_HOST', 'localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if(!$db_selected) {
die('Can\'t use ' . DB_NAME . ' : ' . mysql_error());
}
$Q1 = (isset($_POST['Q1']) ? $_POST['Q1'] : null);
$Q2_1 = (isset($_POST['Q2_1']) ? $_POST['Q2_1'] : null);
$Q2_2 = (isset($_POST['Q2_2']) ? $_POST['Q2_2'] : null);
$Q2_3 = (isset($_POST['Q2_3']) ? $_POST['Q2_3'] : null);
$Q2_4 = (isset($_POST['Q2_4']) ? $_POST['Q2_4'] : null);
$Q2_5 = (isset($_POST['Q2_5']) ? $_POST['Q2_5'] : null);
$Q2_6 = (isset($_POST['Q2_6']) ? $_POST['Q2_6'] : null);
$Q3 = (isset($_POST['Q3']) ? $_POST['Q3'] : null);
$sql = "INSERT INTO response (Q1, Q2_1, Q2_2, Q2_3, Q2_4, Q2_5, Q2_6) VALUES ('$Q1', '$Q2_1', '$Q2_2', '$Q2_3', '$Q2_4', '$Q2_5', '$Q2_6')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
}?>

These points are parts of your problem.
This:
<div id="questions" action="connect.php" method="post">
should be <form and not a div:
<form id="questions" action="connect.php" method="post">
And this:
<div class="ratings" name="Q1">
<div class="rating" id="rating1" value="1">Not at all helpful</div>
<div class="rating" id="rating2" value="2">Not very helpful</div>
<div class="rating" id="rating3" value="3">Somewhat helpful</div>
<div class="rating" id="rating4" value="4">Very helpful</div>
<div class="rating" id="rating5" value="5">Extremely helpful</div>
</div>
I'm not sure whether you wanted to use a dropdown menu select or checkboxes or radio buttons or inputs, however those divs are not valid form elements.
I would also like to point out that it is highly recommended that you use MySQLi_ and/or PDO instead of the deprecated MySQL_ because your (posted) code is open to injection.

Related

I got a problem with select option and value

I try to keep the value from selected options after the button is clicked.
For now, I have done this with my inputs(range,text) and it's working but I can't figure how to do this with my select option.
ADDITIONAL THINGS(you have to create them to run it)
c13ustawienia.php
<?php
$serwer='localhost';
$uzytk='root';
$haslo='';
$baza='komis';
?>
c13dane.txt
1993|Volkswagen|Passat|19000
1973|Opel|Blitz|12000
1997|Volkswagen|Passat|17000
2010|Mercedes|M5|29000
2001|Volkswagen|Passat|29000
1990|Volkswagen|Passat|23000
2018|Tesla|Super|129000
2018|sla|Super|9000
1992|Volkswagen|Passat|10000
2006|Audi|B9|74000
2009|Volkswagen|Passat|89000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Baza</title>
<style>
table {border-collapse: collapse;}
td,th {border: 1px blue solid;}
th {background-color: azure;}
.id {width: 20px; text-align: center;}
.mar {width: 90px;}
.mod {width: 70px;}
.rok {width: 40px; text-align: right;}
.cena {width: 50px; text-align: right;}
.zolty {background-color: yellow;}
.pomar {background-color:orange;}
[type=text] {width:60px;}
header {height: 60px; background-color:greenyellow;}
header>img {height: 75%; text-align: center;}
nav {height: 400px; width: 30%; background-color:khaki;
float: left;}
main {height: 400px; width: 70%; background-color:moccasin;
float: left;}
footer {height: 40px; background-color: powderblue;
clear: both; text-align: center; color:blue;}
</style>
<script>
function wartosc() {
min=document.getElementById('cmin');
max=document.getElementById('cmax');
wmin=document.getElementById('wmin');
wmax=document.getElementById('wmax');
minint=parseInt(min.value);
maxint=parseInt(max.value);
if(maxint<minint)
maxint=minint+1;
wmin.value=minint;
min.value=minint;
wmax.value=maxint;
max.value=maxint;
}
</script>
</head>
<body>
<?php
function tworz_baze() {
require('c13ustawienia.php');
$link=mysqli_connect($serwer, $uzytk, $haslo);
mysqli_query($link, "DROP DATABASE $baza");
mysqli_query($link, "CREATE DATABASE $baza");
mysqli_query($link, "USE $baza");
mysqli_query($link, "CREATE TABLE auta (
ID int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
marka varchar(20),
model varchar(25),
rok int(4),
cena double)");
return $link;
} // tworz_baze()
function czytajdane($plik) {
$f=fopen($plik, 'r');
while(!feof($f)) {
$linia=rtrim(fgets($f));
if(strlen($linia)>5)
$tab[]=explode('|', $linia);
}
return $tab;
} // czytajdane($plik)
function dobazy($link, $tablica) {
foreach ($tablica as $sam) {
list($rok, $mar, $mod, $cena)=$sam;
mysqli_query($link, "INSERT INTO auta VALUES
(NULL, '$mar', '$mod', $rok, $cena)");
}
} // dobazy($link, $tablica)
function pisz($li, $marka, $cenamin, $cenamax) {
echo "<h3>Wybrano:<br>marka: $marka<br>
zakres cen: $cenamin - $cenamax zł</h3>";
echo "<table>
<tr><th>id</th><th>marka</th><th>model</th>
<th>rok</th><th>cena</th></tr>";
$wyn=mysqli_query($li, "SELECT * FROM auta WHERE
marka='$marka' AND cena>=$cenamin AND cena<=$cenamax");
$licznik=FALSE;
while($wiersz=mysqli_fetch_array($wyn)) {
list($id, $mar, $mod, $rok, $cena)=$wiersz;
$kolor = $licznik ? 'zolty' : 'pomar';
echo "<tr class=\"$kolor\"><th class=\"id\">$id</td>
<td class=\"mar\">$mar</td>
<td class=\"mod\">$mod</td>
<td class=\"rok\">$rok</td>
<td class=\"cena\">$cena</td></tr>";
$licznik=!$licznik;
}
echo '</table>';
mysqli_close($li);
} // pisz($li, $model, $cenamax)
function filtry() {
if(isset($_GET['cmin']))
$tab['cmin']=$_GET['cmin'];
else
$tab['cmin']=0;
if(isset($_GET['cmax']))
$tab['cmax']=$_GET['cmax'];
else
$tab['cmax']=CENAMAKS;
if(isset($_GET['marka']))
$tab['marka']=$_GET['marka'];
else
$tab['marka']='Volkswagen';
return $tab;
} // filtry()
function lista($link) {
$w=mysqli_query($link, "SELECT DISTINCT marka
from auta ORDER BY marka");
while($m=mysqli_fetch_array($w))
echo '<option value="'.$m['marka'].'">'
.$m['marka'].'</option>';
// $x=$m['marka'];
// "<option value=\"$x\">....
} // lista($link)
?>
<header>
<img src="auto.png" alt="auto">
<span>Komis samochodowy</span>
</header>
<nav>
<h3>Filtry:</h3>
<form action="c41.php" method="GET">
Cena:<br>
od: <input type="range" name="cmin" id="cmin"
min="0" max="<?php echo CENAMAKS ?>" value="<?php echo $tf['cenamin'];?>"
onchange="wartosc()">
<br>
do :<input type="range" name="cmax" id="cmax"
min="0" max="<?php echo CENAMAKS ?>"
value="<?php echo $tf['cenamin'];?>"
onchange="wartosc()">
<br>
<input type="text" name="wmin" id="wmin" disabled
value="<?php echo $tf['cenamin'];?>"
> -
<input type="text" name="wmax" id="wmax" disabled
value="<?php echo $tf['cenamax'];?>"
><br>
<select name="marka" id="marka">
<?php lista($li); ?>
</select>
<input type="submit" value="Filtruj">
<input type="reset" value="Czyść">
</form>
</nav>
<main>
<?php pisz($li, $tf['marka'], $tf['cmin'], $tf['cmax']); ?>
</main>
<footer>
Adam Kowal ©
</footer>
</body>
</html>
To make inputs work I have giving them variable of function and pointed right key of database to have what I want, but i have no clue how to make it work with select option
frame of code that gives me what i want in inputs: value="<?php echo $tf['cenamin'];?>"
Change your code with the following:
First add a new parameter to the "lista" function to be able to mark the selected value, e.g.
function lista($link, $selected = "default") {
// function code here
}
Secondly, modify the function to respect the passed value and match it to the value gotten from the database:
while($m=mysqli_fetch_array($w)) {
$status = "";
if ($selected == $m['marka']) $status = "selected";
echo '<option '.$selected.' value="'.$m['marka'].'">' .$m['marka'].'</option>';
}
Thirdly, pass the selected value to the function in your code, e.g.:
<?php lista($li, $_GET['marka']); ?>
NB! You should NOT use your current code in any production environments: it includes several SQL injections and isn't built up by best practises (e.g. separating html from the program code etc).

How can I get $_POST to work with my PDO statement?

I can't seem to get $_POST to work with my sql query. I have tried both mysql_query and PDO.
$newartist = $_POST['newartist']; // This doesn't work with PDO statement
//$newartist = 'Hubert De Lartigue'; // This works with PDO statement!
//$query = $DBH->prepare("SELECT * FROM artist WHERE artist =?"); // Original Method
//$query->bindValue(1, $newartist, PDO::PARAM_STR); // Original Method
$query = $DBH->prepare("SELECT * FROM artist WHERE artist = :newartist"); // Suggested Method
//$query->bindParam(':newartist', $newartist); // Suggested method, tested
$query->bindParam(':newartist', $newartist, PDO::PARAM_STR); // Suggested method
$query->execute();
//foreach ($query as $row) { // Switched to while loop so it can "fetch"
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$selectedartist = '<option value="'.$row['artist_id'].'" selected="selected">'.$row['artist'].'</option>';
}
I can however echo $_POST['newartist']; and it will correctly output the artist's name!
The form per request (NOTE: you have to click the + to submit an artist and newartist echos properly after submitting a new artist):
<div style="background: #270126; padding: 0 20px;" id="artist" >
<form method="post" style="width: 100%">
Artist: <select name="artist" style="width: 200px; background: black;" class="required">
<?php
if(!empty($_POST['newartist'])) {
echo $selectedartist;
} else {
echo '<option value="2" selected="selected">Unknown-Artist</option>
'.$theartist.'';
}
?></select> +</div>
<div style="background: #270126; padding: 0 20px;" id="addnewartist" >
<fieldset style="display: none;height: 35px;" id="artistnew">
Artist Name:
<input name="newartist" id="newartist" style="width: 200px; display:inline;" /> Artist URL:<input name="artist_url" value="http://" />
<input type="submit" value="Submit New Artist" name="addartist" class="secondaryAction" style="display:inline;" />
</fieldset>
</div>
<fieldset id="artworknew" style="width: 100%;">
<div style="background: #270126; padding: 0 20px;">
Artwork Name: <input name="name" id="name" style="width: 300px;" />
</div>
<div style="background: #270126; padding: 0 20px;">
File Name: <input name="file" id="file" style="width: 300px" value=".jpg" /><br />
</div>
<div style="background: #270126; padding: 0 20px; height: 35px;">
Folder: <select name="folder" style="width: 200px; background: black;">
<option value="16">digitalart2</option>
<?=$thefolder;?></select>
<input name="disabled" type="checkbox" value="1" />Disable
<input name="dt1" type="hidden" value="<?=date("Y-m-d H:i:s");?>">
</div>
<div align="center">
<input type="submit" value="Submit Artwork" name="addartwork" class="primaryAction" />
</div></fieldset>
</form>
</div>
<?php
if ($_POST['addartist']) {
mysql_query("INSERT INTO `artist` ( `artist_id` , `artist`, `artist_url`)
VALUES (NULL , '".$_POST['newartist']. "', '".$_POST['artist_url']. "');") or die(mysql_error());
//echo '<meta http-equiv="refresh" content="0;url=?form=addart">';
}
if ($_POST['addartwork']) {
// list($subcategory, $subcategory_id, $type, $link, $width, $height) = split(":", $_POST['subcategory']);
// list($genre, $genre_id) = split(":", $_POST['genre']);
mysql_query("INSERT INTO `artwork` (`id`, `name`, `artist_id`, `file`, `folder_id`, `dt1`, `approved`, `disabled`)
VALUES (NULL ,
'".sql_inj_str($_POST['name'])."',
'".sql_inj_str($_POST['artist'])."',
'".sql_inj_str(htmlentities($_POST['file']))."',
'".sql_inj_str($_POST['folder'])."',
'".sql_inj_str($_POST['dt1'])."',
'1',
'".sql_inj_str($_POST['disabled'])."');
") or die(mysql_error());
//$qu=mysql_query("SELECT LAST_INSERT_ID() INTO #artwork;");
echo '<div align="center" style="margin-top: 25px;">..::[ Artwork Submitted! ]::..</div>';
}
include ('footer.php');
?>
I went through all the code you gave me. You have many bad html, css and javascript practices. It make your code hard to debug. I have improved your code and maybe if you can follow my logic and comments, you will figure out what's wrong with you code.
Basically, the code you showed me first is perfectly fine. The problem is with your design. You are entering null values for the id column instead of letting the database do it for you. You have a column for an artist_id and inserting in the artist there. Look at your database definitions to make sure that they have the correct structure and are getting the expected variables. Here is you code but made with good practices. If you can follow my code, you will find it easier to debug the problem.
<?php
/** I have re-wrote your code to give you a better way of writing code that makes it easier to debug**/
/**Store input fields as variables so I don't have to repeat certain things**/
$newartist = isset($_POST['newartist']) ? ($_POST['newartist']) : "Unkown Artist"; // either has a value or the value is Unknown Artist. Only has a value if the $_POST is set
$addartist = isset($_POST['addartist']) ? true : false; // the addartist has been posted or not
$addartwork = isset($_POST['addartwork']) ? true : false; // the addartwork has been posted or not
//This is for add new artist
if($addartist){
$newartist = isset($_POST['newartist']) ? $_POST['newartist'] :null;
$newartist = isset($_POST['artist_url']) ? $_POST['artist_url'] :null;
/**when you do new entry into a database, the primary key or the id field should be left alone,
it automatically updates itself. You must have a primary key in your database for things to work out properly**/
mysql_query("INSERT INTO `artist` ( `artist`, `artist_url`)
VALUES ('". $newartist . "', '". $artist_url . "');") or die(mysql_error());
}else{
$newartist = null;
$artist_url = null;
}
/// this is for adding artwork
if($addartwork){
$name = isset($_POST['name']) ? $_POST['name'] :null;
$artist = isset($_POST['artist']) ? $_POST['artist'] :null;
$file = isset($_POST['file']) ? htmlentities($_POST['file']) :null;
$folder = isset($_POST['folder']) ? $_POST['folder'] :null;
$dt1 = isset($_POST['dt1']) ? $_POST['dt1'] :null;
$disabled = isset($_POST['disabled']) ? 1 : 0;
// list($subcategory, $subcategory_id, $type, $link, $width, $height) = split(":", $_POST['subcategory']);
// list($genre, $genre_id) = split(":", $_POST['genre']);
/**when you do new entry into a database, the primary key or the id field should be left alone,
it automatically updates itself. You must have a primary key in your database for things to work out properly**/
//There is a problem with you artist_id column. The artist has a string value, and you have an id column in the database
//Also you have a sql_inj_str() function. I am guessing that you have difined this function somewhere.
mysql_query("INSERT INTO `artwork` ( `name`, `artist_id`, `file`, `folder_id`, `dt1`, `approved`, `disabled`)
VALUES (NULL ,
'".sql_inj_str($name)."',
'".sql_inj_str($artist)."',
'".sql_inj_str(htmlentities($file))."',
'".sql_inj_str($folder)."',
'".sql_inj_str($dt1)."',
'1',
'".sql_inj_str($disabled)."');
") or die(mysql_error());
//$qu=mysql_query("SELECT LAST_INSERT_ID() INTO #artwork;");
echo '<div align="center" style="margin-top: 25px;">..::[ Artwork Submitted! ]::..</div>';
}else{
$name = null;
$artist = null;
$file = null;
$folder = null;
$dt1 = null;
$disabled = 0;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Query PDO</title>
<!-- Put the styles (CSS) seperate from the html, easier to maintain. You can just copy these styles into an external file and just link it-->
<style>
#artist {
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
form {
width: 100%;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
select {
width: 200px;
/**background: black;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
}
/** give the tag in the html a class name or id in the html and replace the tag name here with the class or id given **/
a {
width: 15px;
font-size: 1.5em;
display:inline;
/**added a myself**/
text-decoration: none;
}
#addnewartist{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
fieldset#artistnew{
display: none;
height: 35px;
}
form #newartist {
width: 200px;
display:inline;
}
form .secondaryAction{
display:inline;
}
#artworknew{
width: 100%;
}
/** I now had no choice but to add in a few class names here**/
.ArtworkName{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
input[name='name'] {
width: 300px;
}
.FileName{
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
}
input[name='file'] {
width: 300px;
}
.Folder {
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
padding: 0 20px;
height: 35px;
}
select[name='folder'] {
width: 200px;
/**background: #270126;**/
/** I just used a different color from yours so that I can see, design choice**/
background: linen;
}
</style>
</head>
<body>
<form method="post">
<!-- move the div inside the form-->
<div id="artist" >
Artist:
<select name="artist" class="required">
<?php echo '<option value="' . $newartist . '" selected="selected">' . $newartist . '</option>'; ?>
</select>
<!--When the link is clicked it runs the doStyles function-->
+
<!-- get all the javascript out of the anchor tag. You can use jquery or external javscript but doing it this way is really really bad practice-->
<script>
// You can store this code in an external javscript file and embed it here
function doStyles(){
document.getElementById('artistnew').style.display='block';
document.getElementById('artworknew').style.display='none';
document.getElementById('artist').style.display='none';
}
</script>
</div>
<div id="addnewartist" >
<fieldset id="artistnew">
Artist Name:
<input name="newartist" id="newartist" />
Artist URL:
<input name="artist_url" value="http://" />
<input type="submit" value="Submit New Artist" name="addartist" class="secondaryAction" />
</fieldset>
</div>
<fieldset id="artworknew" >
<div class="ArtworkName">
Artwork Name:
<input name="name" id="name" />
</div>
<div class="FileName">
File Name:
<input name="file" id="file" value=".jpg" /><br />
</div>
<div class="Folder">
Folder:
<select name="folder" >
<option value="16">digitalart2</option>
<?=$thefolder;?>
</select>
<input name="disabled" type="checkbox" value="1" />Disable
<input name="dt1" type="hidden" value="<?=date("Y-m-d H:i:s");?>">
</div>
<div align="center">
<input type="submit" value="Submit Artwork" name="addartwork" class="primaryAction" />
</div>
</fieldset>
</form>
</div>
</body>
</html>
Everything looks OK. Check you form again, and make sure the name attribute is correct. Also, if you are typing in the name on the search form, make sure you are taking care of the case sensitive. The name should match the name in the database.
Use bindParam
Try taking out the PDO::PARAM_STR for now.
Lastly try this:
$result = $query->execute();
and then use $result in the for each loop

How to process submission without refreshing the page

Hi I am facing some problems in submitting form without refreshing, I know that it has something to do with "return false " but i just dont know where and how to use it. I tried refreshing the page by placing it in (if there are errors) but it just doesnt seem to work. Can you guys help me out??
<?php
$message = '';
$errors = array();
$noErrors = true;
$haveErrors = !$noErrors;
require_once('validations/tradeformresult.php');
if ($noErrors && $userArriveBySubmittingAForm) {
require_once('price.php');// INSERTION
echo "<script type='text/javascript'>\n";
echo "</script>";
echo "<script type='text/javascript'>\n";
echo "alert('Trade is successfully executed!');\n";
echo "</script>";
///////////MESSAGE/////////////////
}
elseif ($haveErrors && $userArriveBySubmittingAForm) {
echo "<script type='text/javascript'>\n";
echo "alert('Please re-enter your parameters.');\n";
echo "return false";
echo "</script>";
}
else if ($userArriveByClickingOrDirectlyTypeURL) { // we put the original form inside the $message variable
$newTitle = 'The link is broken';
$h1Title = '';
$message = '';
}
?>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
</script><head><meta charset="UTF-8"></head>
<style type="text/css">
div#overlay {
display: none;
z-index: 2;
background: #000;
position: fixed;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
text-align: center;
}
div#specialBox {
display: none;
position: relative;
z-index: 3;
p.padding;
padding-top:25px;
padding-bottom:25px;
padding-right:50px;
padding-left:50px;
margin: 150px auto 0px auto;
border: 3px solid blue;
outline: 3px solid darkblue;
width: 500px;
height: 500px;
overflow:auto;
background: #FFF;
color: #000;
}
div#wrapper {
position:absolute;
top: 0px;
left: 0px;
padding-left:24px;
}
</style>
<script type="text/javascript">
function toggleOverlay(){
var overlay = document.getElementById('overlay');
var specialBox = document.getElementById('specialBox');
overlay.style.opacity = .8;
if(overlay.style.display == "block"){
overlay.style.display = "none";
specialBox.style.display = "none";
} else {
overlay.style.display = "block";
specialBox.style.display = "block";
}
}
</script>
</head>
<body>
<!-- Start Overlay -->
<div id="overlay"></div>
<!-- End Overlay -->
<!-- Start Special Centered Box -->
<div id="specialBox" style="display:none">
<script>
</script>
<p>Create Order
<p><?php
$timestamp=time(); require_once 'start.php';
?>
<form method="post" name="formSubmitted" **return false;"**>
<input type="hidden" name="formSubmitted" value="true" runat="server">
<?php echo $message; ?>
<?php ?>
<?php if ($haveErrors || $userArriveByClickingOrDirectlyTypeURL) : ?>
<fieldset>
<p>Symbol : <select name = "selection" id="selection">
<option disabled = "disabled" selected = "selected"> Choose one </option>
<option value="eur/usd"<?php If($selection=='eur/usd'){Echo 'selected';}?>>EUR/USD</option>
<option value="usd/jpy"<?php If($selection=='usd/jpy'){Echo 'selected';}?>>USD/JPY</option>
<option value="usd/cad"<?php If($selection=='usd/cad'){Echo 'selected';}?>>USD/CAD</option>
<option value="eur/jpy"<?php If($selection=='eur/jpy'){Echo 'selected';}?>>EUR/JPY</option>
<option value="eur/chf"<?php If($selection=='eur/chf'){Echo 'selected';}?>>EUR/CHF</option>
<option value="gbp/usd"<?php If($selection=='gbp/usd'){Echo 'selected';}?>>GBP/USD</option>
<option value="aud/usd"<?php If($selection=='aud/usd'){Echo 'selected';}?>>AUD/USD</option>
<option value="usd/chf"<?php If($selection=='usd/chf'){Echo 'selected';}?>>USD/CHF</option>
</select><font color="red"><?php echo $selectionError?></font>
<p> Date : <input type="datetime" value="<?php echo date("Y-m-d ",$timestamp); ?>"READONLY name="date"/></p>
<p> Type : <input type="radio" name="type" value="buy"<?php if ($type == 'buy') echo 'checked'; ?>CHECKED> Buy <input type="radio" name="type" value="sell" <?php if ($type == 'sell') echo 'checked'; ?>>Sell<font color="red"><?php echo $typeError;?></font></p>
<p> Size : <input type="number"pattern="[0-9]+([\.|,][0-9]+)?" step="0.01"min="0"name="size"value="<?php echo $size;?>"/><font color="red"><?php echo $sizeError?></font></p>
<p> Bid Price (Sell) : <input id="bidprice" READONLY name="bidprice" type="text" value="<?php echo $bidprice;?>"/><font color="red"><?php echo $bidpriceError?></font></p>
<p> Offer Price (Buy) :<input id="offerprice" READONLY name="offerprice" type="text" value="<?php echo $offerprice;?>"/><font color="red"><?php echo $offerpriceError?></font> </p>
<p> Stop Loss : <input type="number"step="any"min="0" name="stoploss" value="<?php echo $stoploss;?>"/><font color="red"><?php echo $stoplossError?></font></p>
<p> Take Profit : <input type="number"step="any"min="0"name="takeprofit"value="<?php echo $takeprofit;?>"/><font color="red"><?php echo $takeprofitError?></font></p>
</fieldset>
<div align="center">
<input type="submit" value="Submit" Onsubmit =**"return false"**;/><button onmousedown="toggleOverlay()">Close </button>
</div>
<input type="reset" name="Reset" value="Reset" tabindex="50">
<?php endif; ?>
</form>
</script>
</body>
</html></p>
</div>
</div>
<!-- Start Special Centered Box -->
<!-- Start Normal Page Content -->
<div id="wrapper">
<h2>Trade</h2>
<button onmousedown="toggleOverlay();**return false;"**>Create Order</button>
</div>
<!-- End Normal Page Content -->
</body>
</html>
<?php
?>
Unless you are using AJAX, you can't really do this from PHP. Once a form submits, that's it. Simple validation can be done in the browser. Bind a validation function to your form's submit event. That's the thing you return false or true from.
(You would of course validate again on the server.)
It looks from your code like you're trying to run some php code (tradeformresult.php). Loading it this way isn't going to work as expected-that require_once will be run as the page is being built in PHP, not in the browser.
For sending a form without refreshing the page, you should look into AJAX (http://en.wikipedia.org/wiki/Ajax_(programming))
JQuery has a good AJAX method. Here is a simple example of how to use it:
$.ajax({url:"http://www.someserver.com/api/path",
data:{val1:"value",val2:"value"})
.success(function(returnData) {
console.log(returnData);
});
The above will call the given URL with the given data as parameters, then, if successful, will return whatever data the server gave back into the returnData variable.
If you're using AJAX, you don't really even have to use a <form> tag, since you'll be building the query string manually. You can have the function that makes the AJAX call be triggered from the onClick event of a button.

Can I use PHP print as Input Field's default Value?

I have placed a php code for getting current page URL and now I can get current page URL by writing this code
<?php print(selfURL()); ?>
Now, I want to know how can I write this code as the default value of Input field?
Actually I want the Input field to automatically filled up with the current page URL.
When I use <?php print(selfURL()); ?> as value="<?php print(selfURL()); ?>" it simple shows a text and don't display current url. But when I paste it in other place then its working fine.
Any suggestions?
UpDATE:
Guys, this is the full code of the page, may be it helps!
<?php
function selfURL() { $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : ""; $protocol = strleft(strtolower($_SERVER["SERVER_PROTOCOL"]), "/").$s; $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]); return $protocol."://".$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI']; } function strleft($s1, $s2) { return substr($s1, 0, strpos($s1, $s2)); }
?>
<?php
// Start YOURLS engine
require_once( dirname(__FILE__).'/includes/load-yourls.php' );
?>
<!DOCTYPE html>
<html>
<head>
<title>YOURLS Public Interface Sample</title>
<style>
body {
background:#E3F3FF;
color:#595441;
font:16px/30px verdana,arial,sans-serif;
}
a, a:visited {color:#2A85B3}
h1 {text-align:center; color:#2A85B3}
h2 {
border-bottom:1px solid #2A85B3;
color:#2A85B3;
margin-left:-10px;
padding-left:25px;
width:80%;
}
#container {
width: 780px;
margin-left: auto;
margin-right: auto;
background-color: #fff;
border: 3px solid #2A85B3;
padding: 10px;
margin-top: -13px;
-moz-border-radius:15px;
-webkit-border-radius:15px;
}
#footer {
text-align:center;
margin-top:20px;
}
#footer p {
padding:5px;
background:white;
margin:0 auto;
width:750px;
-moz-border-radius:10px;
border-radius:10px;
-webkit-border-radius:10px;
border:1px solid #2A85B3;
-moz-border-radius-bottomleft:35px;
-moz-border-radius-bottomright:35px;
-webkit-border-bottom-left-radius:25px;
-webkit-border-bottom-right-radius:25px;
}
#footer p a {
background:#fff url(http://yourls.org/images/favicon.gif) 2px center no-repeat;
padding-left:20px;
}
div#copybox { width:600px; height:auto;}
div#sharebox {height:auto; width:600px; margin-top:20px;}
</style>
<link rel="stylesheet" href="<?php echo YOURLS_SITE; ?>/css/share.css?v=<?php echo YOURLS_VERSION; ?>" type="text/css" media="screen" />
<script src="<?php echo YOURLS_SITE; ?>/js/jquery-1.6.1.min.js" type="text/javascript"></script>
<script src="<?php echo YOURLS_SITE; ?>/js/ZeroClipboard.js?v=<?php echo YOURLS_VERSION; ?>" type="text/javascript"></script>
<script type="text/javascript">ZeroClipboard.setMoviePath( '<?php echo YOURLS_SITE; ?>/js/ZeroClipboard.swf' );</script>
<script src="<?php echo YOURLS_SITE; ?>/js/share.js?v=<?php echo YOURLS_VERSION; ?>" type="text/javascript"></script>
</head>
<body>
<h1>YOURLS: Your Own URL Shortener</h1>
<div id="container">
<?php
// Part to be executed if FORM has been submitted
if ( isset($_REQUEST['url']) ) {
$url = yourls_sanitize_url( $_REQUEST['url'] );
$return = yourls_add_new_link( $url );
$shorturl = isset( $return['shorturl'] ) ? $return['shorturl'] : '';
echo <<<RESULT
<h2>URL has been shortened</h2>
<p>Original URL: <code>$url</code></p>
<p>Short URL: <code>$shorturl</code></p>
RESULT;
// Part to be executed when no form has been submitted
} else {
$site = YOURLS_SITE;
echo <<<HTML
<h2>Enter a new URL to shorten</h2>
<form method="post" action="">
<p><label>URL: <input type="text" name="url" value="<?php echo selfURL(); ?>" size="70" /></label></p>
<p><label>Optional custom keyword: $site/<input type="text" name="keyword" size="8" /></label></p>
<p><label>Optional title: <input type="text" name="title" size="57" /></label></p>
<p><input type="submit" value="Shorten" /></p>
</form>
HTML;
}
?>
</div>
<?php print(selfURL()); ?>
</body>
</html>
Try this,
<input name="textVal" type="text" val=<?php echo selfURL(); ?> />
You can use like below.
Method 1
<input name="myinput" type = "text" value = "<?php print(selfURL()); ?>" />
Method 2
<input name="myinput" type = "text" value = "<?php echo selfURL(); ?>" />
Answer after question has been updated
<input type="text" name="" id="" value="<?php echo $_SERVER['PHP_SELF']; ?>"/>
below is the solution : $_SERVER['PHP_SELF'];
Tested Code is as below
<input type="text" name="" id="" value="<?php echo $_SERVER['PHP_SELF']; ?>"/>
your code edit
$var = $_SERVER['PHP_SELF'];
OR
$var = selfURL();
<p><label>URL: <input type="text" name="url" value="$var" size="70" /></label></p>
You are adding php inside her-doc syntax and that's the error

Toggle Panels With PHP

I wonder whether someone may be able to help me please.
From some demos and tutorials I've found, I've put together this page which adds toggle panes to a page using values from a mySQL database to populate the fields.
The problem I'm having is that at each layer only the first out of multiple records is shown.
e.g. The screen currently shows 16/03/2012 as the only record, there should be one other record for the 23/02/2012.
Then within the 16/03/2012, the next level should show two items, whereas it is only showing one.
I've been working on this for a while now but I can't seem to find the solution of how to show the correct number of records.
I just wondered whether someone could perhaps have a look at this please and let me know where I'm going wrong.
I've added the full script below for reference.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Panel Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".content").hide();
//toggle the componenet with class msg_body
jQuery(".heading").click(function()
{
jQuery(this).next(".content").slideToggle(500);
});
});
</script>
<style type="text/css">
body {
margin: 20px auto;
font: 12px Verdana,Arial, Helvetica, sans-serif;
}
.layer1 {
margin: 0;
padding: 0;
width: 500px;
}
.heading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.content {
padding: 5px 10px;
background-color:#fafafa;
}
p { padding: 5px 0; }
</style>
</head>
<?php
mysql_connect("hostname", "username", "password")or
die(mysql_error());
mysql_select_db("database");
$result = mysql_query("SELECT userdetails.userid, finds.dateoftrip, detectinglocations.locationname, finds.userid, finds.locationid, detectinglocations.locationid, finds.findname, finds.finddescription FROM userdetails, finds, detectinglocations WHERE finds.userid=userdetails.userid AND finds.locationid=detectinglocations.locationid AND finds.userid = 1 ORDER BY dateoftrip DESC");
if (mysql_num_rows($result) == 0)
// table is empty
echo 'There are currently no finds recorded for this location.';
else
{
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
{
}
}
}
?>
<body>
<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
</div>
</div>
</body>
</html>
Many thanks and kind regards
You are fetching all the records but using only the last one.
You should put this:
<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
</div>
</div>
in the while loop which fetch the data:
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
So it will look like this:
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
echo '<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="'.$dateoftrip.'" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="'.$findname.'" disabled="disabled"/>
</div>
</div>';
}
You need to put your output inside your loop. Also you may have to modify your javascript to account for the multiple content ids.
You should also make the form controls into arrays so you'll be able to parse them if needed (see below).
For example, this is how to modify the form.
?>
<body>
<div class="layer1">
<?php
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
$i++;
?>
<p class="heading"><input name="dateoftrip[]" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname[]" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
<?php
{
}
}
}
?>
</div>
</div>

Categories