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']); ?>">
Related
I have a simple form set up in HTML to pass values to PHP and put them in a MYSQL database. I just can't fathom why nothing is happening when I click the submit button. Previously it was saying 'failed' but now nothing. I have checked the values from the form - fine. I've checked the database connection - fine. I've checked the SQL statement - well, I can't see any errors.
This is my main HTML page
<p class="subtitle">Let me know what you think</p>
<form action="db_insert.php">
<input name="username" placeholder="Name">
<br>
<textarea name="comments" placeholder="Please type your comments here"
cols=120 rows=5></textarea>
<br>
<input type="button" name="submit" value="submit">
<br>
<p id="commTitle">Comments</p>
<br>
<p id="comment"></p>
This is the PHP
<?php
include 'db_connection.php';
//create database connection
$conn = OpenCon();
$username = htmlspecialchars($_POST['username']);
$comment = htmlspecialchars($_POST['comment']);
$sql = 'INSERT INTO sitecomments(username, comment) VALUES(:username,:comment)';
$stmt = $conn -> prepare($sql);
$stmt -> bindValue(':username', $username);
$stmt -> bindValue(':comment', $comment);
$q_result = $stmt -> execute();
if($q_result){
echo 'Comment Inserted Successfully';
}
else{
echo 'Failed';
}
db_connection.php looks like this (with credentials removed.
<?php
function OpenCon(){
//pass the database details to variables
$host = "localhost";
$dbuser = "*****";
$dbpass = "*****";
$dbname = "*****";
// combine host and db name in to single variable
$dbhost = "mysql:host=$host;dbname=$dbname";
//create PDO from database information
$dbconn = new PDO($dbhost, $dbuser, $dbpass);
return $dbconn;
}
?>
As I said, I've checked the database connection and all is fine so where on earth am I going wrong? My database has 3 fields but one is autoincremented so I haven't included it in the query. I tried the query in MyPHPAdmin and it passed ok.
The first thing I notice is that the input has name of "comments" rather than the $_POST variable you're accessing called comment:
<textarea name="comments" placeholder="Please type your comments here" cols=120 rows=5></textarea>
$comment = htmlspecialchars($_POST['comment']);
Try changing that and see if it fixes the issue.
It would be helpful to handle errors within your code. In your current example if something goes wrong you will have a hard time finding out where the problem is.
You can try all of the following examples from the PHP Docs on PDO error handling and PDO::errorInfo:
Assert your connection is valid:
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
Assert your SQL is valid
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
As usual the error is a pebcak error, and you need to utilize proper debugging tools to find out where your mistakes are. Good luck!
I want to validate my form using JQuery and use php to send it to my database.
This is what I've tried:
<body>
<form id="first_form" method="post" action="">
<div>
<label for="first_name">First Name:</label>
<input type="text" id="first_name" name="first_name"></input>
</div>
<div>
<label for="last_name">Last Name:</label>
<input type="text" id="last_name" name="last_name"></input>
</div>
<div>
<label for="handphone">Handphone:</label>
<input type="text" id="handphone" name="handphone"></input>
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
<script>
$(document).ready(function() {
$('#first_form').submit(function(e) {
e.preventDefault();
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var handphone = $('#handphone').val();
$(".error").remove();
if (first_name.length < 1) {
$('#first_name').after('<span class="error">This field is required</span>');
return false;
}
if (last_name.length < 1) {
$('#last_name').after('<span class="error">This field is required</span>');
return false;
}
if (handphone.length < 1) {
$('#handphone').after('<span class="error">This field is required</span>');
return false;
}
});
});
</script>
<?php
$first_name = "<script>var first_name = $('#first_name').val();</script>";
$last_name = "<script>var first_name = $('#last_name').val();</script>";
$handphone = "<script>var first_name = $('#handphone').val();</script>";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO vali (first_name, last_name, handphone)
VALUES (first_name, last_name, handphone)";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
</body>
So as you can see, the first part is just the html and form.
The second part is where I used Jquery to validate (which works).
Now the issue is at the php part, where it sends the data to my database as empty.
The logic behind my php code is that, I take the values of the variables I set in Jquery and just update it to the database. But its updating empty values.
I tried to return false in Jquery, but its not working for me. May I know what am I doing wrong here?
Firsty, you have to understand JavaScript in this case is a client-scripting language and PHP is a server-scripting language. Variables can't be pass from JavaScript to PHP is the <script> tag.
Secondly, we have different types of requests; GET, POST, PUT, DELETE and so on. This we can check via PHP. A form can only send two types of request as at the time of me typing this answer, GET and POST request, this is the method value you set in your form. Every value set in a form can be accessed in the request global array and the name of the value being the key/indetifier. $_GET[] if you sent a get request and $_POST[] if you sent a post request.
In your form above, your method is set to POST, meaning all the values would be available in the global $_POST[].
When ever a page loads, the server script gets loaded first before the Client Side / HTML / CSS and other resources used by your document.
PHP has a function called isset() which is used to check if a variable available regardless it's value which is very useful for form validation.
If you ever have PHP codes in file performing logic/operations, it is advisable you placed them topmost of you file since it isn't used in rendering your document/view.
From your code, you should edit as
<?php
if(isset($_POST['submit'])){
// This block will only be executed when a submit button is triggered
//Make your connection here, it is not a must but good practice to always make connection first in order to make it available everywhere. Ensure to check if connection was successful or not.
$first_name = $_POST['first_name']; // this gives you the exact value you passed in the form.
...
// All you variables should be assigned using the above method
//in the above assignation of variables, we didn't sanitize. mysqli has a method real_escape_string() which does that for us. Ensure to always sanitize and properly validate inputs you send to your DB
//Sanitizing inputs
$first_name = $con ->real_escape_string($first_name);
// Do the above for other inputs, then you are good to perform an insert.
$result = $conn->query($sql);
if($result){
//Record has been inserted, you can choose to redirect or do some other logic
}else{
//Record was not successfully inserted. Print your error if in development to get an insight to what went wrong
}
}
$conn->close()
?>
I have a form on an HTML webpage that sends a user's comment and name to a MySQL database table, where it is stored, and then included back onto the page. The problem is, if the user's name has an apostrophe in it, the server (I pay for hosting, it's not my server and I can't change the configuration on it) is sending them to a error page that says:
"The requested URL was rejected. If you think this is an error, please contact the webmaster.
Your support ID is: 13509873612934211694"
UPDATE:
I just completely rewrote the page using a different php format. Now the apostrophe issue and the server error is fixed. However, the page is sending blank entries to the database on every page load. Any ideas?
<?php
$servername = "my_server";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
$users_name = htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8');
$users_request = $_POST['requests'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$conn->exec("INSERT INTO submissions (requests, name)
VALUES ('$users_request', '$users_name')");
$conn->commit();
header("Location: clv3.php");
}
catch(PDOException $e)
{
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="POST" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Make A Request:<br>
<textarea name='requests' id='requests'></textarea> <br>
Your Name (a-z only):<br>
<input type='text' name='name' id='name'/><br>
<input type='submit' value='Send' class='button'>
</form>
Ever heard of SQL injection? This is one you create...
Always escape your data! You are now pushing data given by user directly into database.
$name = mysqli_real_escape_string($conn, $_POST['name']);
$comments = mysqli_real_escape_string($conn, $_POST['comments']);
Also you can encode special chars before insert, and decode when showing
Did you perhaps try:
encodeURI(yourString)
Then on php side you do:
url_decode($_POST['myVariable'])
I have been trying to get this to work for some hours. I have researched many threads on here trying to see if I could find the problem with my code. I am new to PHP and I keep getting a Internal Server error, but I cant seem to track it down. I have tried all sorts of methods suggested online to get this to work with no luck. Its a basic user signup form in HTML, in a PHP file.(I was going to do both html and php on the same file but could not get that to work) The idea is to have the form submit to my MYSQL database to a customer table. If any of you could shed some light on what I am doing wrong or point me in the right direction, it would be much appreciated. Thanks in advance.
HTML
<form id="signupField" action="register.php" method="post">
First Name:<br>
<input type="text" name="FN" size="auto"/><br>
Last Name:<br>
<input type="text" name="LN" size="auto"/><br>
Street Address:<br>
<input type="text" name="SA" size="auto"/><br>
City:<br>
<input type="text" name="City" size="auto"/><br>
State:<br>
<input type="text" name="ST" size="auto"/><br>
Zip:<br>
<input type="text" name="Zip" size="auto"/><br>
Email Address:<br>
<input type="text" name="Email" size="auto"/><br>
Password:<br>
<input type="text" name="Password" size="auto"/><br>
<input type="submit" value="submit" name="submit"/>
</form>
Referenced PHP:
<?php
$hostname = "localhost";
$username = "serviceaccount";
$password = "password";
$dbname = "nameofdb";
$conn = new mysqli($hostname,$username,$password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
<?php
$FName=$_POST["FN"];
$LName=$_POST["LN"];
$SA=$_POST["SA"];
$City=$_POST["City"];
$State=$_POST["ST"];
$Zip=$_POST["Zip"];
$Email=$_POST["Email"];
$Password=$_POST["Password"];
if (isset($_POST["submit"])) {
$sql = "INSERT INTO Customers(FName,LName,StreetAddress,City,State,Zip,Email,Password) VALUES('$_POST["FN"]','$_POST["LN"]','$_POST["SA"]','$_POST["City"]','$_POST["ST"]','$_POST["Zip"]','$_POST["Email"]','$_POST["Password"]')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New record created successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
$conn->close();
}
}
?>
EDIT After finding this error: Connection failed: Unknown MySQL server host 'localhost:3306' (0) I was able to solve the connection issue to the database. Now when I put in the rest of the PHP back in I get a 500 Error still. It definitely narrows down where the issue is though!
EDIT I want to thank you all for you help on here. The main issue was the SQL connection. After I got that taken care of, I found that I had an extra bracket in place which was the cause for the other internal error I was receiving.
First, the "basic check" question: the html with the form and register.php are in the same directory, right? Not includes, requires, etc
If you have access to the apache error_log, check it out first to see the error message you're getting. If you can't understand it, post it here to help you.
If you don't have acccess to the file, first we need to find where are you getting the mistake. As an idea, start with this in register.php...
<?php
$hostname = "localhost";
$username = "serviceaccount";
$password = "password";
$dbname = "nameofdb";
$conn = new mysqli($hostname,$username,$password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Got to http://[yourdirectory]/register.php DIRECTLY and see what you get. Then start adding the rest step by step and let us know when you get the mistake.
Other think to check is the database NULL variables configuration. All the columns allow null values? Are you filling all form fields or are you leaving any field empty?
Replace your register.php code with following.
<?php
$hostname = "localhost";
$username = "serviceaccount";
$password = "password";
$dbname = "nameofdb";
$conn = new mysqli($hostname,$username,$password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
if it prints that connection failed; then you have to check your code for connecting to database.
Use isset($_POST["FN"]) .. etc for all post variables and try to use variables $FName , $LName etc. in your insert query instead of direct $_POST variables.
e.g.
$FName = '';
if(isset($_POST["FN"]) && $_POST["FN"] !=''){
$FName = $_POST["FN"];
}
Also check whether connection is opening or failing.
before insert any new field into your db use
mysql_real_escape_string
check for empty params before insert these to db
use the following to turn all error reporting on for MySQLi
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
You should use your variables that you assigned for your post fields instead of the $_POST-objects and make sure you sanitize all user inputs.
You could try replacing your $sql-string with the following:
$sql = "INSERT INTO Customers(FName,LName,StreetAddress,City,State,Zip,Email,Password) VALUES('$FName','$LName','$SA','$City','$State','$Zip','$Email','$Password')";
I´ve a problem a login, the page doesn´t show anything. This is the code:
PHP:
<?php
require 'connect_db.php';
/* start the session */
session_start();
conectar();
$email = $_POST['email'];
$password = $_POST['password'];
$sql = "SELECT * FROM teachers WHERE email='$email' and password='$password'";
$result = mysql_query($sql);
// counting table row
$count = mysql_num_rows($result);
if($count == 1)
{
$_SESSION['loggedin'] = true;
$_SESSION['email'] = $email;
$_SESSION['start'] = time();
$_SESSION['expire'] = $_SESSION['start'] + (10 * 60) ;
echo "<body><p>Welcome! </p></body>";
}
else
{
echo "Mail or password not correct.";
echo "<a href='teacher.html'>Try again</a>";
}
//$conexion->close();
?>
The HTML calling this code is:
<form action= "php/login_profesores.php" method="POST" onsubmit="return validacion()">
<label>Mail</label>
<input type="text" class="" id="inputMail"></input></br></br>
<label>DNI</label>
<input type="password" id="inputDNI"></input></br>
<input name="Enviar" type="submit" class="submit" value="Send" /></input></br>
</form>
validación() is the javascript code what works, but the problem is that php doesn´t show any page when the user logins in the system. The DB is well-configured and teacher´s table exists.
connect_db
<?php
function conectar()
{
define('DB_SERVER','http://**/');
define('DB_NAME','**');
define('DB_USER','**');
define('DB_PASS','**');
$conexion=new mysqli();
$conexion->connect('DB_SERVER','DB_USER','DB_PASS', 'DB_NAME');
$error=$conexion->connect_error; //Tambien vale connect_error
echo $error;
}
?>
You must have name attribute in your input fields if you want to pass the value using POST, GET or any other method.
<input type="text" class="" name="email" id="inputMail"></input></br></br>
<label>DNI</label>
<input type="password" name="password" id="inputDNI"></input></br>
In the form you are specifing input types but you are not specifying names for that.
You are using MySQL_ procedural in your PHP page but you're using MySQLi_ Object Orientated in your connection page.
Update everything to MySQLi (object orientated). MySQL_ is now deprecated and no longer supported and should not be used.
You should also check with your SQL that it allows access from the IP address your page is trying to access it from. If they are on the same server then you should replace your SQL database connection address with localhost .
Thanks, it works! I had to write the name of server without http:// and I had another problem mixing mysql and mysqli because it is not correct.