Executing query through HTML form - php

views/registration.php
<form action="classes/registration.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit">
</form>
classes/registration.php
if(isset($_POST['submit']))
{
// Define form variables
$username = $_POST['username'];
$password= $_POST['password'];
// Insert form data into database
$query = "INSERT INTO users (username, password)
VALUES ('$username', '$password')";
if(mysqli_query($conn, $query))
{
echo "Registration successfull.";
}
}
The problem is, when I click submit, I get a blank page. The query isn't being executed.
I thought the problem might be because my values aren't setup correctly, so I did the following:
VALUES ('$_POST['password']', '$_POST['password']')";
but that gives me an error, presumably because I am using ' inside of '
So now I am back to square one, unsure of why my query isn't being executed

You are getting a blank page because you don't echo something if $_POST submit isn't set.
if(isset($_POST['submit']))
is never true as your $_POST['submit'] is never set. You need to give your submit a name, this (the name) is what get's POSTed / what you can access within $_POST[' /*name of input*/ ']
Change your form to the following, then you should see your
echo "Registration successfull.";
HTML:
<form action="classes/registration.php" method="post">
Username: <input type="text" name="username"><br>
Password: <input type="text" name="password"><br>
<input type="submit" name="submit"> <!-- <<<<<<<<<<< here -->
As a sidenote, you should absolutely consider using a prepared statement. Running a registration form with your insert query is like an invitation for people keen on ruining your server. You might want to try the query like this:
$query = $conn->prepare("INSERT INTO users (username, password) VALUES (?,?)");
$query->bind_param('ss',$username,$password);
$query->execute;
This way, you will be secured against mysql injection.

Your file naming and paths seem to be mismatching(as per the file names you provided).
No matter if you keep:
views/registration.php
views/classes/registration.php
But if you follow:
--/classes
/registration.php
--/views
/registration.php
[Note: '--/' is the path of your root directory]
Then the form action classes/registration.php won't go anywhere.
So change it:
<form action="../classes/registration.php" method="post">
I suggest to follow the naming convention:
filename- for pages with HTML forms, and
filename_action- for action pages
Also notice the possible error cases mentioned by user baao in the other answer.

Related

Repurposed PHP/MySQL CRUD code that used to work no longer works

I'm an occasional PHP/MySQL hobbyist, meaning every couple of years I get an idea for a simple CRUD project and try to execute it. This last happened in Oct 2018. Yesterday I started another CRUD project, hoping to repurpose some old code. But my INSERT commands are not working. The code is literally taken from an old live site I had that worked perfectly.
I've spent an entire day googling and there's a lot of old stuff out there. I did the usual, turning on PHP errors and echoing out my variables (which turn up empty). I know I'm connecting to my database because I echoed out a success message. Not really looking for anyone to solve my problem for me, but rather to tell me, yeah things have change and you need to check out X source.
Here's a stripped down version of my code. Has PHP/MySQL CRUD syntax changed since 2018?
// Connect to database
require_once "mysqli-connect.php";
$mysqli = dbConnect('dbname');
// Define variables and initialize with empty values
$fname = $lname = "";
// Process the form
if(isset($_POST['submit'])) {
// Set first name
$fname = trim($_POST['fname']);
// Set last name
$lname = trim($_POST['lname']);
// Prepare an insert statement
$query = "INSERT INTO test_table (fname, lname) VALUES (?, ?)";
if ($stmt = $mysqli->prepare($query)) {
// Bind variables to the prepared statement as parameters
$stmt->bind_param("ss", $param_fname, $param_lname);
// Set parameters
$param_fname = $fname;
$param_lname = $lname;
// Attempt to execute the prepared statement
if($stmt->execute()){
// Get last inserted id
$last_id = mysqli_insert_id($mysqli);
// Redirect to photo upload page
?>
<script type="text/javascript">
window.location = 'upload_image.php'; // This does NOT redirect like it should
</script>
<?php
exit;
} // End execute
} // End prepare
// Close statement
$stmt->close();
} // End process form
// Close connection
$mysqli->close();
?>
<form class="needs-validation" novalidate action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<label for="fname">*First name</label>
<input type="text" class="form-control" name="fname" value="<?php echo $fname; ?>" maxlength="20" autofocus required>
<div class="invalid-feedback">
Valid first name is required.
</div>
<label for="lname">*Last name</label>
<input type="text" class="form-control" name="lname" value="<?php echo $lname; ?>" maxlength="20" required>
<div class="invalid-feedback">
Valid last name is required.
</div>
<input type="submit" class="btn btn-submit btn-block" value="Continue">
</form>
I literally pasted "$_POST['submit']" in a google search and the first result said
isset( $_POST['submit'] ) : This line checks if the form is submitted using the isset() function, but works only if the form input type submit has a name attribute (name="submit")
All it took to fix this was adding name="submit" to my input type. I didn't have that in the original file from 2018. Weird.
EDIT: This worked in my test table, but not my real table. Turns out MySQL doesn't like table names with underscores. While they are perfectly valid characters, apparently there's no guarantee they'll always work. Once I removed the underscores, everything worked fine. Took a long time just adding, removing and changing things one at a time.

Using a Submit Button to insert an entry into a MySQL database via PHP?

I'm pretty new to PHP, so I'm not quite sure on what to do with this.
Basically I'm trying to insert an entry into my MySQL database, through a "submit" button in HTML. I can't seem to get this to work, is it possible?
<?php
include('db_connect.php');
$SQL = "INSERT INTO chosenitems (ID, Name, Price) VALUES ('', '4-6 Days', '£75.00')";
$result = mysql_query($SQL);
?>
The INSERT works perfectly fine on its own, but I want it to be executed when the "submit" button is pressed.
Any help would be greatly appreciated.
Thanks
Tobo.
Just set the action of the form to the URL of the script that performs the insert.
Note that since you are modifying a database, the request is probably non-idempotent and you should use the POST method.
<form action="/path/to/your/script.php" method="post">
<input type="submit">
</form>
<form method="post">
<input type="submit" name="submit" value="submt"/>
</form>
PHP
<?php
if(isset($_POST['submit']))
{
$SQL = "INSERT INTO chosenitems (ID, Name, Price) VALUES ('', '4-6 Days', '£75.00')";
$result = mysql_query($SQL);
}
?>
You can check button value is posted and can execute line of code in it.
<?php
include('db_connect.php');
if(isset($_REQUEST['SUBMIT_BUTTON_NAME']))
{
$SQL = "INSERT INTO chosenitems (ID, Name, Price) VALUES ('', '4-6 Days', '£75.00')";
$result = mysql_query($SQL);
}
?>
Hope this will be helpful to you
I had for the submit details:
<form id = "submitForm" action="config/profile_save.php" method="post">
<button type="submit" class="button" name="submit" value="submit">Save Profile</button></form>
Inside each input field on the page, I placed form = "submitForm"
I then changed the name too.(This is the super global variable later)
<input type="text" autofocus="true" class="custom_link_url_text" id="custom_link_url_text"
name="custom_link_email" placeholder="Enter your public email address" spellcheck="false"
style="width: 245px;" maxlength="75" form = "submitForm">
I was then able to capture the data on the next page using the name as POST variable.
if(isset($_POST['submit'])) {
$custom_link_email = $_POST['custom_link_email'];
}
Once I did that it was just a case of inserting data into the database.

PHP form post to MySQL error

I'm creating a php-post form, containing: Who, What, Where, Contact and date_created.
I've made a database with these rows.
Here's my HTML Form code:
<form id="contactform" action="post.php">
<p class="contact"><label for="who">Who</label></p>
<input id="who" name="who" placeholder="Who are you? (First & Second name)" required="" tabindex="1" type="text">
<p class="contact"><label for="email">What</label></p>
<input id="what" name="what" placeholder="What do you want?" required="" type="text">
<p class="contact"><label for="username">Where</label></p>
<input id="where" name="where" placeholder="Country, City, Street..." required="" tabindex="2" type="text">
<p class="contact"><label for="password">Contact</label></p>
<input type="text" id="contact" name="contact" placeholder="Phone number or email"required="">
<br><br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Submit" type="submit">
And here's the php post.php code:
<?php
// Grab our POSTed form values
// Note that whatever is enclosed by $_POST[""] matches the form input elements
$who = $_POST["who"];
$what = $_POST["what"];
$where = $_POST["where"];
$contact = $_POST["contact"];
// Connect to our DB with mysql_connect(<server>, <username>, <password>)
$sql_connection = mysql_connect("server_name", "admin", "password");
mysql_select_db("database_name", $sql_connection);
$sql = "INSERT INTO content (
who,
what,
where,
contact,
date_created
)
VALUES (
'$who',
'$what',
'$where',
'$contact',
NOW()
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
?>
When I try to post something, nothing is happening. The screen is just white, the database is empty and the url is like this:
http://my-website.com/post.php?who=Firstname+Secondname&what=Some+sentences+here-and&where=America&contact=some#website.com&submit=Submit%21
Just as HamZa DzCyberDeV said, you didn't specify which method you're using in <form> tag.
For situations when you're POSTing something in your database, just as you are now - use method="post" and for forms when you're searching for something, use method="get".
In case of using post method, your URL will change to only my-website.com/post.php and in case of using get method, your URL will change to something like my-website.com/post.php?... (where your things which you're getting are going) - just how you got URL after submitting.
The screen is just white because post.php (where you're going after clicking on submit button) doesn't contain anything to send to output, which you can easily do with echo.
For instance, you can make a new html page which will be written down with echo:
echo '
<html
<body>
This is my website!
</body>
</html>
';
Also, what you could do is to use include() php script which has already formed HTML, or you can check out here for some other redirect methods:
http://php.about.com/od/learnphp/ht/phpredirection.htm
Just remember that PHP is language which server is processing and only HTML tags (with CSS and JS) are sent to other browser to be read.
For more about POST and GET method you can read here:
http://php.net/manual/en/reserved.variables.post.php
http://php.net/manual/en/reserved.variables.get.php
why don't you try this to get an error or a clue to what is going wrong, enclose your code in try and catch blocks:
try {
// your code
} catch ( Exception $e ) {
echo $e->getMessage();
}

php mysql; writing data to database

having a bit of trouble adding some data to a database. I have the file new_entry.php which is a form, which posts the data added to insert_new.php.
Every time the fields are filled in and submitted the data does not go to the database with the error message "Could not add the data to table" appearing..any ideas?
NEW_ENTRY.PHP
<body>
<form method="post" action="insert_new.php"><!-- form sent to insert_new.php-->
Section: <input type="text" name="section"/><br />
Food: <input type="text" name="food"/><br />
Description: <input type="text" name="description"/><br />
Price: <input type="text" name="price"/><br />
<br />
<input type="submit" value="submit"/>
</form>
</body>
INSERT_NEW.PHP
<?php
include 'library/connect.php';//connect to databse
$section = $_REQUEST["section"]; // get data from the HTML form on new student form
$food = $_REQUEST["food"];
$description = $_REQUEST["description"];
$price = $_REQUEST["price"];
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', $price)")/* insert the data to the food_menu table*/
or die ("Could not add the data to table");//error message
header('Location:index.php');//auto redirect to view page
include 'library/closedb.php';
?>
It seems that you have a mistake at the end of your MySQL query near price.
Please replace the code below with existing line:
mysql_query ("INSERT INTO food_menu (section, food, description, price) VALUES ('$section', '$food', '$description', '$price')")
Tell me the result please.
First: Don't do this. You really need to research SQL Injection or you will be very sorry.
Secondly, your price has no numeric validation (assuming it's going into a numeric column)... this is also bad... what if someone put in a dollar sign or something?
Next, please post your table definition and connection code (not the connection values).
You can also get more feedback if you do something like:
or die (mysql_error());//error message

Forms, Mysql and values

So say I have a form like so:
<form action="submit2.php">
<input name="name" type="text" />
<input name="age" type="text" />
<input type="submit" />
</form>
I using this code to insert the values of the form into a database table called "example" after the user clicks the submit button.
mysql_query("INSERT INTO example (name, age) VALUES('$name', '$age' ) ") or die(mysql_error());
However, all I get is a blank entry in the table. Am I wrong in assuming that an input's value becomes a variable if if is giving a name(e.g. name="age") in the html code?
Access the variables through the $_POST global variable.
if(isset($_POST['name']) && isset($_POST['age'])){
$name = mysql_real_escape_string($_POST['name']);
$age = mysql_real_escape_string($_POST['age']);
mysql_query("INSERT INTO example (name, age) VALUES('$name', '$age' ) ") or die(mysql_error());
}
An input named "name" will create a variable $name in submit2.php only if register_globals is enabled, which is a security issue. You should never have register_globals turned on (it will be removed in PHP6, by the way).
I'm not sure what the default method attribute is, but it should create a variable named either $_GET['name'] or $_POST['name']. If it doesn't create any of them, add a method attribute to your form :
<form action="submit2.php" method="post">
However, this does not assure you that those variables exist (what if someone access submit2.php without using your form?). You have to use either isset or !empty (I prefer the latter, because it also checks if it's not empty).
Last thing : don't forget to escape your variables. Never trust user input. In this case, since you're inserting a variable in a query, you should use mysql_real_escape_string function.
you need to change the data from the form to usable values
<form action="submit2.php" method="post">
<input name="name" type="text" />
<input name="age" type="text" />
<input type="submit" />
</form>
and change database query portion to:
$name=mysql_real_escape_string($_POST['name']);
$age=mysql_real_escape_string($_POST['age']);
mysql_query("INSERT INTO example (name, age) VALUES('$name', '$age' ) ") or die(mysql_error());
The mysql_real_escape_string helps security for not having script injected into your database and having someone change or remove entries.

Categories