The php code below seems to run but not save into the database. Its simple yet critical enough to be a bother.
<html>
<body>
<?php
if(isset($_POST['submit'])){
$connect=mysql_connect("localhost","root","root","form2");
if(mysql_connect_error($connect))
{
echo 'Failed to cnnect';
}
$fname=$_POST['fname'];
if(mysql_query("INSERT INTO user(fname) VALUES('$fname')"))
{
echo ' Success';
}else
{
echo ' No good!';
}
}
?>
<form method ="POST">
First name <input type = "text" name = "fname"></input>
<input type = "submit" name = "submit" value ="enter"></input>
</form>
</body>
</html>
When should one use mysqli for security reasons (since mysql is deprecated) and how should it be used?
Related
I'm trying to create a form on a webpage, which takes an id number entered by the user, and deletes the corresponding record in a database. I'm unable to get it working.
This is the delete code which isn't working:
<?php
if (isset($_POST['deleteSubmit'])) {
$details = $conn->real_escape_string($_POST['deleteNum']);
$deleteSQL = "DELETE FROM userName WHERE id = '$details'";
$result = $conn->query($deleteSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>DELETE NAME (DELETE)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="num">Enter User Reference to be Deleted:</label><br>
<input num="deleteNum"type="number"><br>
<input num="deleteSubmit" type="submit" value="Delete">
</form>
For reference, this is the post code which is working (it's being used to add names to the database):
<?php
if (isset($_POST['nameSubmit'])) {
$details = $conn->real_escape_string($_POST['newName']);
$insertSQL = "INSERT INTO userName (name) VALUES ('$details')";
$result = $conn->query($insertSQL);
if (!$result) {
echo 'Error!';
exit($conn->error);
} else {
header('Location: index.php');
exit;
}
}
?>
<h4>ENTER NAME (POST)</h4>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<label for="fname">Enter Name:</label><br>
<input name="newName"type="text"><br>
<input name="nameSubmit" type="submit" value="Submit">
</form>
The database connection file is being called in both programs and is working for the post.php element, which is why I haven't included it or reference to it.
The database has one table called userName which contains two columns id (which is auto incremented) and name.
I've tried changing some of the syntax on the delete.php file with no success. I've ran the $deleteSQL code directly in my database and it works.
I see no error messages when enter an id and click the delete button.
For anyone who reads this in future, the query was solved by #kenlee;
(1) Change num="deleteSubmit" to name="deleteSubmit"
(2) change num="deleteNum" type="number" to name="deleteNum" type="number"
(3) Please use paratemerized prepared statement in your queries
Im having some Trouble getting a simple PHP Login form to pass and check Login Data against a Database. For some reason the Data will not pass across from the Html Form to the PHP handler. Both are separate files but the code is as follows:
<html>
<head>
<title>Login</title>
</head>
<body>
<h1> Welcome please Login: </h1>
<form action="LoginCreate.php" method="post">
Username: <input type=“name” name=“username” id="username"><br/>
Password: <input type="password” name=“password” id="password"><br/>
<input type="submit" value="Login"> <input type="submit" value="Create Account">
</form>
Then for the PHP fike: (please note I have not yet added code for checking against the database.)
<?
$db=sqlite_open("database.db");
$username = sqlite_escape_string($_POST["username"]);
$password = sqlite_escape_string($_POST["password"]);
if(isset($_POST['Create Account'])){
sqlite_query($db,"INSERT INTO username (name) VALUES ('$username')");
sqlite_query($db,"INSERT INTO password (password) VALUES ('$password')");
echo "<p> Account Created. <p>";
}
else if(isset($_POST['Login'])){
echo "<p> Login Successful. <p>";
}
sqlite_close($db);
?>
What should be causing the Data not to be Posting correctly, have I got the syntax wrong somewhere? I'm using MicroApache and getting no Errors popup in Chrome.
You need to add the name="action" attribute to your submit buttons and check
if(isset($_POST['action'])) {
if ($_POST['action'] == 'Create Account') {
} elseif ($_POST['action'] == 'Login') {
}
}
I'm finding that echo isn't working in my scripts.
The stripped down script below is what I've been using to debug this, but the result has been the same.
Perhaps you can see something simple I've overlooked. Any help appreciated.
Additional details:
Location: http://www.example.com/include/sandbox.php
The web-server can execute php-scripts: phpinfo(); presents PHP Version 5.3.24.
No header lines to worry about.
(I'm wanting to check that a field is not empty before submitting to a database, and provide prompts or an echo on submit.)
<?php
if($_SERVER['REQUEST_METHOD'] == 'post'){
if(!isset($fieldA)){
echo "Error: Submission field empty.";
}
else{
echo "Success! Submitted field wasn't empty.";
}
}
?>
<h1> Example Title </h1>
<form method="post" action="sandbox.php" >
<input type="text" name="fieldA" value="" />
<br />
<input type="submit" name="submit" />
</form>
if($_SERVER['REQUEST_METHOD'] == 'POST'){
..........
}
Try this one. or change the if condition like,
if(!isset($_POST['fieldA'])){
if(empty($_POST['fieldA'])) {
echo "Error: Submission field empty.";
}
}
else{
echo "Success! Submitted field wasn't empty.";
}
I am trying to make a "form" of the type "text" which will check whether an email is valid or not. I first tried to check if the text field was empty by making an if statement, but it didnt work, and it instead ran the "else" option of the statement. How do I fix it so it actually checks if the text field is empty? Here is the code.
INDEX.php:
<?php
include 'connection.php';
echo "<p> Example Text </p>";
?>
<h1> Submit email address </h1>
<form action = "create.php" method = "post">
<input type ="text" name = "email" value = "" />
<br />
<input type = "submit" name = "submit" />
</form>
Create.php :
<?php
include 'connection.php';
$email = $_POST['email'];
if(!isset($email)){
echo "please fill out the form";
header ('Location: index.php');
}
else{
echo "Successive login";
}
?>
When doing:
$email = $_POST['email'];
You are in fact setting $email so the !isset() will return false (meaning that it is NOT not isset)
instead you need to check if it is not empty
if(!empty($email)){
}
else{
}
================
EXTRA
Here is an example of how how you can check valid email addresses:
if (!filter_var($email, FILTER_VALIDATE_EMAIL) === false) {
echo("$email is a valid email address");
} else {
echo("$email is not a valid email address");
}
Also check out my PHP function that checks to see if the email is valid and can receive emails by connecting to the mail server and verifying it:
https://github.com/hbattat/verifyEmail
I did that. It did work when I removed the header code as well, but I
want the echo to be displayed in index.php rather than in a new page
(create.php). How do i do that? – tomSurge 3 hours ago
When you submit to the create.php basically you load the create.php page with some post parameters. So anything you display there will not be displayed in index.php because you are not in the same page.
Instead you could post to the same page index.php and do the create process there:
<?php
include 'connection.php';
if($_SERVER['REQUEST_METHOD'] == 'post'){ //check if the page was requested via post method (that means the form was submitted)
if(!isset($email)){
echo "please fill out the form";
}
else{
echo "Successive login";
}
}
echo "<p> Example Text </p>";
?>
<h1> Submit email address </h1>
<form action = "index.php" method = "post">
<input type ="text" name = "email" value = "" />
<br />
<input type = "submit" name = "submit" />
</form>
OR
You could use AJAX and not load the page when posting the info to create.php and just display the response message:
<?php
include 'connection.php';
echo "<p> Example Text </p>";
?>
<!-- include jQuery in the header of your html -->
<script src="LINK TO jQUERY .js file"></script>
<script type="text/javascript">
$(document).ready(function(){
//trigger this when the form is submitted
$('form').on('submit', function(e){
//prevent default submission and reload of the page
e.preventDefault();
//post the date to the create.php file using ajax
//get the form data
var formData = $(this).serialize();
$.post('create.php', fomrData, function(response){
var result = parseJSON(response);
$('#msg').text(result.msg);
}
});
});
});
</script>
<h1> Submit email address </h1>
<form action = "create.php" method = "post">
<input type ="text" name = "email" value = "" />
<br />
<input type = "submit" name = "submit" />
</form>
create.php
<?php
include 'connection.php';
$email = $_POST['email'];
$result = array();
if(!isset($email)){
$result['status'] = 'fail';
$result['msg'] = "please fill out the form";
}
else{
$result['status'] = 'success';
$result['msg'] = "Successive login";
}
//echo the json
echo json_encode($result);
?>
isset() only checks if the variable is set. You need to use empty($email) instead.
Replace isset with empty and it should work as you want.
If I understand your question, you have to change the statement to if(!empty($email)) Also, if you want to check if the email is in the correct format, please use a regex to do so. isset() only checks for null
You can also test for submission of something (anything) in the posted email field with:
'' == $_POST['email']
As others have suggested, empty($_POST['email']) works too, just showing another option.
Displaying the Error Message
If you want the error message to appear on index.php then you need to pass the message or some sort of flag from the create.php page (where the error is discovered) to the index.php page (where the error message is displayed).
To demonstrate a bare-bones example (one of many ways to accomplish this), first I added a PHP variable to the form. Notice the line containing echo $_GET['error']; immediately after the email input element:
index.php (form):
<form action="create.php" method="post">
<input type="text" name="email" value="" />
<?php if (isset($_GET['error'])) { echo $_GET['error']; } ?>
<br />
<input type="submit" name="submit" />
</form>
...and, instead of echo'ing the message in the create.php script, send the message along to the index.php script in the URL query:
create.php (email check):
if ( '' == $_POST['email'] ) {
header('Location: index.php?error=please+fill+out+the+form');
}
Additionally, I recommend you use this (PHP server-side validation) as a backup to a Javascript client-side validation solution. Nicer for your website visitors and uses fewer server resources.
Another way is to just add a required="" to your input Here is an example https://jsfiddle.net/57s38s2e/
I have an if else statement. The code logic is that the first if statement would get all the necessary informations needed and the second if statement would print all the informations that are generated at the first if statement. The problem is that when it triggers the second if statement, it disregards all the data that are stored in the first if statement.
Can anybody help me how to solve this problem? Thank You
This is just a sample code but the process and logic of code is somehow the same.
<head>
<title>Sample PHP Web</title>
</head>
<body>
<form method = "post">
<input type = "submit" value = "submit" name = "submit">
<?php
if(isset($_POST['submit']))
{
$nn[0] = "man";
$nn[1]= "men";
echo'<input type = "submit" value = "print" name = "print">';
}
?>
</form>
<?php
if(isset($_POST['print']))
{
echo $nn[0];
echo $nn[1];
}
?>
</body>
After the initial form submission is handled the values you set into PHP variables are lost. They do not persist across page requests. If you want them to persist you need to use sessions.
<?php
session_start();
?>
<head>
<title>Sample PHP Web</title>
</head>
<body>
<form method = "post">
<input type = "submit" value = "submit" name = "submit">
<?php
if(isset($_POST['submit']))
{
$_SESSION['nn'][0] = "man";
$_SESSION['nn'][1]= "men";
echo'<input type = "submit" value = "print" name = "print">';
}
?>
</form>
<?php
if(isset($_POST['print']))
{
echo $_SESSION['nn'][0];
echo " "; // seperate words with a space
echo $_SESSION['nn'][1];
}
?>
</body>