Reputation: 171
I'm trying to connect my website to a database, by adding whatever someone writes from the form to a table in my database, but so far I've only gotten errors and nothing appears on my MySQL database.
The error that I keep getting are these two:
Notice: Undefined index: fill
Warning: mysql_close() expects parameter 1 to be resource, object given in (folder)
How do I proceed to solve this problem?
<form action="insert.php" method="post">
<label for="fill">Add:</label>
<input type="text" name="fill">
<input type="submit" value="Insert!">
</form>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "database";
$conn = mysqli_connect($servername,$username,$password,$dbname);
if ($conn->connect_error) {
die ("connection failed: " . $conn->connect_error);
}
else
{
echo 'Connected to database';
}
mysql_select_db($dbname);
$sql = "INSERT INTO card_refill ('refill') VALUES ('$_POST[fill]')";
mysql_close($conn)
?>
Upvotes: 0
Views: 61
Reputation: 91
Since the dbname is already provided in mysqli_connect
function, mysql_select_db($dbname)
is not necessary. As for the execution of the query, SQL string should be run via mysqli_query
function. However before running SQL queries, the variables need to be sanitised to prevent SQL injections and XSS attacks.
Try something like this:
$conn = mysqli_connect($servername,$username,$password,$dbname);
if ($conn->connect_error) {
die ("connection failed: " . $conn->connect_error);
}else{
echo 'Connected to database';
}
$sql = "INSERT INTO card_refill ('refill') VALUES ({$_POST['fill']})";
$result = mysqli_query($conn,$sql);
//do whatever you need to do with the result
mysqli_close($conn);
Upvotes: 1
Reputation: 1416
This database insert part should be done only if you press the submit of form. So use isset
to detect submit.
Put all the php code inside a if loop.
if(isset($_POST['fill'])) //execute only if fill is set
{
$conn = mysqli_connect......;
// all your codes here
mysqli_close($conn);
}
Upvotes: 1