Code that Generates the HTML Form:
<form action='inc/q/prof.php' method='post'>
<input type='text' id='addComment' name='addComment' tabindex='3' value='Enter comment' />
</form>
*Php Code that is referenced in <form action = *
<?php
// Insert Comments into Database that user provides
$comm = mysql_real_escape_string($_POST['addComment']);
// following line has changed:
$pID4 = filter_input(INPUT_POST, 'pID', FILTER_SANITIZE_NUMBER_INT);
$cID = mysql_real_escape_string($_POST['courseInfoDD']);
$username = "####";
$password = "####";
$pdo4 = new PDO('mysql:host=localhost;dbname=####', $username, $password);
$pdo4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth4 = $pdo4->prepare('INSERT INTO Comment (info, pID, cID) VALUES(?,?,?);');
$sth4->execute(array($comm, $pID4, $cID ));
?>
Edit 2:
I assume you call prof.php?pID=120 and then you display the given form? And when you click the form the action references your PHP code? If so, then change the php file which prints your form to this:
<?
$pID = filter_input(INPUT_GET, 'pID', FILTER_SANITIZE_NUMBER_INT);
?>
<form action='inc/q/prof.php' method='post'>
<input type='text' id='addComment' name='addComment' tabindex='3' value='Enter comment' />
<input type="hidden" name="pID" value="<? echo $pID; ?>" />
</form>
Then, in the script handling your form submission, you can access the pID value via
$_POST["pID"]
as seen in my first edit, below:
Edit: Your PHP script would then look like this:
// Insert Comments into Database that user provides
$comm = mysql_real_escape_string($_POST['addComment']);
// following line has changed:
$pID4 = filter_input(INPUT_POST, 'pID', FILTER_SANITIZE_NUMBER_INT);
$cID = mysql_real_escape_string($_POST['courseInfoDD']);
$username = "###";
$password = "####";
$pdo4 = new PDO('mysql:host=localhost;dbname=####', $username, $password);
$pdo4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth4 = $pdo4->prepare('INSERT INTO Comment (info, pID, cID) VALUES(?,?,?);');
$sth4->execute(array($comm, $pID4, $cID ));
The hidden input field is the best way to pass the variables, since you can access it like a normal submitted POST variable (compare it with your $_POST['courseInfoDD']).
But remember to never use this for security relevant information, since this data can be viewed and changed (e.g. by javascript injection).
Related
I'm trying to select a PHP variable from a database insert it into an html form input. I guess my question is how do you store the query into a variable and then call that variable in an html form? Also, the form is located on a separate page from the form action file. Why is it undefined if it's defined in the PHP file? The desired output is when I load the html page the value from the database for nickname auto-fills that field of the form.
error:
Notice: Undefined variable: Nickname in C:\xampp\htdocs\Client-Projects\Crossfire\templates\CoinSubmission.html on line 45
CoinSubmission.html
<form autocomplete="off" action="AdminCoinSub_Code.php" method="POST">
<p>
<input type="text" name="Nickname" id="Nickname" value="<?php echo htmlspecialchars($Nickname); ?>" />
</p>
</form>
AdminCoinSub_Code.php
<?php {
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "administrator_logins";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO coin (ProfileID, Store, Position,
Nickname, ContactNumber, MachineCount, CutOffDate, Coins, location, LastSubmission, Rank)
VALUES (:ProfileID, :Store,:Position, :Nickname,:ContactNumber,:MachineCount,:CutOffDate, :Coins,:location,:LastSubmission,:Rank)");
$stmt->bindParam(':ProfileID', $_POST['ProfileID']);
$stmt->bindParam(':Store', $_POST['Store']);
$stmt->bindParam(':Position', $_POST['Position']);
$stmt->bindParam(':Nickname', $_POST['Nickname']);
$stmt->bindParam(':ContactNumber', $_POST['ContactNumber']);
$stmt->bindParam(':MachineCount', $_POST['MachineCount']);
$stmt->bindParam(':CutOffDate', $_POST['CutOffDate']);
$stmt->bindParam(':Coins', $_POST['Coins']);
$stmt->bindParam(':location', $_POST['location']);
$stmt->bindParam(':LastSubmission', $_POST['LastSubmission']);
$stmt->bindParam(':Rank', $_POST['Rank']);
$stmt->execute();
echo "Success";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
}
$conn=mysqli_connect($servername,$username,$password,$dbname);
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT `Nickname` FROM `adminlogin` WHERE `ProfileID` = ':ProfileID'";
$Nickname = $conn->query($query); // This is where the query is executed
$fetcher = $Nickname->fetch_assoc();
while($row = mysqli_fetch_array($Nickname))
if (mysqli_num_rows($Nickname) > 0) {
echo 'User name exists in the table.';
} else {
echo 'User name does not exist in the table.';
}
?>
First of all, your html page should have the extension .php and not .html, that way it can interpret your php code inside the html file, don't worry this wont break the html.
why is it undefined if it's defined in the php file.
It's because each php script run separately unless you hook them together.
I would recommend yo read a bit more about how php works.
For this example to work i would do it it this way.
CoinSubmission.php
<?php //This goes at the top of the file
include_once('AdminCoinSub_Code.php') //If they are in the same dir else you will need to set the path properly.
?>
<form autocomplete="off" action="AdminCoinSub_Code.php" method="POST">
<p>
<input type="text" name="Nickname" id="Nickname" value="<?php echo
htmlspecialchars($Nickname); ?>">
</p>
</form>
The include at the top will "paste" your code of AdminCoinSub_Code in the CoinSubmission file and treat it as one file. So the variable will be accesible for it.
Note: My explanation is oversimplified, it ain't exactily how it works, but should get the gist of it.
Alaa Morad answer if also valid, but remember to change the .html to .php
Happy Coding :)
That's because $Nickname will not be set if Register Globals is off witch is a normal thing !
Register Globals has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0
so use $_POST
<input type="text" name="Nickname" id="Nickname" value="<?php echo htmlspecialchars($_POST['Nickname']); ?>">
I am trying to save a form data into my database but I get just empty records.
I tryied many solutions but I really don't know where's the bug. I am getting crazy!
This is my form:
<head>
<form action="uploadall.php" method="post">
Name: <input type="text" name="name"><br>
Autore: <input type="text" name="author"><br>
Descrizione: <textarea id="editordescription" name="description" cols="45" rows="15">
</textarea>
<script>
CKEDITOR.replace( 'editordescription' );
</script>
<br>Misure: <input type="text" name="misure"><br>
Data: <input type="text" name="date"><br>
<input type="hidden" name="status" value="Disattivo" size="20">
<input type="submit">
</form>
And this is my PHP script to save records:
<?php
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string(htmlspecialchars($_POST['name']));
$author = mysqli_real_escape_string(htmlspecialchars($_POST['author']));
$description = mysqli_real_escape_string(htmlspecialchars($_POST['description']));
$misure = mysqli_real_escape_string(htmlspecialchars($_POST['misure']));
$date = mysqli_real_escape_string(htmlspecialchars($_POST['date']));
$status = mysqli_real_escape_string(htmlspecialchars($_POST['status']));
}
$servername = "xxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxxx";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO exposition (name, author, description, misure, date, status)
VALUES ('$name', '$author', '$description', '$misure', '$date', '$status')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
And this is what I get in my database at the moment:
First, you are mixing the mysql api's at somepoint you are using mysqli_* at some point u using mysql_* They don't mix. And mysql_* functions are depreciated they no longer supported by later versions of php. better use mysqli or pdo. this mysql_real_escape_string() or mysqlo_real_escape_string() is not safe enough to prevent you against sql injections. solution is simple better start using mysqli prepared statements or pdo prepared statements.
another error : <input type="text" name="name"> <input type="text" name="name"> these two inputs fields have the same name attribute php will only read one. and you will get an undefined index here $misure = $_POST['misure']; You need to activate error reporting while you are still developing so you can see your errors and notices:
add this at the top of every php page : ini_set('display_errors', 1);
error_reporting(E_ALL);
also date date is a reserved word for mysql so you better use something else for your column name or add backslashes date
Oh and your code never execute here :
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$author = mysql_real_escape_string(htmlspecialchars($_POST['author']));
$description = mysql_real_escape_string(htmlspecialchars($_POST['description']));
$misure = mysql_real_escape_string(htmlspecialchars($_POST['misure']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$status = mysql_real_escape_string(htmlspecialchars($_POST['status']));
}
Why is that? because you do not have POST value with the submit attribute name. <input type="submit"> see? your submit does not have a name attribute. therefore. This means
all this :
VALUES ('$name', '$author', '$description', '$misure', '$date', '$status')"; These are all undefined variables. I'm surprised why doesn't your server tell you that, with that error reporting enable you will get all those.
This is what u need to do to solve that :
Your html side.
<form action="uploadall.php" method="post">
Name: <input type="text" name="name"><br>
Autore: <input type="text" name="author"><br>
Descrizione: <textarea id="editordescription" name="description" cols="45" rows="15">
</textarea>
<script>
CKEDITOR.replace( 'editordescription' );
</script>
<br>Misure: <input type="text" name="misure"><br>
Data: <input type="text" name="date"><br>
<input type="hidden" name="status" value="Disattivo" size="20">
<input type="submit" name="submit">
</form>
uploadall.php
<?php
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
$servername = "xxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//check your inputs are set and validate,filter and sanitize
$name = $_POST['name'];
$author = $_POST['author'];
$description = $_POST['description'];
$misure = $_POST['misure'];
$date = $_POST['date'];
$status = $_POST['status'];
//prepare and bind
$sql = $conn->prepare("INSERT INTO exposition (name, author, description, misure, date, status)
VALUES (?,?,?,?,?,?)");
$sql->bind_param("ssssss", $name, $author, $description, $misure, $date);
if ($sql->execute()) {
echo "New record created successfully";
} else {
//you have an error
}
$conn->close();
}
?>
That's all good luck.
Update :
I corrected errors you told me and I am using PDO now but it still
doesn't work
I read that from your comments above, but you not telling us what the errors are, but I believe they are the ones I highlighted above.
with PDO this is how u will achieve your goal :
<?php
//connection
$servername = 'XXXXXXXXXXXXX';
$dbname = 'XXXXXXXXXXXXX';
$username = 'XXXXXXXXXXXXXX';
$password = 'XXXXXXXXX';
$charset = 'utf8';
$dsn = "mysql:host=$servername;dbname=$dbname;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $username, $password, $opt);
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
//check your inputs are set and validate,filter and sanitize
$name = $_POST['name'];
$author = $_POST['author'];
$description = $_POST['description'];
$misure = $_POST['misure'];
$date = $_POST['date'];
$status = $_POST['status'];
//prepare and bind
$stmt = $dbh->prepare("INSERT INTO exposition (name, author, description, misure, date, status)VALUES (?,?,?,?,?,?)");
if ($stmt->execute(array($name,$author,$description,$misure,$date,$status))) {
echo "New Record inserted success";
}
}
?>
Variable name problem E.g
Name: <input name="name">
and :
Misure: <input name="name">.This must be different.
Again, <input type="submit"> should be <input type="submit" name="submit">.
Hope, it will be helpful.
The variables you are using inside your INSERT Query are out of scope from the first if block where you are getting the data from your form. If the variables are initialized before the first if block it might work. like below..
$name = ""; $author = "";$description = "";$misure = "";$date = "";$status=";
if (isset($_POST['submit'])){ // as is}
I am trying to display a Website Title on my Home Page. This website title is stored in the database named mywebsite and in table settings. I want to update this with an input type text's value. The title is displayed perfectly but when I write something in the text field and submit it, the database doesn't update. I think I am doing everything right and there isn't any error displaying on my page, but still it is not working. Can anyone figure out the error?
Here's my code:
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
// Making connection
$con = mysqli_connect($host, $username, $password, $database);
// Making a sql query for "Website Title" and saving it in variable $query
$query = "SELECT * FROM settings WHERE NameOfSetting='Website Title'";
// Applying query
$result = mysqli_query($con, $query);
// Fetching data from database
$row = mysqli_fetch_array($result);
if (isset($_POST['submit'])) {
$title = $_POST['text'];
mysqli_query($con, "UPDATE settings SET TheSetting=$title WHERE NameOfSetting='Website Title'");
}
?>
<h1><?php echo $row['TheSetting']; ?></h1>
<form method="POST">
<input type="text" placeholder="Change the title" name="text">
<input type="submit" name="submit">
</form>
EDIT: When I enter any numbers in the field and then submit and refresh it works fine but it's only working with numbers not with alphabets. I don't know why?
This line:
SET TheSetting=$title
$title needs to be wrapped in quotes:
SET TheSetting='$title'
Sidenote: You may also want to change this line (as a security precaution):
$title = $_POST['text'];
to:
$title = mysqli_real_escape_string($con,$_POST['text']);
Try with
mysqli_query($con, "UPDATE settings SET TheSetting='$title' WHERE NameOfSetting='Website Title'");
Well you can always do some sort of error checking. I.e. using or die(mysqli_error);
$con = mysqli_connect($host, $username, $password, $database)or die(mysqli_error);
This will atleast give you an idea of what your proplem is. Use this error checking method every time you connect, query, or close a database.
use this code it will solve your problem.
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
// Making connection
$con = mysqli_connect($host, $username, $password, $database)or die(mysqli_error());
// Making a sql query for "Website Title" and saving it in variable $query
$query = "SELECT * FROM settings WHERE NameOfSetting='Website Title'";
// Applying query
$result = mysqli_query($con, $query);
// Fetching data from database
$row = mysqli_fetch_array($result);
if (isset($_POST['submit'])) {
$title = $_POST['text'];
mysqli_query($con, "UPDATE settings SET TheSetting='".$title."' WHERE NameOfSetting='Website Title'");
}
?>
<h1><?php echo $row['TheSetting']; ?></h1>
<form method="POST">
<input type="text" placeholder="Change the title" name="text">
<input type="submit" name="submit">
</form>
This might be a stupid problem but i'm new to this (this is a homework ^^) and i can't find a solution :)
i have a .php file with an html form plus some php code to execute a query and insert the values from the form in my DB. And it works, but every time the page is loaded the php code is executed and this insert in the DB a "blank" line, because obviously the form was not filled yet. This is the code
<html>
<head>
<meta charset="utf-8">
<meta name="generator" content="AlterVista - Editor HTML"/>
<title></title>
</head>
<body>
<form action="myPage.php" method="post">
ID: <input type="text" name="id" /> <br />
<input type="submit" name="Submit" value="Go" /> <br />
</form>
<?php
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_close();
?>
</body>
</html>
Is there a way to execute the php code only once the "Go" button on the form is executed?
Try:
if(isset($_POST['Submit'])) {
$user = "DB";
$password = "";
$host = "";
$database = "my_DB";
$connessione = mysql_connect($host, $user, $password);
#mysql_select_db($database, $connessione) or die( "Unable to select database");
$id = $_REQUEST['id'];
$query = "INSERT INTO myTable (ID) VALUES ('".$id."')";
mysql_query($query, $connessione);
mysql_close();
}
PHP will work before the page is rendered. You need to set up a condition to stop the PHP you don't want running until you submit the form.
if(isset($_POST['myform'])) {
// process the form
}else{
// html for form goes here
}
Hope that helps.
Assuming the form points to the script itself, there are numerous options :) Among others:
This first example just checks if a form was posted. If a normal (GET) request is received, it will do nothing, because it will not fall into your if-clause
// your form here
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// your php code
}
And this example checks if a variable with the name 'Submit' has been posted, and if so, if it has the value 'Go' in it. It is a slightly stricter check, but in your current example behaviour is exactly the same (so you can pretty much choose which one you like most ;))
// your form here
if(array_key_exists('Submit', $_POST) && $_POST['Submit'] == 'Go') {
// your php code
}
So I'm trying to input some session variables into the database, and I'm successfuly inserting all rows, except the $_SESSION['organisationId']. Some context: A user lands on a url as the one given in the snippit below, I get the organisationId, then want that user to be assigned that organisationId when they create the account - working as a sort of 'invite-system' of sorts.
// This is the URL I am using: http://thisapp.com/login.php?competitionId=51da7ed4d686a&organisationId=51d81cab92709
<?php
session_start();
ob_start();
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
include('db.php');
$_SESSION['competitionId'] = $_GET['competitionId'];
$_SESSION['organisationId'] = $_GET['organisationId'];
<h4>Create your Account</h4>
<form action="login.php" method="post" name="acceptinvite">
name: <input type="text" name="createname"><br>
email: <input type="text" name="createemail"><br>
password: <input type="password" name="createpassword"><br>
<input type="submit" value="Create Account">
</form>
<?php
if (isset($_POST["createname"]) && !empty($_POST["createname"])) {
//define variables
$name = mysql_real_escape_string($_POST['createname']);
$email = mysql_real_escape_string($_POST['createemail']);
$password = mysql_real_escape_string($_POST['createpassword']);
$teamLeader = 0;
$organisationId = mysql_real_escape_string($_SESSION['organisationId']);
$orgName = mysql_real_escape_string($_SESSION['orgName']);
//finish registering the user
$acceptInviteTeam = ("INSERT INTO `users` (`organisationId`, `name`, `email`, `password`, `isTeamLeader`) VALUES ('$organisationId', '$name', '$email', '$password', '$teamLeader')");
$result = mysql_query($acceptInviteTeam) or die (mysql_error());
}
else {
echo "Fill out the form and use the correct credentials";
}
?>
Here's what the problem is.
When you enter the link http://thisapp.com/login.php?competitionId=51da7ed4d686a&organisationId=51d81cab92709 you have organisationId and you save it in the session. But the target of the form is simply login.php. when you submit the form, there is no organisationId in the url, so the session variable gets overwritten by null.
This is the fix:
$_SESSION['competitionId'] = isset($_GET['competitionId']) ? $_GET['competitionId'] : $_SESSION['competitionId'];
$_SESSION['organisationId'] = isset($_GET['organisationId']) ? $_GET['organisationId'] : $_SESSION['organisationId'];
Alternatively you can use an if statement.