Justin Harwood
Justin Harwood

Reputation: 47

Inputted values not saved while inserting data from html form into sql database (html,php,sql)

The problem: insert.php connects fine, but only inserts empty values ('') when I hit 'save' on the html form. The text I type, which I'm trying to insert, isn't saved. Somewhere a connection isn't being made and that data is lost but I can't figure out exactly where. Any help?

HTML insert form (collecting data for 2 parameters, 'user' and 'thread')

<form action="insert.php" method="post">
user: <input type="text" name="user"><br>
thread: <input type="text" name="thread"><br>
<input type="submit" value="Save">
</form>

PHP code to connect to SQL, insert inputted values

<?php

$user = $_POST['user'];
$thread = $_POST['thread'];

$servername = "##.##.###";
$username = "harwoodjp";
$password = "~";
$dbname = "332";

//create connection
$conn = new mysqli($servername, $username, $password, $dbname);

//check connection
if ($conn->connect_error) {
    die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";

$sql = mysql_connect($servername,$username,$password);
mysql_connect($servername,$username,$password);
mysql_select_db("332project");

//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);

echo "<script>window.location='select.php'</script>"; //select.php displays the full table

//close MySQL
mysql_close($sql);
?>

Upvotes: 4

Views: 1844

Answers (2)

jay.jivani
jay.jivani

Reputation: 1574

try this

<?php

$user = $_POST['user'];
$thread = $_POST['thread'];

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";

//create connection
$conn = mysql($servername, $username, $password, $dbname);

//check connection
if ($conn->connect_error) {
    die("SQL (&#9746)<br/> " . $conn->connect_error);
}
echo "SQL (&#9745) <br/>";

$sql = mysql_connect($servername,$username,$password);
mysql_select_db("db");

//insert values
$insert_query = "INSERT INTO test1(user,thread) VALUES ('$user', '$thread')";
mysql_query($insert_query);

echo "<script>window.location='select.php'</script>"; //select.php displays the full table

//close MySQL
mysql_close($sql);

?>

Upvotes: 1

Lynn Adrianna
Lynn Adrianna

Reputation: 107

It might be because the default form posting method is GET.

Either change your $_POST to $_GET or add method="POST" to your form tag.

Upvotes: 0

Related Questions