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
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.
I have created a simple login and registration project.
The user is then presented with their 'Profile Page'. I want them to be able to click an 'edit' button and type information into fields that were not present during registration. I can get the script to add a 'bio' to the database but it creates a new record, How can I add this bio info to a particular members record?
<?php
ob_start();
session_start();
if(!isset($_SESSION['Email'])){
header("Location: login.php");
}
?>
<body>
<div id="wrapper">
<?php
$con = mysql_connect("HIDDEN");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("HIDDEN", $con);
$sql="INSERT INTO members (Bio)
VALUES
('$_POST[Bio]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
?>
<form action="edit.php" method="post">
Bio: <input type="text" name="Bio">
<input type="submit">
</form>
</div>
</body>
</html>
If the bio column is in the same table, then you need to perform an UPDATE statement, not another INSERT statement. You also need to know the user’s ID.
UPDATE `members` SET `bio` = ?
Also, don’t use $_POST variables directly in an SQL statement. You’re leaving your site vulnerable to SQL injection vulnerabilities then. Use something like PDO to prepare statements and then execute them with bound parameters. An example, where $db in an instance of PDO:
$sql = "UPDATE `members` SET `bio` = :bio WHERE `id` = :id LIMIT 1";
$statement = $db->prepare($sql);
$statement->bindParam(':bio', $bio);
$statement->bindParam(':id', $user_id);
$statement->execute();
You’ll need to assign the $bio and $user_id variables.
<?php
ob_start();
session_start();
if(!isset($_SESSION['Email'])){
header("Location: login.php");
}
?>
<body>
<div id="wrapper">
<?php
if(isset($_REQUEST['submit'])) {
$con = mysql_connect("HIDDEN");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("HIDDEN", $con);
$sql="INSERT INTO members(Bio) VALUES ('".$_POST['Bio']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
}
?>
<form action="edit.php" method="post">
Bio: <input type="text" name="Bio">
<input type="submit" name="submit">
</form>
</div>
</body>
</html>
I made a form to insert and modify categories in my project.
when i hit "submit" i get the record submitted into the database but it appears empty !
and if i go to the databse field and write the text myself it will appear good in MySQL and and "????" in the browser !
here is the code i wrote:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<?php
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('$_POST[name]','$_POST[parent_id]','$_POST[description]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
<form action="ins.php" method="post">
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit" />
</form>
</body>
</html>
You have to quote (using ") around your index name in your SQL request because $_POST is an array:
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".$_POST["name"]."','".$_POST["parent_id"]."','".$_POST["description"]."')";
But generally speaking please dont trust directly what's user are posting to your script to avoid SQL Injections. You can use mysqli::query which is way better and safer :
Mysqli
First sanitize your user input.
If you after that want to use the values from the array without all the concatenation everyone else mentions use {} around array accessors.
$sql="INSERT INTO categories (name, parent_id, description)
VALUES
('{$_POST['name']}','{$_POST['parent_id']}','{$_POST['description']}')";
To clean for example $_POST do something like this is a good start. This is a bit of my older code. As others have written use mysqli instead
function clean_array($t_array)
{
foreach($t_array as $key=>$value)
$array[$key] = mysql_real_escape_string( trim($value) );
return $t_array;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<?php
if ($_POST['action']=="doformpost") {
//only do DB insert if form is actually posted
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
}
?>
<form action="ins.php" method="post">
<input type="hidden" name="action" id="action" value="doformpost" />
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit" />
</form>
</body>
</html>
Try using double quotes in your statement like this:
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
("'.$_POST['name'].'","'.$_POST['parent_id'].'","'.$_POST['description'].'")";
lots of issues here.
$_POST[name] should be $_POST['name']
your query will run even if the form is not submitted.
you are using deprecated mysql_* functions. Use PDO or mysqli
Your code is vulnerable to sql injection
With all that out, here's what you need to do.
Just to verify that the form is submitted, use
if( !empty($_POST['name']) &&
!empty($_POST['parent_id']) &&
!empty($_POST['description']) )
(use isset if empty value is allowed.)
Then run the query.
In PDO, the code will look like this ->
<?php
// configuration
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "mydb";
$dbuser = "user";
$dbpass = "pass";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "INSERT INTO categories (name, parent_id,description)
VALUES
(?,?,?)";
$q = $conn->prepare($sql);
$q->execute(array($_POST[name],$_POST[parent_id],$_POST[description]));
?>
This is just a start. you can use try and catch block to catch exceptions.
Before running query, check if form is submitted by !empty() or isset() as described above.
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
("'.$_POST['name'].'","'.$_POST['parent_id'].'","'.$_POST['description'].'")";
Please provide quotes while inserting values in database
I found that if you forget the simply html attribute in the <form> for METHOD="POST"... you will get blank data in your database despite all else working fine.
ie.. <form action="file.php" method=POST>
use this statement for your code
if( isset($_POST['name']) && isset($_POST['parent_id']) && isset($_POST['description']) )
//your insert query
Don't forgot about safety!
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".mysql_real_escape_string($_POST['name'])."','".intval($_POST['parent_id'])."','".mysql_real_escape_string($_POST['description'])."')";
And i think a problem with encodings.
launch query before you inserting a data:
$sql = 'set names `utf-8`'; (for example)
Use Below insert query to insert data , i m sure it will definitely help you.
$sql="INSERT INTO categories (name,parent_id,description)
VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
Try this
<?php
if(isset($_POST['submit'])) {
$con = mysql_connect("localhost","user","pass");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description) VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
} else {
echo "1 record added";
}
mysql_close($con);
}
?>
<html>
<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit"name="submit" value="Submit" />
</form>
</body>
</html>
Me too faced the same problem.
Proceed your insert query like this, this helped me.
$email_id = $_POST['email_id'];
$device_id = $_POST['device_id'];
***For My Sqli***
if(!empty($email_id ))
{
$result_insert = mysqli_query($db_conn,"INSERT INTO tableName (user_email, user_device_id,last_updated_by) VALUES('".$email_id."', '".$device_id."', '".$email_id."') ");
if(mysqli_affected_rows($db_conn)>0)
{
$response["success"] = 1;
$response["message"] = "Successfully Inserted";
}
else
{
$response["success"] = 0;
$response["message"] = "Problem in Inserting";
}
}
else
{
$response["success"] = 4;
$response["message"] = "Email id cannot be Blank";
}
}
///////////////////////////////////////////////////////////////////////////////
**For My Sql**
if(!empty($email_id ))
{
$result_insert = mysql_query("INSERT INTO tableName (user_email, user_device_id,last_updated_by) VALUES('".$email_id."', '".$device_id."', '".$email_id."') ");
if(mysql_affected_rows()>0)
{
$response["success"] = 1;
$response["message"] = "Successfully Inserted";
}
else
{
$response["success"] = 0;
$response["message"] = "Problem in Inserting";
}
}
else
{
$response["success"] = 4;
$response["message"] = "Email id cannot be Blank";
}
}
NOTE : here i have checked only for email.
I need to redirect submissions so that users aren't taken to a blank screen.
Here's the code for my form::
<form action="giveaway_execute.php" method="post">
First Name:
<input type="text" name="firstname" /><br />
Last Name:
<input type="text" name="lastname" /><br />
etc...
...
...
<p><input type="submit" value="Submit"/>
</p>
</form>
and here's the php for 'giveaway_execute.php' which interacts with the mySQL db (everything submits; removed password and db name for security)::
<?php
define ( 'DB_NAME','xxxx');
define ( 'DB_USER','xxxx');
define ( 'DB_PASSWORD','xxxx');
define ( 'DB_HOST','localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: ' .mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value1 = $_POST['firstname'];
$value2 = $_POST['lastname'];
$value3 = $_POST['phone'];
$value4 = $_POST['street'];
$value5 = $_POST['city'];
$value6 = $_POST['state'];
$value7 = $_POST['zip'];
$value8 = $_POST['email'];
$value9 = $_POST['weddingdate'];
$sql = "INSERT INTO entrants (firstname, lastname, phone, street, city, state, zip, email, weddingdate) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6', '$value7', '$value8', '$value9')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
I've tried redirects on the PHP file but nothing is working. Any suggestions would be greatly appreciated.
Thank you.
You can just include another page after you're done with your database operations, or as suggested you can use a header call but be sure to use an absolute url.
Also worth noting your code is highly vulnerable to SQL injection, and it doesn't do any validation.
It's a good idea to use isset on your fields to avoid getting notices and SQL errors if fields aren't set.
Finally, it's recommended to use a library such as PDO or mysqli over the older mysql_* extension.
try
header('location:page2.php');
at the end of the file.
Replace page2.php with the actual page you want to send them to
// process.php
$db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
if(isset($_POST['value'])){
error_log(print_r($_POST,1),0);
$db->query('INSERT INTO test (id, value) VALUES (NULL, "'.$_POST['value'].'")');
header('Location: http://google.com');
exit();
}
else {
echo "$_POST is not set.";
}
// form.php
<form action="process.php" method="post">
<input type="text" name="value">
<input type="submit" id="submit-btn" value="Submit">
</form>
Try something simpler and build from there. Also read this: http://www.php.net/manual/en/pdo.prepared-statements.php