1

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:

  1. I can connect to database and insert in the correct columns checkbox and radio values from the form

  2. 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;
    
  3. 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!

Qirel
  • 25,449
  • 7
  • 45
  • 62
Letizia
  • 23
  • 1
  • 7

2 Answers2

3

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?

burn
  • 31
  • 1
0

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']);
Mohamed Abulnasr
  • 589
  • 7
  • 18