Form post to db only once, php - php

a form is posted to db only once, i have to delete the row in db for the form to post new form data again. I tried several modifications from internet but didnt allowed me to post after the first successful time
Form:
<form action="post.php" method="POST">
<h5>A form:</h5>
<input class="right-inputs" id="field1" type="number" name="field1" placeholder="Enter stuff">
<input class="right-inputs" id="field2" type="text" name="field2" value="" readonly>
<script src="js/insert.js"></script>
<button class="btn-cmn" type="submit" name="submit">post</button>
</form>
post.php:
<?php
include_once 'db.php';
$var1 = $_POST['field1'];
$var2 = $_POST['field2'];
$sql = "INSERT INTO `a_table` (column1, column2) VALUES ('$var1', '$var2')";
mysqli_query($conn, $sql);
mysqli_close($conn);
header("Location: page.php?post=success");
?>
db.php:
<?php
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "database_sample";
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
?>
your table structure look like :

I think You have Primary Key in your table that not automatic generate value. So you can't add more row while have same Primary key..
Make sure you generate unique key for primary or have auto increment number for this.

I think issues in your database to put error_reporting(E_ALL); in your php page in top section then after try to insert so get some error view in your code.

Related

POST $variable to PHP xampp database?

I have created php submit button using form action with the intention of just storing a username and school name to be stored in a database using xampp by clicking okay button. I have set the database table to have flds for ID as primary key and AI, username and school set to varchar with max length of 50. The code i have used shown does $con to the DB but only the ID is being send to the DB?? (what have i missed or need to do so that the data inputted can be stored like the ID)?.
<?php
require 'config.php';
$username = " "; //$username
$school = " ";//what school they attend
if(isset($_POST['register_button'])){
$_SESSION['reg_username'] = $username; //Stores first name into session variable
$_SESSION['reg_school'] = $school; //Stores first name into session variable
$query = mysqli_query($con, "INSERT INTO users VALUES ('', '$username', '$school')");
}
?>
<html>
<head>
<title> School </title>
</head>
<body>
<h1> Welcome! </h1>
<form action="index.php" method="POST">
<input type="text" name="reg_username" placeholder="Name" value="<?php
if(isset($_SESSION['reg_username'])) {
echo $_SESSION['reg_username'];
}
?>" required>
<br>
<input type="text" name="reg_school" placeholder="School" value="<?php
if(isset($_SESSION['reg_school'])) {
echo $_SESSION['reg_school'];
}
?>" required>
<br>
<input type="submit" name="register_button" value="Okay">
</body>
</html>
You need to load the post data into your variables before you insert them. The only assignement you did was $username = '';
$username = $_POST['reg_username'];
$school = $_POST['reg_school'];

Blank entry when inserting into mysql (database)

i am trying to create a login and registration page using php and mysql but i met with some problem.
I reference to this video and the code is below (the code is incomplete, i only did for registration).
So the problem is that when i submit an entry using the register side, my database shows a blank record. I tried various method like
$reg = "INSERT INTO usertable (user,pwd) values ('".$user."','".$pwd."')";
but it did not work and when i did this:
$reg = "INSERT INTO usertable (user,pwd) values ('ABC','1234')";
it worked. What should i do to insert entry using the input text?
<?php
session_start();
$conn = mysqli_connect('localhost', 'root', '1234');
mysqli_select_db($conn,'registeration');
$user = $_POST["user"];
$pwd = $_POST["pwd"];
$s = "select * from usertable where user = '$user'";
$result = mysqli_query($conn,$s);
$num = mysqli_num_rows($result);
if($num == 1){
echo"Username Already Taken";
}
else{
$reg = "INSERT INTO usertable (user,pwd) values ('$user','$pwd')";
mysqli_query($conn,$reg);
}
?>
<h2> Register Here </h2>
<form action="index.html" method="post">
<label>Username</label>
<input type="text" name="user" required>
<label>Password</label>
<input type="text" name="pwd" required>
<br><button type="submit"> Login </button>
</form>
A easy way to know what's full SQL query string the program or you have made.
$reg = "INSERT INTO usertable (user,pwd) values ('$user','$pwd')";
echo $reg
It is better use {} to instead of . to insert variable into a string.
$reg = "INSERT INTO usertable (user,pwd) values ('{$user}','{$pwd}')";
To be sure the POST/GET action target is correct,
For your current code I am not sue index.html can handle it, probably it should be $_SERVER["PHP_SELF"]
To understand PHP String Operators, please refer to
https://www.php.net/manual/zh/language.operators.string.php
I found my mistake. I wrote my php and the register table (together in registration.php) however, my form redirects me to index.html. I copied and pasted my php into my index.php (changed the name) and it worked.
Thanks for those who helped me!
<h2> Register Here </h2>
<form action="index.php" method="post">
<label>Username</label>
<input type="text" name="user" required>
<label>Password</label>
<input type="text" name="pwd" required>
<br><button type="submit"> Login </button>
</form>

How to store different information in two different tables in MySQL?

I have two different tables in MySQL- one that stores account info (usernames, email, password) and one that stores names of classes they typed inside the field box. So basically, once the user clicks "register" they are brought to the page "class_creation.php" where they type their classes- that information is supposed to be stored in the "classes" table inside MySQL after the user clicks the "submit" button. Then the user is directed to a page called "signup.php" where they enter their account info (username, email, password) and the info from signup.php gets stored inside the MySQL table "users". The second page, signup.php successfully stores its data inside the "users" table- however the "class_creation.php" does not store any data inside its table- and everything is empty. I'm not sure if its a connection issue to phpmyadmin? I tried editing the connection file but nothing I tried seemed to work.
//This is the connection file- I'm using it to connect both the signup.php page and the class_creation.php page to the MySQL database. Its called: "dbh.inc.php"
<?php
$servername = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "loginsystem";
$class1 = $_POST['class1'];
$sql = "INSERT INTO user_classes (class1) VALUES ('class1')";
enter code here
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBName);
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
//This is the backend file I'm using for the class creation page- its called: "class.inc.php"
<?php
if (isset($_POST['submit'])) {
require 'dbh.inc.php';
require 'login.inc.php';
$class1 = $_POST['class1'];
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_bind_param($stmt, "s", $class1);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
header("Location../signup.php");
mysqli_stmt_close($stmt);
mysqli_close($conn);
?>
//And finally this is the "class_creation.php" code, used as the layout file for the textfields
<!DOCTYPE html>
<html>
<head>
<title/>
</head>
<body>
<form action="signup.php" method="POST">
<input type="text" name="class1" placeholder="" />
<input type="text" name="class2" placeholder="" />
<input type="text" name="class3" placeholder="" />
<input type="text" name="class4" placeholder="" />
<input type="text" name="class5" placeholder="" />
<input type="text" name="class6" placeholder="" />
<input type="text" name="class7" placeholder="" />
<input type="text" name="class8" placeholder="" />
<button type="submit" name="submit">Submit</button>
</form>
</body>
</html>
The info typed in by the user inside the class_creation.php page should appear in the MySQL database- but clearly I must be doing something wrong. Any ideas? The signup.php file seems to store its own data just fine inside the "users" table- let me know if you need to see those files as well but I believe the error is some where within these files.
In your class.inc.php, you can do something like:
<?php
if (isset($_POST['submit'])) {
require 'dbh.inc.php';
require 'login.inc.php';
$class1 = $_POST['class1'];
$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "s", $class1);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_close($stmt);
mysqli_close($conn);
header("Location../signup.php");
}

Inserting input field value to database and displaying result on same page

I am starting to learn the basics of SQL and PHP codes.
I am trying to create a simple newsletter subscription page. this would require the user to enter their email and submit. That will then get added to my database.
Now, this works well when the HTML and PHP code are separate and the submission occurs but redirects to the PHP page with the echo.
I want to get the message on the same page and I tried merging the PHP code in the page as below
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
mysql_connect("hostname", "username", "password");
mysql_select_db("db name");
$user = $_POST['email'];
$query = "INSERT INTO tablename(columname)VALUES('$email')";
echo "inserted";
}
?>
<html>
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
</html>
Hoever with this code it just doesnt do anything.
What have am I doing wrong here? Appreciate your expert advice.
There are few mistakes in the code, you can fix them by doing the following:
Save the file as a php file first. For example name it "email.php".
Make the form action="email.php"
Don't write two complete separate codes in the same file, one for php file and the other for html file like you did. You can include the html code inside the php code using heredoc syntax which allows you to include a long html code like the following:
echo<<<_HTMLCODE
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
_HTMLCODE;
In the query syntax, add $user instead $email because the variable $user contains the value submitted by the form.
Add a code to excute the inserted query. for example:
mysql_query($query);
So your final code will be like this:
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
mysql_connect("hostname", "username", "password");
mysql_select_db("db name");
$user = $_POST['email'];
$query = "INSERT INTO tablename VALUES('$user')";
mysql_query($query);
echo "inserted";
}
echo<<<_HTMLCODE
<form method="POST" action="email.php" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
_HTMLCODE;
?>
I have tried the code above after I added the data of my database on the localhost and after I created a table for the emails and it worked. Here is the edited code with my database access info and the table name in my code editor:
When i opened the table emails in my database, I found the email that I had submitted using the form (your modified code):
(advice: use mysqli instead of mysql)
Please use prepare statements to prevent Sql Injections.
Here is sample code try this.
ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli ("localhost", "root", "usbw", "test");
if (mysqli_connect_errno()) {
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}
if (isset($_POST['submit'])) {
$email = filter_input(FILTER_VALIDATE_EMAIL, $_POST['email']);
$sql = "INSERT INTO table (email) VALUES (?)";
$stmt = $connect->prepare($sql);
$stmt->bind_param('s', $email);
$result = $stmt->execute();
if ($result) {
$msg = 'Succesfully added';
} else {
$msg = 'OOPS Error Occured';
}
}
?>
<html>
<form method="POST" action="" >
<label>Email:</label> <input name="email" type="text"/>
<input type="submit" name="submit" value="Insert" /> <br>
</form>
</html>

HTML Form Using Values In Multiple Places

I have 3 files.
1st one :
<html>
<form action="employeeDel.php" method ="post">
Enter Ssn To Delete Employee:<br>
<input type="number" name="ssnDel">
<br>
<br>
<input type="submit" value="Submit">
</form>
</html>
This form sends data to employeeDel.php.
employeeDel.php :
<html>
<form action ="employeeDelFinal.php" method="post">
<input type="hidden" name="ssn" value="ssnDel">
<?php
$ssnDel = $_POST ["ssnDel"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "company";
$conn = mysqli_connect ( $servername, $username, $password, $dbname );
// Check connection
if (! $conn) {
die ( "Connection failed: " . mysqli_connect_error () );
}
$sql = "SELECT * from employee WHERE ssn=".$ssnDel;
<input type="submit" name="Delete?">
</form>
</html>
From here, when user clicks on submit button, I want html form to send ssnDel value to employeeDelFinal.php file.
employeeDelFinal.php :
<?php
$ssnDel = $_POST ["ssn"];
echo ssnDel;
?>
That value never reaches here. I got an error on employeeDel.php file, it says value of ssnDel is null. I guess in the beginning of form in employeeDel file, I create ssnDel again, so it becomes null.
Is there a way to send a data from html form to employeeDel.php, from employeeDel.php to employeeDelFinal.php by using form? I tried hidden text but it didn't solve my problem as seen.
The line
<input type="hidden" name="ssn" value="ssnDel">
should be something like
<input type="hidden" name="ssn" value="<?php echo(intval($_POST['ssnDel'])); ?>">
(Assuming that ssnDel is an ID-Number.)
Otherwise that hidden variable will have the string-value ssnDel, not the value of the variable $_POST['ssnDel'].
And as already mentioned, echo ssnDel; should be echo $ssnDel; and you should use less spaces (e.g. no spaces after $_POST or function names).
There are couple of things I noticed. You have
employeeDelFinal.php :
<?php
$ssnDel = $_POST ["ssn"];
echo ssnDel;
?>
You don't have a dollar sign in your echo statement ssnDel.
And why do you have spaces in between $_POST ["ssnDel"] make it
$_POST["ssnDel"]

Categories