I want to go from a HTML form to a SQL database using PHP.
Here is my current code:
PHP:
if(isset($_POST['submitIpG']))
{
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO GmodServers (ipaddress)
VALUES ($_POST['submitIpG'])";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
echo "<br />\n";
}
As you can see it's hard coded with a specific IP. However, I want it to use an IP from the user input in my form.
HTML:
<form method="post">
<input type="value" name="submitIpG" value=""/>
<input type="submit" name="submitIpG" value="ADD"/>
</form>
How do I do this? I've tried things such as:
$sql = "INSERT INTO GmodServers (ipaddress)
VALUES ('$_POST['submitIpB']')";
Without success.
Thanks!
You should set the action php script in form html also your inputs should be like
<form method="post" action="your_php_file.php">
<input type="text" name="submitIpG" placeholder="the ip input"/>
<input type="submit" name="submit" value="ADD"/>
</form>
and your_php_file.php should be like
$sql = "INSERT INTO GmodServers (ipaddress)
VALUES ('$_POST['submitIpG']')";
But the most important part is DO NOT USE sql queries like that. Please consider using prepared statement.
There is a good and simple example at w3school. this is the link you may want. https://www.w3schools.com/php/php_mysql_prepared_statements.asp
Related
I have a piece of code which inserts user's input into a database:
Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("DB status: connection failed: " . $conn->connect_error);
} else {
echo "DB status: connected";
}
?>
<html>
<h1>Add data</h1>
<form method="post">
<p>Name: <input type="text" name="name"></p>
<p>Goals scored in:</p>
<p>14/15 <input type="text" name="14"></p>
<p>15/16 <input type="text" name="15"></p>
<p>16/17 <input type="text" name="16"></p>
<p>17/18 <input type="text" name="17"></p>
<button type="submit" name="save">save</button>
</form>
<?php
$sql = "INSERT INTO `goals` (`Name`, `14/15`, `15/16`, `16/17`, `17/18`) VALUES ('".$_POST["name"]."', '".$_POST["14"]."', '".$_POST["15"]."', '".$_POST["16"]."', '".$_POST["17"]."')";
$result = mysqli_query($conn,$sql);
?>
The problem is that when I load the page for the first time, it already sends 0's to the database. How can I prevent this from happening?
Thanks a lot for helping!
add an action to your form and use that to send the sql query. You should probably also be using form validation requiring some fields like name to be filled out.
<p>Name: <input type="text" name="name" required></p>
Calling a particular PHP function on form submit
Add this piece of code at the beginning to fix the issue:
if (isset($_POST['submit']))
{
}
I have an activity table which i want the users to be able to add data to it from my website. I have a Form and an INSERT INTO Query but when i click submit button the form clears but the database does not have the inputted record. I think the issue is that one of the fields (activity_cat) is a FOREIGN KEY on the table I'm trying to insert to.
<form>
<form action="" method="post">
Activity Category: <input type="text" name="activity_cat" /><br><br>
Activity Name: <input type="text" name="activity_name" /><br><br>
Activity Address: <textarea name="activity_address"> </textarea><br><br>
Activity Description: <textarea name="activity_description"> </textarea><br><br>
<input type="submit" name="submit"/>
</form>
The above form is my html form and the below is my php code to insert into the database
<?php
$conn = mysqli_connect($db_host, $db_username, $db_pass, $db_name);
if (!$conn) {
die(mysqli_error());
}
if(isset($_POST["submit"])){
$sql = "INSERT INTO `activity`(`activity_cat`, `activity_name`, `activity_address`, `activity_description`)
VALUES ('".$_POST["activity_cat"]."','".$_POST["activity_name"]."','".$_POST["activity_address"]."','".$_POST["activity_description"]."')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
}
?>
The "activity_cat" is a Foreign Key in the "activity" table. This is so the activities are categorised into different categories. Im not sure if this is the problem or not. I am entering the exact activity_cat records that are in categories table but still no luck. Ideally i would like a drop down menu which the user can select the category type for the option in the form. Any help with this would be appreciated. I am new to coding, especially PHP and mysql. Any other information needed please ask
Thank You
You need to include a name attribute on your submit button.
Add name='submit'
On your submit button
Apart from the fact that your code is prone to SQL Injection attacks, you are checking if submit is set, when you did not provide a name for your button.
Add a name attribute to your input tag like so:
<input type="submit" name="submit" />
First, you have an un-closed form tag:
<form> <!-- What is this -->
<form action="" method="post">
Second, (and this is what's causing the problem in this case):
You did not specify an action to your form! The action attribute must be set to the path of the php file which holds your script, which inserts stuff into your database.
For example:
something.html:
<form action="inserter.php" method="post">
Activity Category: <input type="text" name="activity_cat" /><br><br>
Activity Name: <input type="text" name="activity_name" /><br><br>
Activity Address: <textarea name="activity_address"> </textarea><br><br>
Activity Description: <textarea name="activity_description"> </textarea><br><br>
<input type="submit" name="submit"/>
</form>
inserter.php:
<?php
$conn = mysqli_connect($db_host, $db_username, $db_pass, $db_name);
if (!$conn) {
die(mysqli_error());
}
if(isset($_POST["submit"])){
//You don't need to concatenate, you can just put the variables directly into a string (which are double quoted) like this: ${variable's_identifier}
$sql = "INSERT INTO `activity`(`activity_cat`, `activity_name`, `activity_address`, `activity_description`)
VALUES ('${_POST["activity_cat"]}','${_POST["activity_name"]}','${_POST["activity_address"]}','${_POST["activity_description"]}')";
if ($conn->query($sql) === TRUE) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Error: " . $sql . "<br>" . $conn->error."');</script>";
}
}
//You SHOULD close the connection when you are done!
mysqli_close($conn);
?>
However, please do use parameterized prepared statements!
$conn = new mysqli($db_host, $db_username, $db_pass, $db_name);
$stmt = $conn->prepare("INSERT INTO `activity`(`activity_cat`, `activity_name`, `activity_address`, `activity_description`) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $_POST["activity_cat"], $_POST["activity_name"], $_POST["activity_address"], $_POST["activity_description"])
$stmt->execute();
$stmt->close();
$conn->close();
Hello guys i need some help.I connected to database from server and can insert some info like $sql = "INSERT INTO Posts (Text_Post) VALUES ('Sample Text')";. Now I want to save on click text from <input type="text" /> to database. Can you tell me what i am doing wrong.
<?php
$servername = "google.com";
$username = "google";
$password = "google";
$dbname = "google";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_POST['Submit'])) {
$sql = "INSERT INTO Posts (Text_Post) VALUES ('".$_POST['text']."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>anonim</title>
</head>
<body>
<form name="form" action="" method="post">
<input type="text" name="text" id="text" value="Salut" /=>
<input type="submit" id="Submit" />
</form>
</body>
</html>
You're missing the name tag on your submit. When data is POST'ed to the server, it uses the name tag.
<input type="submit" id="submit" name="Submit">
Remember to watch your Capitals also - (since you're checking if Submit is SET then you need to POST the submit).
You could just do:
if(isset($_POST['text'])) {
Also, going off the comments: I'd suggest taking a look at this link because you're prone to SQL Injections.
when we are going to post a form using POST or GET. we should always give name to all our fieds so we get get them just using $_POST['name'] or $_GET['name']. In Your case just give a name to your submit tag and check whether data is submitted or not.
replace
<input type="submit" id="Submit" />
with
<input type="submit" id="submit" name="submit">
and check it like
if(isset($_POST['submit'])) {// it will only check where form is posted or not
// your code...
}
I am having trouble inserting data into the database 'justrated'. Once the user has entered their business name it should create a new entry in the table 'businesses'. For some reason I cannot get it so that the data is entered in the table. Any advice is gladly appreciated.
CODE:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<form>
<input type="text" name="BusinessName" method="POST">
<input type="Submit" value="submit" name="submit" method="POST">
</form>
<?php
if (isset($_POST["submit"])){
//create connection
$conn = new mysqli("localhost", "root", "", "justrated");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO businesses (BusinessName)
VALUES ('".$_POST['BusinessName']."' )";
mysql_query($sql);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
?>
</body>
</html>
One of your problems is that $_POST['BusinessName'] is empty because the form was submitted using a GET request, not a POST request. The method=POST attribute goes on the <form> element. Eg:
<form method="POST">
<input type="text" name="BusinessName">
<input type="Submit" value="submit" name="submit">
</form>
Also, you should escape the data properly before you insert it into the database:
$sql = "INSERT INTO businesses (BusinessName)
VALUES ('" . $conn->real_escape_string ($_POST['BusinessName']) . "' )";
Furthermore, in these two lines:
mysql_query($sql);
if ($conn->query($sql) === TRUE) {
you try to execute the same query twice using both the MySQL and MySQLi extension. You should remove the first line.
HTML Code
<form method="post" action="test1.php">
<input type="text" name="BusinessName" >
<input type="Submit" value="submit" name="submit" >
</form>
PHP Code
if (isset($_POST["submit"]))
{
//create connection
$conn = new mysqli("localhost", "root", "", "justrated");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO businesses (`BusinessName`)
VALUES ('".$_POST['BusinessName']."' )";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
Don't mix the mysql & mysqli....
Html:
<form method="POST">
<input type="text" name="BusinessName">
<input type="Submit" value="submit" name="submit" >
</form>
Php:
Use
$conn->query($sql); not mysql_query()
hello please check this one i hope this working for you
$sql = "INSERT INTO businesses (`BusinessName`)
VALUES ('".$_POST['BusinessName']."' )";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Given the following HTML form:
<form id="form1" name="form1" method="post" action="comments.php">
<textarea name="text" id="textarea" cols="45" rows="5"></textarea><br/>
<input type="submit" name="button" id="button" value="Update" />
</form>
...and the following PHP code (comments.php):
<?php
require("includes/config.php");
$fromtextarea = $_POST['text'];
$con = mysql_connect($dbserver, $dbusername, $dbpassword);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($dbname , $con);
$sql = "INSERT INTO textarea (comment) VALUES ('$fromtextarea')";
if (mysql_query($sql)) {
header("Location: home.php");
}
else
echo "no no no";
mysql_close($con);
?>
How can I get the data and display all user comments on a page?
Take a look at SELECT sql statement. Your query should look like something like this:
SELECT comment FROM textarea;
Then see how to manipulate the result with mysql_fetch_* functions in PHP (http://www.php.net/manual/fr/function.mysql-fetch-assoc.php).
By the way, mysql_* functions are deprecated (and will be deleted soon). I advise you using mysqli_* functions (http://www.php.net/manual/fr/book.mysqli.php) or (better) PDO (http://php.net/manual/fr/book.pdo.php).
Do like this
$sql = "INSERT INTO textarea (comment) VALUES ('". $_POST["text"] . "')";
Make sure you sanitize it before using it in your query.