So i'm pretty new to PHP and can't understand why my POST request is not working. .
I'm just building a simple TodoApp and have a Add new task view like this:
add.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" />
<link rel="stylesheet" href="../css/style.css" />
<title>To-Do List</title>
</head>
<body>
<div class="wrapper">
<form action="" method="post">
<h2 class="title">Add a new task</h2>
<div class="content">
<div class="inputFields">
<label for="task">Task:</label>
<input type="text" name="task" placeholder="Task name" />
<label for="task">Description:</label>
<br />
<textarea type="text" name="description" placeholder="Add a description" rows="5"
cols="40"></textarea>
<br />
<button type="submit" class="btn">Save</button>
</div>
</div>
</form>
<button class="btn">Go back</button>
</div>
</body>
</html>
My db file DB.php looks like this:
<?php
error_reporting (E_ALL ^ E_NOTICE);
/**
* #package DBConnection
* #author Frida
*/
// DB Connection
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=TodoApp', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// GET - Get All tasks
$statement = $pdo->prepare('SELECT * FROM todo_list ORDER BY created DESC');
$statement->execute();
// Fetch all tasks as an assoc array
$tasks = $statement->fetchAll(PDO::FETCH_ASSOC);
// POST - Add a task
$task = $_POST['task'];
$description = $_POST['description'];
$date = date('Y-m-d H:i:s');
$pdo->exec("INSERT INTO todo_list (task, description, status, created)
VALUES ('$task', '$description', 0, '$date')
")
?>
This is my schema:
Todo schema
I've done var_dump($_POST) which shows the array without any issues, if anyone can help me out?
In your HTML form action attribute is empty which mean that form is submit to same file in your case add.php.
So you should use $_POST in add.php file either you must submit form to DB.php for example
<form action="DB.php" method="post">
Related
I'm super new to PHP and I recently tried to create a "system" that adds customers to the SQLite database and displays them in a table. Well, every time I navigate to the HTML page in order to add a new customer, the script runs itself creating empty values within the database. When I click submit after filling the values it just works properly. Below I attach my code for this specific part of the "system".
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>New Customer</title>
<style>
form {
display:flex;
flex-direction:column;
width:65%;
max-width:75%;
margin:0 auto;
}
</style>
</head>
<body>
<form action="" method="POST">
<h1>Insert a new customer</h1>
<label for="id">Customer Id</label>
<input type="text" name="id" id="id">
<label for="name">Customer Name</label>
<input type="text" name="name" id="name">
<label for="age">Customer Age</label>
<input type="number" name="age" id="age">
<label for="address">Customer Address</label>
<input type="text" name="address" id="address">
<button type="submit">Submit</button>
</form>
<?php
class COMPANY extends SQLite3 {
function __construct() {
$this->open('customers.db');
}
}
$database = new COMPANY();
if (!$database) {
echo $database->lastErrorMsg();
} else {
echo "Database accessed!\n";
}
$insert ="INSERT INTO CUSTOMERS (ID, NAME, AGE, ADDRESS) VALUES ('".$_POST["id"]."', '".$_POST["name"]."', '".$_POST["age"]."','".$_POST["address"]."');";
$result = $database->exec($insert);
if(!$result) {
echo $database->lastErrorMsg();
} else {
echo "Records added successfully!\n";
}
$database->close();
?>
</body>
</html>
You need to use isset() and check if the form has actually posted the values. In your code, the page loads and PHP code executes without checking if the form has submitted and the blanks are inserted in the database
if(isset($_POST['id'],isset($_POST['name'],isset($_POST['age'], isset($_POST['address']) {
.. your code
}
PS: this doesn't include sanitization and validation of fields, please add them as you wish
There should be validation, values should not be empty.
I am making social project form and im trying to add reply ..the reply button is a link that sends user to reply.php page with post id saved in href...on the reply.php my form action is the same page but when i click button to submit form it doesnot get the id and refreshes page with post and display error undefined id need help..
here is my reply.php
<?php
require('session.php');
$id=$_GET['id'];
//echo $id;
$submit=#$_POST['submit'];
$reply=#$_POST['reply'];
if(isset($submit)){
$id=#$_GET['id'];
$sql=mysqli_query($con,"INSERT INTO REPLY (reply,Username,post_id) VALUES '$reply','$user_check','$id'");
$sql2=mysqli_query($con,"SELECT * FROM REPLY WHERE post_id= '$id'");
while($row=mysqli_fetch_array($sql2)){
echo $row['Username']."<br/>".$row['reply']."<br/>";
}
}
else "error in submission";
?>
<!DOCTYPE html>
<html>
<title>Studhelp</title>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="w3.css">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src="bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Raleway">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<?php
$sql=mysqli_query($con,"select * from posts where post_id='$id'");
while($row=mysqli_fetch_array($sql)){?>
<!-- Middle Column -->
<div class="w3-col m7">
<div class="w3-row-padding">
<div class="w3-col m12">
<div class="w3-card-2 w3-round w3-white">
<div class="w3-container w3-padding">
<h3 class="w3-opacity"><?php echo $row['Username'] ;?></h3>
<?php
echo $row['Posts']."<br/>".$row['date']."<br/>";
}
?>
</p>
</div>
</div>
</div>
</div>
<form action="reply.php" method="post">
<input type="text" name="reply" >
<input type="submit" name="submit" value="reply">
</form>
this is the anchor tag send id to reply.php
Reply
If I understand correct you need to be able to read your "id" variable after you post the form. To achieve this use $_REQUEST instead of $_GET, like this:
$id = $_REQUEST['id'];
And also pass the variable with your form, as a hidden field:
<form action="reply.php" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="text" name="reply" />
<input type="submit" name="submit" value="reply" />
</form>
You didn't check if the fom was submitted
Enclose other PHP code after session.php inside a conditional checker such as:
if ($_POST):
You can use form tags to create a form and put the id field as hidden.
GET requests shouldn't be use to modify data
I am trying to create a very simple Control Panel for a web programming project, the "Show" function in my control panel works very well and shows all the elements by my Delete, Add and Update functions do not work at all.
Here's what I want to do with each function:
Add function -> I want to add an element to my database from the input elements
Delete function -> I want to delete the element that its ID is input by the user in the Control Panel
Update -> Using this function I want to change the Product Title of the selected Product.
These 3 functions don't work, when I input data in the webpage I see that nothing is added/altered to/in the tables.
Here's the code:
add.html
<title>Add</title>
</head>
<body>
<form action="add.php" method="post">
<font size="+2" color="#CC0033">ID</font><input type="text" name="ID" />
<font size="+2" color="#CC0033">Product Title</font><input type="text" name="ProductTitle" />
<font size="+2" color="#CC0033">Price</font><input type="text" name="Price" />
<font size="+2" color="#CC0033">Quantity</font><input type="text" name="Quantity" />
<input type="submit" value="Insert" />
</form>
</body>
</html>
add.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Done</title>
</head>
<body>
<?
$ID=$HTTP_POST_VARS["ID"];
$ProductTitle=$HTTP_POST_VARS["ProductTitle"];
$Price=$HTTP_POST_VARS["Price"];
$Quantity=$HTTP_POST_VARS["Quantity"];
$db=mysql_connect("localhost","root","");
if($db==false)
{
print "Error";
exit;
}
mysql_select_db("Computer");
$query=("insert into Products values('".$ID." ',' ".$ProductTitle."',' ".$Price."',' ".$Quantity."')");
mysql_query($query);
?>
</body>
</html>
delete.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
Enter the ID of the product that you wish to delete:
<form action="delete.php" method="post">
<input type="text" name="UserInput">
<br>
<input type="submit" value="Delete">
</form>
</body>
</html>
delete.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?
$UserInput=$HTTP_POST_VARS["UserInput"];
$db=mysql_pconnect("localhost","root","");
if(!db)
{
print "Error";
exit;
}
mysql_select_db("Computer");
$query=("delete from Products where ID=".'$UserInput');
mysql_query($query);
?>
</body>
</html>
update.html
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<form action="update.php" method="post">
Product ID<input type="text" name="ProductID">
Product Name<input type="text" name="ProductTitle">
New Product Name<input type="text" name="NewProductTitle">
<br>
<input type="submit" value="Update">
</form>
</body>
</html>
update.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?
$ProductID=$HTTP_POST_VARS["ProductID"];
$ProductTitle=$HTTP_POST_VARS["ProductTitle"];
$NewProductTitle=$HTTP_POST_VARS["NewProductTitle"];
$db=mysql_pconnect("localhost","root","");
if(!$db)
{
echo "Error";
exit;
}
mysql_select_db("Computer");
$query=("update Products set ProductTitle='".$NewProductTitle. "' where ID=$ProductID");
mysql_query($query);
?>
</body>
</html>
firstly, good on you for trying to come up with a solution, however, as other commenters have said, you do have issues in your script. Firstly, I'd consider replacing $HTTP_POST_VARS["ID"]; with the $_POST global variable, and also running an if(isset()) to ensure all fields were set when the user submitted the form.
Secondly, you should consider using MySQLi or PDO for handling your database connection, as they can also provide validation and filtration to prevent injection attacks as Marc B mentioned. It's a good attempt if you are an absolute beginner and I feel if you stick at it you can progress further, and this community is great for getting answers and understanding where you have gone wrong. Hopefully this helps and good luck! :)
This is my coding for the search form:
<html>
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form action="https://excelforth.com/search1.php" method="GET">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
</body>
</html>
The thing is , When I submit this form on my web page , It goes to the php Results page and displays the results. But the thing is that it is just a plain page with just the results displayed.
My search page :
www.mysite/test/certification-database-search/
The Php file is located in my webroot folder . I was told that for wordpress , the individual subpages cannot be edited .
How do I :
1.Display the results on the same page as the search page. Not a completely new page.
2.Retain the page layout and theme / headers/ footers of the page
3.If possible run the .php file in /certification-database-search/ and query it from there. instead of using the one in my webroot folder.
THANKS!!
Put your form and PHP in one page, PHP on top with HTML below, then use action=""
Use the variables from the inputs as $var=$_GET['var']; then echo $var;
Sidenote: If you want to stop a process, you can use die(); or exit();
You can put a message inside it; i.e.: die("Enter a search term");
A basic example:
<?php
if(isset($_GET['submit'])){
$query=$_GET['query'];
echo $query;
}
?>
<html>
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form action="" method="GET">
<input type="text" name="query" />
<input type="submit" name="submit" value="Search" />
</form>
</body>
</html>
An alternative, showing an error message if field is empty:
<?php
if(isset($_GET['submit'])){
if(empty($_GET['query'])){
echo "Enter a search term";
}
$query=$_GET['query'];
echo $query;
}
?>
<html>
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form action="" method="GET">
<input type="text" name="query" />
<input type="submit" name="submit" value="Search" />
</form>
</body>
</html>
Ok so what I want to build:
A website where you login (I will do this later). There is a form where you submit your news report, which then goes into a MySQL database. This then gets displayed in a table view on the iPhone (that comes later).
As I mentioned, I get an 'Error querying database'. I have tried to fix it but I am new to MySQL and PHP, so I don't know what else to do.
I have this set up on a home server (WAMP).
My report.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Football Central News Report Submission Page</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h1>Football Central News Report Submission Page</h1>
<h2>Sumbit your football news report here</h2>
<h3>CHECK FOR MISTAKES !!!</h3>
<form method="post" action="report.php">
<label for="title">Title:</label>
<input type="text" name="title" />
<br />
<label for="author">Author:</label>
<input type="text" name="author" />
<br />
<label for="subtitle">Subtitle:</label>
<input type="text" name="subtitle" />
<br />
<label for="body">Body:</label>
<textarea name="body"></textarea>
<br />
<label for="image">Image:</label>
<input type="file" id="image" name="image" />
<br />
<input type="submit" value="Submit your news report" name="submit" />
</form>
</body>
</html>
My report.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Football Central News Report Submission Page</title>
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<h1>Football Central News Report Submission Page (Confirmation)</h1>
<?php
$title = $_POST['title'];
$author = $_POST['author'];
$subtitle = $_POST['subtitle'];
$body = $_POST['body'];
$image = $_POST['image'];
$dbc = mysqli_connect('localhost', 'root', 'xxxxxx', 'news_reports')
or die('Error connecting to database server.');
$query = "INSERT INTO news_reports (title, author, subtitle, body) " .
"VALUES ('$title', '$author', '$subtitle', '$body', '$image')";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
mysqli_close($dbc);
?>
<p>
-Thanks for submitting the form.<br />
-Your news report has been submitted to the database and should appear in the app shorty.
</p>
</body>
</html>
AND FINALLY-My database structure (I can't post screenshots)
Fields:
report_id (primary key, auto-increment)
title
author
subtitle
body
image
P.S
For image /\ I am following "Head First PHP and MySQL", so it is the image name that is stored in the db, not the image (I haven't put this into the form, but I don't THINK this is the problem).
Sorry for the long post guys.
Luke
You have a mismatch. You named 4 columns to insert to but you defined 5 values. Add the missing column.
$query = "INSERT INTO news_reports (title, author, subtitle, body) " .
"VALUES ('$title', '$author', '$subtitle', '$body', '$image')"