Form submission not working properly from wordpress page - php

I am trying to make an insert form directly inside wordpress post, the code is working partly fine i.e. it is adding blank row in "test" table in "webdatabase" with every submission but not adding any value in name and rollno column, it is also not displaying any error.
Please help so that value submitted through form can be inserted in to "test" table, thanks in advance.
My form with php code is as under:
<form action="http://localhost/wordpress" method="POST">
Name:<br><input type="text" name="name" value=""><br>
Roll No:<br><input type="text" name="rollno" value=""><br><br>
<input type="submit" value="Submit">
</form>
<?php
$testname = $_POST['name'];
$testrollno = $_POST['rollno'];
$conn = new mysqli("localhost","root", "","webdatabase");
$sql = "INSERT INTO test (name,rollno) VALUES (' " . $testname . " ', '" . $testrollno . "')";
mysqli_query($conn, $sql);
$conn->close();
?>
My table structure in mysql database is shown as under:
Column Type
ID int(15)
name varchar(20)
rollno varchar(20)

You can use the “isset” function on any variable to determine if it has been set or not. You can use this function on the $_POST array to determine if the variable was posted or not. This is often applied to the submit button value, so
The HTML will be;
<form action="http://localhost/wordpress" method="POST">
Name:<br><input type="text" name="name" value=""><br>
Roll No:<br><input type="text" name="rollno" value=""><br><br>
<input type="submit" name="action" value="Submit">
</form>
and PHP will be;
<?php
if (isset($_POST['action'])) {
$testname = mysqli_real_escape_string($_POST['name']);
$testrollno = mysqli_real_escape_string($_POST['rollno']);
$conn = new mysqli("localhost","root", "","webdatabase");
$sql = "INSERT INTO test (name,rollno) VALUES (' " . $testname . " ', '" . $testrollno . "')";
mysqli_query($conn, $sql);
$conn->close();
}
?>

Since you are using WordPress, you should use the WordPress DB API. https://codex.wordpress.org/Class_Reference/wpdb
Complete code:
<form action="http://localhost/wordpress" method="POST">
Name:<br /><input type="text" name="name" value=""><br />
Roll No:<br /><input type="text" name="rollno" value="" /><br /><br />
<input type="submit" value="Submit">
</form>
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$wpdb->insert('test', array('name' => $_POST['name'], 'rollno' => $_POST['rollno']));
}
Note: above code is untested

Related

How to upload a radio button value entered in an html form

I have made the form so that it gets the selected radio value button and it gets passed to the php section and to the database.But in the database it shows as "on" no matter what the selection is.
I have no idea where I have gone wrong
HTML form:
<form action="Database.php" name="register" method="post">
<div>
First Name <input type="text" name="fname"/><br>
Last Name <input type="text" name="lname"/><br>
Email <input type="email" name="email"/><br>
Contact No. <input type="text" name="num"/><br>
Gender <br> <input type="radio" name="g1" value="Male"/>Male
<input type="radio" name="g1" value="Female"/>Female
<br>
<br>
</form>
PHP:
$fname = $conn->real_escape_string($_POST['fname']);
$lname = $conn->real_escape_string($_POST['lname']);
$email = $conn->real_escape_string($_POST['email']);
$cnumber = $conn->real_escape_string($_POST['num']);
$gender = $conn->real_escape_string($_POST['g1']);
$sql="INSERT INTO data (fname, lname, email, cnumber, gender)
VALUES ('".$fname. "','".$lname."','".$email."', '".$cnumber."', '".$gender."')";
I expected output to be male/female
but it says "on"
Using your form I have used a small code and found this works
<form action="Database.php" name="register" method="post">
<div>
First Name <input type="text" name="fname"/><br>
Last Name <input type="text" name="lname"/><br>
Email <input type="email" name="email"/><br>
Contact No. <input type="text" name="num"/><br>
Gender <br> <input type="radio" name="g1" value="Male"/>Male
<input type="radio" name="g1" value="Female"/>Female
<br>
<input type="submit" style="min-width:100%" align="center" name='submit' value="SUBMIT">
<br>
</form>
Your PHP side should be this:
if(!isset($_POST['submit']))
{
//This page should not be accessed directly. Need to submit the form.
echo "Submitted";
}
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$g1 = $_POST['g1'];
$sql = "INSERT INTO etrack.test SET
fname = '".$fname."',
lname = '".$lname."',
g1 = '".$g1."'";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
echo("Error description: " . mysqli_error($con));
echo "Error 1";
}
I am getting the required results

PHP and SQL - Trying to change user login data, does nothing

I'm trying to create a form that lets an administrator change a user's password. I used this to create the forms on the page. The first allows deletion and works fine, the second should be sending the new password from the form to a function that sends to the post function I'll post below it.
echo <<<_END
<pre>
username $row[0]
role $row[2]
</pre>
<form action="admin2.php" method="post">
<input type="hidden" name="delete" value="yes">
<input type="hidden" name="username" value="$row[0]">
<input type="submit" value="DELETE RECORD"></form>
<pre>password <input type="text" name = "password"></pre>
<form action="admin2.php" method="post">
<input type="hidden" name="change" value="yes">
<input type="hidden" name="username" value="$row[0]">
<input type="submit" value="CHANGE PASSWORD">
_END;
And the if statement:
if (isset($_POST['change']) && isset($_POST['username']) &&
isset($_POST['password']))
{
$username = get_post($connection, 'username');
$password = get_post($connection, 'password');
$query = "UPDATE users SET password='$password' WHERE username='$username'";
$result = $connection->query($query);
if (!$result) echo "UPDATE failed: $query<br>" .
$connection->error . "<br><br>";
}
The page loads but when I press the button there isn't any change on the backend. Any ideas?
EDIT:
Ok, having made the changes linked to above, it does change the password but only when it's the last entry in the table. Otherwise it just deletes the entry on the table below it.
if (isset($_POST['delete']) && isset($_POST['username']))
{
$username = get_post($connection, 'username');
$query = "DELETE FROM users WHERE username='$username'";
$result = $connection->query($query);
if (!$result) echo "DELETE failed: $query<br>" .
$connection->error . "<br><br>";
}
What you need to do is , put the password input in the second form tag.like this (the the button name to edit.) :
<form action="admin2.php" method="POST">
<input type="password" name="password" />
......
<input type="submit" name="edit" value="Edit" />
</form>
The admin2.php cannot read the password post because the form not send the password in the post request.
The change the PHP code:
if (isset($_POST["edit"]))
{
if(isset($_POST["username"], $_POST["password"])){
$username = get_post($connection, 'username');
$password = get_post($connection, 'password');
$query = "UPDATE users SET password='$password' WHERE username='$username'";
$result = $connection->query($query);
if (!$result) echo "UPDATE failed: $query<br>" .
$connection->error . "<br><br>";
}
}
Your problem is, you run two form in one php script, so you need to differ which form refer to which PHP code block. If you put 2 form run on one PHP script, with the same names (include the button), then the server will run from the first PHP script that contain the names.

Inserting HTML Form data into MySQL with PHP

I'm trying to make a simple message board MySQL database where you can write a review and submit it via an HTML form on one page and view all of the reviews on a separate page once you've submitted your review.
My problem is two of the fields from the HTML form are not being inserted into my MySQL database which results in my view all reviews page to be missing the Name and Title.
Link to what the "Read all Reviews" page looks like.
The code works without any issue when I tested it doing MySQL queries with just PHP but I need my HTML form to work.
HTML form:
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name "name" id = "name"><br />
Title of Review:<br />
<input type="text" name "title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
Code for process.php:
<?php // Create a database connection.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "password";
$dbname = "ya_reviews";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
//Test if connection occurred.
if (mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
//Perform database query
$name = $_POST['name'];
$title = $_POST['title'];
$body = $_POST['body'];
//This function will clean the data and add slashes.
// Since I'm using the newer MySQL v. 5.7.14 I have to addslashes
$name = mysqli_real_escape_string($connection, $name);
$title = mysqli_real_escape_string($connection, $title);
$body = mysqli_real_escape_string($connection, $body);
//This should retrive HTML form data and insert into database
$query = "INSERT INTO reviews (name, title, body)
VALUES ('".$_POST["name"]."','".$_POST["title"]."','".$_POST["body"]."')";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if ($result) {
//SUCCESS
header('Location: activity.php');
} else {
//FAILURE
die("Database query failed. " . mysqli_error($connection));
//last bit is for me, delete when done
}
mysqli_close($connection);
?>
View all Reviews:
<?php
//This will fetch the data from the database
$query = "SELECT * FROM reviews";
$result = mysqli_query($connection, $query);
//Test if there was a query error
if (!$result) {
die("Database query failed.");
}
// This will let me display the data.
// The loop will be spilt so I can format with HTML
while ($row = mysqli_fetch_assoc($result)) {
//output data from each row
?>
Name: <?php echo $row["name"] . "<br />"; ?>
Title: <?php echo $row["title"] . "<br />"; ?>
Review: <?php echo $row["body"] . "<br />";
echo "<hr>"; ?>
<?php
} ?>
Note: I connected to the database with the same code seen in process.php before the above code, I excluded it to save space.
Your HTML attribute syntax is incorrect. Its missing = sign between attribute and value.
Change name "name" to name="name" and name "title" to name="title"
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Also during insert you aren't using escaped values.
Use $name instead of $_POST["name"] in insert query. Same goes for title and body values.
The problem is that the name attribute is not correct in HTML.
<input type="text" name="name" id = "name"><br />
<input type="text" name="title" id = "title"><br />
I think you messed up with syntax of HTML
<form action ="process.php" method = "post">
<fieldset>
<legend>Review Field</legend>
Reviewer Name: <br />
<input type="text" name="name" id = "name"><br />
Title of Review:<br />
<input type="text" name="title" id = "title"><br />
Enter your review below:
<!--Textbox start-->
<textarea name="body" id = "body" rows="10" cols="100">
</textarea>
<!--Textbox end-->
<br />
<input type="submit" name = "submit" id="submit">
<br />
</fieldset>
</form>
It will work surely!
Yo, you're just missing some syntax, therefore creating errors when it comes to gathering the data from those elements,
<input type="text" name "title" id = "title">
You're missing the "=" sign from the name parameter

Dynamic insert into with multiple values

This is my index.php file and it has a simple form but with jscript I'll add some more inputs dynamically, then I need to insert these inputs to my database.
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid_1" placeholder="cid1">
<input type="text" name="cid_2" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
</form>
I've created insert.php as below. I just needed to type for each inputs but actually inputs will be added dynamically as I said, so I just need to apply while or foreach function I guess but I'm not that sure how to do, hope someone there can help me about this.
One more thing I need, In this case everything is working but it inserts everytime even if some inputs are empty. I could not found anything about this too.
Thank you for your help from now.
<?php
$link = mysqli_connect("localhost", "root", "", "test");
$uid = mysqli_real_escape_string($link, $_POST['uid']);
$cid1 = mysqli_real_escape_string($link, $_POST['cid_1']);
$cid2 = mysqli_real_escape_string($link, $_POST['cid_2']);
$sql = "INSERT INTO table (uid, cid) VALUES ('$uid', '$cid1'), ('$uid', '$cid2')";
mysqli_query($link, $sql)
?>
From your SQL query I understood that under uid, you are storing dynamic "cid" values from input. So you are adding dynamic input fields for "cid".
In order to capture dynamic fields on server, you have to name your input fields as given below which will be posted as an array on server.
<input type="text" name="cid[]" placeholder="cid1">
Next you will loop through that array and save each input data in your table.
Complete code:
HTML
<form action="insert.php" method="post">
<input type="text" name="uid" placeholder="uid">
<input type="text" name="cid[]" placeholder="cid1">
<input type="text" name="cid[]" placeholder="cid2">
<input type="submit" value="Register" name="submit" />
PHP
$mysqli = new mysqli('localhost','usename','password','table');
$uid = $mysqli->real_escape_string($_POST['uid']);
if($uid !== ''){
if(isset($_POST["cid"]) && is_array($_POST["cid"])){
foreach ($_POST["cid"] as $key => $value) {
$value = $mysqli->real_escape_string($value);
if($value !== ''){
// insert into table
$insert_row = $mysqli->query("INSERT INTO test ( uid, cid ) VALUES( '$uid', '$value' )");
}
else{
echo ($key+1)." no cid field is empty";
break;
}
}
}
}
else
echo "uid is empty";

Inserting data to database via web form

I have looked for the answer to my question and seeing as all programming varies I can't seem to fix my problem. I have created a php file that does in fact connect to my database. However, when I try submitting data to my database via my php webpage it won't go through. The same happens when I try to display info from my database to a webpage. Seeing as it is in fact connecting to the database, I'm not sure what the issue is. Any help is appreciated, try to dumb it down for me as much as possible when you answer. Also, I have triple-checked my database name and table names to make sure they match up with my coding. Here's my code:
Connection to database:
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PSWD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'art database');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
My form to insert data to my database:
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sqlinsert = "INSERT INTO users (first name, last name) VALUES ('$fname','$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
$newrecord = "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>
The reason it's not working is because you have spaces in your columns/query.
INSERT INTO users (first name, last name)
wrap them in backticks like this:
INSERT INTO users (`first name`, `last name`)
It is not recommended to use spaces in column names or tables.
Try and use underscores instead, or remove the spaces and make the appropriate changes to your columns in your DB also, if you do.
You should also consider using:
('" . $fname . "','" . $lname . "')
instead of ('$fname','$lname')
I'm also questioning this => DEFINE ('DB_NAME', 'art database');
There is a space in between art and database. If that is the case and is in fact the name you've given your DB, do rename it to art_database and use DEFINE ('DB_NAME', 'art_database'); instead.
And do use the following for added protection:
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
Interesting article to read on protection:
How can I prevent SQL injection in PHP?
EDIT: (options)
OPTION 1, in 2 files:
First, rename your columns to firstname and lastname and use the following code and naming your file insert-data.php
DB query file (insert-data.php)
<?php
if (isset($_POST['submit'])) {
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Then in a seperate file, your HTML form; name it db_form.php for example:
HTML form (db_form.php)
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
</body>
</html>
NEW EDIT - OPTION 2, all in one file:
Use this in one page, with nothing else added:
<?php
if (isset($_POST['submit'])) {
if(empty($_POST['fname'])) {
die("Fill in the first name field.");
}
if(empty($_POST['lname'])) {
die("Fill in the last name field.");
}
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="">
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>
I have made some changes, which is working fine for me
Where i can ignore if data is already in database
You Can try this to
<?php
if (isset($_POST['submit'])) {
include('db.inc.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
// $sqlinsert = "INSERT INTO `user` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
$sqlinsert = "INSERT IGNORE INTO `dbname`.`user` (`fname`, `lname`) VALUES ( '$fname', '$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Where db.inc.php is a different file in same directory for connecting database
<?php
$dbcon=mysqli_connect("localhost","dbuser","yourpassword","dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Categories