Insert into SQL database user input from HTML form - php

I am trying to insert into column "UserId" in my sql database, using php, text that the user inputs in the HTML form.
Below is a basic example to help me figure out what I am doing wrong.
HTML
<html>
<form action="index1.php" method ="post" name="trial">
<input type="text" name="testName" id="testId">
<br>
<input type="submit" value="Submit">
</form>
</html>
PHP
$servername = "localhost";
$username = "root";
$password = "xx";
$dbname = "wp";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$UserId = $_POST['testName'];
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$testName')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Some notes:
I can connect to database and insert in the correct columns checkbox and radio values from the form
I cannot find a way to insert in the database the user text input from the form (UserProfile is the table and UserId the column).
Would using a javascript variable, like below one, help?
var testVar = document.getElementById("testId").value;
I know I am opening myself to hacking using the above code, I would like to improve it later on but I think I need to first figure out the basics (ie: how to get the user text input added to the database)
Than you in advance for any help!

you are storing the value in $UserId, not in $testName:
Change your SQL Query to
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$UserId')";
I think this will help.
BTW: Think about SQL-Injection! Look here: How can I prevent SQL injection in PHP?

Look here
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$testName')";
Change $testName to $UserId in sql statement because it's the name of your new variable in php:
$UserId = $_POST['testName'];
$sql = "INSERT INTO UserProfile (UserId) VALUES ('$UserId')";
But I advice you to:
1- use PDO for any sql handling in php
2- use mysqli_real_escape_string to protect your code from threats.
make it like:
$UserId = mysqli_real_escape_string($con, $_POST['testName']);

Related

Simple php - mysql select and insert

I am not a programmer (duh), I just need to make a really simple tool for populating sql database. First I have html with form:
<form action="http://localhost:8081/phpSearch.php" method ="post">
Enter code: <input type="text" name="search"><br>
<input type ="submit">
</form>
and then php that should connect to MYSQL, search for data according to input (code,name) in one table and then populate another table with the result. And I'm only mising what to put instead of question marks.
<?php
$search1 = $_POST['search'];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydb";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT code,name FROM users WHERE code LIKE '%$search1%'";
$sql2 = "INSERT INTO newUsers (newCode,newName) VALUES ('$search1', ??????)";
$conn->close();
?>
I'm pretty sure this is easy for you experts, so thanks in advance.
You could actually do this in a single SQL query:
$search1 = "%".$_POST['search']."%";
$sql = "INSERT INTO newUsers (newCode, newName) SELECT code, name FROM users WHERE code LIKE ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $search1);
$stmt->execute();
This will insert all the results of the SELECT query directly into the other table, without needing any intermediate processing in PHP. More about the INSERT...SELECT query format can be found here.
Note I've used prepared statements and parameters - which both executes the query securely and reduces the risk of accidental syntax errors. You can get more examples of this here.
Also, in a real application you shouldn't log in as root from your web application - instead create a SQL account for the application which has only the privileges it actually needs.

How can I pass my user entered information to my database using php?

The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.
<!-- connect to database -->
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
//<!-- post added information to database -->
if ($_POST['name']) {
if ($_POST['number']) {
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
} ?>
From looking at my code I believe the issue is with this line.
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";
There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";
These hard coded entries are put into the database but i can't get the user entered data to go in.
Create variables for the $_POST values and add the vars for ease of code understanding:
$name = $_POST['name'];
$number = $_POST['number'];
$sql = "INSERT INTO hello (id, name, number) VALUES ('', $name, $number)";
One reason your code may not be working because you have the single quotes around the $_POST values, then you can also do what Jasbeer Rawal recommended.
UPDATE
Based on the kind comments... I would personally take a different approach to adding the data to your database, instead use prepared statements. I use MySQLi, but you can also use PDO.
Start by creating your connection:
<?php
define("HOST", "localhost");
define("USER", "");
define("PASSWORD", "");
define("DATABASE", "");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then when the user submits the form handle it:
if(isset($_POST['submit']
{
$name = $_POST['name'];
$number = $_POST['number'];
if ($stmt = $mysqli->prepare("INSERT hello (name, number) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $name, $number);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: Could not prepare SQL statement.";
}
}
This will add $name and $number and your ID role has to be a primary role and set to auto_increment. IDs will be automatically generated.
You're about to go down a slippery slope using mysqli. I'd recommend trying to learn to use PDO for making queries. Right now, someone could easily put SQL into the name POST data and actually do damage to your database.
Anyways, your problem at hand, you have a missing bracket and one issue:
VALUES ('', '$_POST['name']', '$_POST['number'')";
It won't work as intended with nested single quotes.
VALUES ('', '$_POST[name]', '$_POST[number]')";
Remove single quotes from $_POST['name'] and $_POST['number'] as below
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', $_POST['name'], $_POST['number'])";
Your insert code be like this
$sql = "INSERT INTO hello (id, name, number)
VALUES ('','{$_POST['name']}', '{$_POST['number']}')";
Then your value will be in database
If field id is primary key and auto increment then your insert statement should be like
Try this:
$sql = "INSERT INTO hello ( name, number)
VALUES ('{$_POST['name']}', '{$_POST['number']}')";

PHP Update MySQL, form input coming through as column name

So I am sorry as I feel I ask stupid questions a lot. I am learning as I go but getting there.
I've created a basic HTML form and with the help of a previous answer I've made the PHP and MySQL query. However when I submit the form the input values from the form come up as column names rather than the information to be updated in the row.
In simple terms when the form is submitted if the input is to change first name from James to Josh the error message is:
"Error updating record: Unknown column 'Josh' in 'field list'"
I though in my SQL query below it would pick up the column name as first_name but this is obviously not happening.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "Users";
//Create variables
$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];
$ID=$_POST['ID'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE Users SET first_name=$first_name, last_name=$last_name WHERE
ID=$ID";
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$conn->close();
?>
I don't know PHP, but I suspect that your problem is that you arent't quoting the value in your update statment. So try something like:
"UPDATE Users SET first_name='$first_name', last_name='$last_name' WHERE ID=$ID"

Php wont input data into database

So im trying to get my data from my form submission to be put into a mysql database but whenever i submit a form it gives me this error: Error: INSERT INTO form_submissions(ID, first, last, phone, class) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])
Now here is my PHP code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form_database";
$value = $_POST['first'];
$value1 = $_POST['last'];
$value2 = $_POST['phone'];
$value3 = $_POST['class'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `form_submissions`(`ID`, `first`, `last`, `phone`,
`class`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])";
if ($conn->query($sql) === TRUE) {
echo "Submitted Successfully";
} else {``
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
assuming that ID is auto-incrementing, and that the others are text,
$sql = "INSERT INTO `form_submissions`(`first`, `last`, `phone`,
`class`) VALUES ('$value','$value1','$value2','$value3')";
Your query should be like:
INSERT INTO `form_submissions`(`first`, `last`, `phone`, `class`)
VALUES ('John','doe', '98564', 'SOMECLASS');
To check: echo the $sql query and debug it in phpmyadmin.
Note: If you enabled AUTO_INCREMENT, you can ignore the data feed of that column. It will do its job automatic.
Security tip - >
To prevent SQLi Injection check out this post.
There are two things wrong.
The first thing is you give 5 fields (ID, First, last, phone, class)
And you only have 4 variables in your post. I think you don’t need to send the ID on an insert if the column is set to auto increment in the database, So don’t send an value for the ID field.
Your variables are not correctly inserted in the query.
The [value-1] douse not mean the $value1 variable will automatically be injected in there.
This can be done in a lot of way’s
I wil give you a simple solution, (but it wil be a bad one for real websites). The simple solution is:
$sql = "INSERT INTO `form_submissions`(`first`, `last`, `phone`,`class`) VALUES (`$value`,`$value1`,`$value2`, `$value3`)";
The reason this is bad is: You are directly entering post data inside your query and are now vounerable to SQL-Injections. You need to escape your post data befoure inserting it in a query. Or better yet don’t use ‘mysqli’ but an PDO.
An good PDO example can be found here
https://www.w3schools.com/php/php_mysql_insert.asp
I hope this helps.
Your SQL is apparently wrong. It should look's like with something like that:
$sql = "INSERT INTO `form_submissions`(`ID`, `first`, `last`, `phone`,
`class`) VALUES ($value1,$value2,$value3,$value4,$value5)";
The field ID should be auto_increment. If it is, you don't need to pass value to it.

Mysqli and PHP not sending data [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I'm building a recruiting website and need to save user data in my database but my form isn't sending anything to the database in phpmyadmin (using WAMP).
I checked the error logs for PHP, MySQL and Apache but don't see any errors. I also added "if/echo" blocks inside the $conn variables to test the connection, which returned true. Code below.
<!-- index.html-->
<form action="process.php" method="post">
<input type="text" name="first_name" placeholder="First Name" /><br/>
<input type="text" name="last_name" placeholder="Last Name" /><br/>
<button type="submit" name="submit"></button>
</form>
//database.php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "xxxx";
$dberror1 = "Could not connect to the database!";
$dberror2 = "Could not find selected table!";
// Connection to the database, Already tried this with echo statement and works
$conn = mysqli_connect($dbhost, $dbuser, $dbpass) or die ($dberror1);
// Selecting the database to connect to
$select_db = mysqli_select_db($conn, 'mainbase') or die ($dberror2);
//process.php
<?php include 'database.php';
if(isset($_POST['submit'])) {
// Creating variables to store form values
$first_name= $_POST['first_name'];
$last_name=$_POST['last_name'];
//Executing the query
mysqli_query($conn, " INSERT INTO 'candidates'('first_name', 'last_name') //Values in 'candidates' table on phpmyadmin
VALUES ('$first_name','$last_name')");/*variables from above*/
}
You're using myqli incorrectly. But on top of that, use PDO to connect to your database instead. It's safer and easy to expand in the future. Here is an example of how to connect to your database with PDO.
<?php
$myUser = "XXXXXX";
$myPass = "XXXXXX";
try{
$dbPDO = new PDO('mysql:host=localhost;dbname=xxxxxxxx', $myUser, $myPass);
$dbPDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connection was successful";
} catch(PDOException $e){
print "Error!: " . $e->getMessage() . "<br />";
die();
}
?>
Simply change the Xs to your server's settings.
When you want to start a query simply you can do it like so:
$query = $dbPDO->prepare("SELECT * FROM Table_Name");
$query->execute();
Of course you'd want to pass variables to your queries so you can do that like this:
$query = $dbPDO->prepare("SELECT * FROM Table_Name WHERE ID = :id");
$query->bindParam(':id', $id);
$query->execute();
That keeps SQL injection off your worries. Just make sure to sanitize your variables before binding them to the query as well.
I figured I'd show how to insert your variables into your table with PDO.
$firstName = $_POST['first_name'];
$lastName = $_POST['last_name'];
$query = $dbPDO->prepare("INSERT INTO candidates first_name, last_name VALUES (:fname, :lname)");
$query->bindParam(':fname', $firstName);
$query->bindParam(':lname', $lastName);
$query->execute();
You could also make an array of both of your POST variables and pass that instead of binding each variable at a time.
$candidateName = array('$_POST['first_name']', '$_POST['last_name']');
$query = $dbPDO->prepare("INSERT INTO candidates first_name, last_name VALUES (?, ?)");
$query->execute($candidateName);
I hope that helps!
Happy coding!
The problem
Don't put table name and column names between apostrophes. That's what's causing your query to fail. Apostrophes are used to pass strings.
mysqli_query($conn, " INSERT INTO 'candidates'('first_name', 'last_name')
VALUES ('$first_name','$last_name')");
Should be
mysqli_query($conn, " INSERT INTO candidates(first_name, last_name)
VALUES ('$first_name','$last_name')");
Or
mysqli_query($conn, " INSERT INTO `candidates`(`first_name`, `last_name`)
VALUES ('$first_name','$last_name')");
if you like it better.
The error handling
In order to verify the problem you can echo the mysqli_error() function result whenever the query fails, it's a nice practice and would probably have helped you find a solution faster than asking it here.
$query= mysqli_query($conn, " INSERT INTO `candidates`(`first_name`, `last_name`)
VALUES ('$first_name','$last_name')");
if(!$query) //the query will return 0 if it fails
{
echo mysqli_error($conn);
}
The security issue
You're adding POST value directly into your query, which is dangerous.
On these lines:
$first_name= $_POST['first_name'];
$last_name=$_POST['last_name'];
You should be escaping user input.
This will escape any special characters that can cause issues in the mysql query.
$first_name = mysqli_real_escape_string($conn, $_POST['first_name']);
$last_name = mysqli_real_escape_string($conn, $_POST['last_name']);

Categories