My PHP file is not posting form to the database - php

enter code hereMy php file is not posting the form on my database. I have searched in other threads, but i can't make it work.
I tried everything, but I can't make it work. I am using XAMPP for hosting.
Code:
<?php
$link=mysql_connect('localhost','root','');
mysql_select_DB('registro',$link);
?>
<html>
<head>
<meta charset="utf-8" />
<link rel="icon" type="image/png" href="/images/icon.png" />
<title>Insert.</title>
<link href="estilo.css" rel="stylesheet" type="text/css" />
</head>
<link href="../../../../../Mis Cosas/Mis documentos/Insert/estilos/estilos.css" rel="stylesheet" type="text/css">
<body>
<?php if(!$_POST) { ?>
<h1>Registro</h1>
<form id="form1" name="form1" action="index.php" method="POST">
<p>Nombre:
<input name="nombre" type="name" class="input" placeholder="Nombre">
</p>
<p><BR>Apellido:
<input name="ape" type="text" class="input" placeholder="Apellido">
</p>
<p>Email:
<input name="email" type="email" class="input" placeholder="Email">
</p>
<p>Teléfono:
<input name="tel" type="text" class="input" placeholder="Teléfono">
<BR>
<input name="enviar" type="submit" class="button" value="Enviar">
</p>
</form>
<?php
}else{
$nombre=$_POST['nombre'];
$apellido=$_POST['ape'];
$email=$_POST['email'];
$tel=$_POST['tel'];
$sql = "INSERT INTO clientes(nombre,apellido,email,tel) VALUES('$nombre','$apellido','$email','$tel')";
Mysql_query($sql);
print"Done";
}?>
</body>
</html>

First problem:
Mysql_query($sql); //even though php functions are case-insensitive
^
should be lower case
Second problem: You are not escaping your data, you should use PDO or MySQLi instead. This introduces serious problems to your site like SQL Injection.
I think your problem is this that you are not escaping your variables. You are probably getting an error message like syntax error if any of your input fields contains a quote, but because of your error_reporting it might be displayed within error_log. So either use mysql_real_escape_string($postVariable); or use prepared statements.
Example with PDO:
$nombre = $_POST['nombre'];
$apellido = $_POST['ape'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$sql = "INSERT INTO clientes(nombre, apellido, email, tel)
VALUES(:nombre, :apellido, :email, :tel)";
$stmt = $pdoObj->prepare($sql);
$stmt->bindParam(':nombre', $nombre, \PDO::PARAM_STR);
$stmt->bindParam(':apellido', $apellido, \PDO::PARAM_STR);
$stmt->bindParam(':email', $email, \PDO::PARAM_STR);
$stmt->bindParam(':tel', $tel, \PDO::PARAM_STR);
if ($stmt->execute()) {
echo 'DONE';
}

Related

Submit button don't add data to MySQL

I tried to create a form which will send an email and add data to MySQL data base. For email part because I work on localhost I used formsubmit. All good but there is a conflict. When I press on send only the email is send without any data added to my database. If I delete the action attribute from form data will be added but in this case I can't send any emails. Here is my file:
<?php
require 'config.php';
if(!empty($_SESSION["id"]))
{
$id= $_SESSION["id"];
$result = mysqli_query($conn,"SELECT * FROM tb_user WHERE id= $id");
$row = mysqli_fetch_assoc($result);
}
else
{
header("Location: login.php");
}
if(isset($_POST["submit"]))
{
$name = $_POST['name'];
$email = $_POST['email'];
$cui = $_POST['cui'];
$tip = $_POST['tip'];
$adresa = $_POST['adresa'];
$query = "INSERT INTO beneficiari VALUES('','$email','$name','$cui','$tip','$adresa')";
mysqli_query($conn,$query);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Beneficiari </title>
<link rel="stylesheet" href="indexCSS.css">
<link rel="stylesheet" type="text/css" href="beneficiariCSS.css">
</head>
<body>
<div class="topnav">
Welcome <?php echo $row["name"]; ?>
Logout
<a class="active" href="index.php">Home</a>
Anunturi
Viz
Registration
</div>
<div class="container">
<form action="https://formsubmit.co/0e6b51872b4393271dbfa08bb0655fc8" method="POST">
<h3>Inregistrare</h3>
<input type="text" name="name" id="name" placeholder="Denumire institutie" required>
<input type="email" name="email" id="email" placeholder="Enter an valid email" required>
<input type="text" name="cui" id="cui" placeholder="CUI" required>
<input type="text" name="tip" id="tip" placeholder="Tipul institutie" required>
<input type="text" name="adresa" id="adresa" placeholder="Adresa" required>
<button type="submit" name="submit">Send</button>
</form>
</div>
</body>
</html>
You can remove the action from form, and add it after the SQL query, within the if statement as header, like so:
if(isset($_POST["submit"]))
{
$name = $_POST['name'];
$email = $_POST['email'];
$cui = $_POST['cui'];
$tip = $_POST['tip'];
$adresa = $_POST['adresa'];
$query = "INSERT INTO beneficiari VALUES('','$email','$name','$cui','$tip','$adresa')";
mysqli_query($conn,$query);
header('location: https://formsubmit.co/0e6b51872b4393271dbfa08bb0655fc8');
}
I believe this will work.
But whatever you do make sure you check the input!! The way you are handling your input right now is very dangerous, and allows users to inject you with SQLs (read up on SQL injections and protection)

How to import two values from html to my SQL table

I need to import the values of emailaddress and fullname from html into my SQL table.
Here is my HTML:
<!DOCTYPE html>
<head>
<title>Julian's Newsletter</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link href="newsletter.css" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
</head>
<body>
<h1>Newsletter</h1>
<form action="formsubmit.php" method="post">
<div class="container">
<h2>Subscribe to my Newsletter</h2>
<p>Subscribe to my newsletter to recieve recent news, a specialy curated product list, and the Product of the Month.</p>
</div>
<div class="container" style="background-color:white">
<input type="text" placeholder="Name" name="fullname" required>
<input type="text" placeholder="Email address" name="emailaddress" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Monthly Newsletter
</label>
</div>
<div class="container">
<input type="submit" value="Subscribe">
</div>
</form>
</body>
And here is my PHP so far. I am a beginner and I have very little knowledge of PHP.
<?php
$servername = "localhost";
$emailaddress = "emailaddress";
$fullname = "fullname";
$dbname = "email_windowsisslow_com";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $fullname, $emailaddress);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO emaillist (emailaddress, fullname)
VALUES ('', '')";
// use exec() because no results are returned
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I am new to Stack Overflow and I do not assume that anyone will actually write the code for me. I need help understanding what is written, and how to write the code to perform the action I require of it.
I would suggest you must use prepared statements to avoid SQL injection.
$stmt = $conn->prepare("INSERT INTO emaillist (emailaddress, fullname)
VALUES (:emailaddress , :fullname)");
$stmt->bindParam(':emailaddress ', $emailaddress );
$stmt->bindParam(':fullname ', $fullname );
$stmt->execute();
In your PHP file change the two lines:
$emailaddress = "emailaddress";
$fullname = "fullname";
To
$emailaddress = $_POST["emailaddress"];
$fullname = $_POST["fullname"];
And add to your insert statement
$sql = "INSERT INTO emaillist (emailaddress, fullname) VALUES ({$emailaddress}, {$fullname})";

Simple registration form using html, MySQL and php [duplicate]

This question already has answers here:
Fatal error: Cannot use isset() on the result of an expression
(3 answers)
Closed 6 years ago.
I am creating a simple registration form, I have created all files needed to make complete form registration and login. registration should have Firstname, Lastname, username and password, I have tested with two parameters meaning username and password my codes works perfectly but when I add more parameters eg Firstname and Lastname I get error: Fatal error: Cannot use isset() on the result of an expression
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Registration</title>
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<?php
#include database connection files
require('db.php');
//inserting data to our database
// If form submitted, insert values into the database.
if(!isset($_REQUEST['username'] || $_REQUEST['Firstname'] || $_REQUEST['Lastname'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$Firstname = stripslashes($_REQUEST['Firstname']);
$Firstname = mysqli_real_escape_string($con,$Firstname);
$Lastname = stripslashes($_REQUEST['Lastname']);
$Lastname = mysqli_real_escape_string($con,$Lastname);
$email = stripslashes($_REQUEST['email']);
$email = mysqli_real_escape_string($con,$email);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `users` (username, Firstname, Lastname, password, email, trn_date)
VALUES ('$username',Firstname,Lastname, '".md5($password)."', '$email', '$trn_date')";
$result = mysqli_query($con,$query);
if($result){
echo "<div class='form'>
<h3>You are registered successfully.</h3>
<br/>Click here to <a href='login.php'>Login</a></div>";
}
}
else{
?>
<div class="form">
<h1>Registration</h1>
<form name="registration" action="" method="post">
<input type="text" name="Firstname" placeholder="Firstname" required/>
<input type="text" name="Lastname" placeholder="Lastname" required/>
<input type="text" name="username" placeholder="Username" required />
<input type="email" name="email" placeholder="Email" required />
<input type="password" name="password" placeholder="Password" required />
<input type="submit" name="submit" value="Register" />
</form>
</div>
<?php } ?>
</body>
</html>
Unfortunately, I can't figure it out , what is wrong with my code?
Haven't done PHP in a while, but my guess is that you need to change this:
if(!isset($_REQUEST['username'] || $_REQUEST['Firstname'] || $_REQUEST['Lastname'])){
with this:
if(!isset($_REQUEST['username']) || !isset($_REQUEST['Firstname']) || !isset($_REQUEST['Lastname'])){
actually you probably want the opposite of that, given that you want to only save if all the data is available right?

INSERT with PDO $_POST not working

SOLVED - ANSWER ADDED AT THE BOTTOM OF THE POST
Please can someone help me out as I can´t understand what the heck I am doing wrong.
I have a html form with 2 fields "title" and "message". I´m trying to get this to go into the database with PDO and $_POST but I am just getting this error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null' in
I´m doing everything by the book but it´s not working and I going to throw my computer out the window soon. So please anyone have any idea what is wrong? Why is title turning "NULL"?
The database is a 4 column table (id, title, message and timestamp). The id field is primary and auto intent
ANY help is really appreciated!!! And I´m a beginner...
Here is post.php file:
<?php
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message, time) VALUES (:title, :message, :time)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$stmt->bindParam(':time', $time);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
?>
<!DOCTYPE html>
<html>
<head>
<title>Create blog post</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!--- Add blog post --->
<div class="add_form">
<form id="add_post" method="post" action="post.php" enctype="text/plain">
<fieldset>
<legend>Create post</legend>
<label for="post_title">Title:
<input id="title" type="text" name="title" value="<?php if (isset($title)) { echo htmlentities ($title); } ?>" >
</label>
<label for="message">Message:
<textarea id="message" name="message" rows="20" cols="30" maxlength="50" value="<?php if (isset($message)) { echo htmlentities ($message); } ?>" ></textarea>
</label>
</fieldset>
<input id="send" type="submit" value="Send">
</form>
</div>
</body>
</html>
And here is the connect.inc.php file:
<?php
class DB extends PDO
{
public function __construct($dbname = "blogdata")
{
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = "mysql:host=localhost;dbname=$dbname;charset=utf8";
parent::__construct($dsn, "root", "", $opt);
}
}
?>
ANSWER:
This issue was finally solved. The problem is you need to check if $_POST is empty or not. And right after the if (!empty($_POST)) { set the require 'connect.inc.php';. Also to minimize code do like Dave Just said, change :
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
To:
$stmt->execute(array(':title' => $_POST['title'], ':message' => $_POST['message']));
Here is the working code in post.php:
<?php
if (!empty($_POST)) {
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message) VALUES (:title, :message)");
$stmt->execute(array(':title' => $_POST['title'], ':message' => $_POST['message']));
$title = $_POST['title'];
$message = $_POST['message'];
// Redirect to index.php
header ('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create blog post</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!--- Add blog post --->
<div class="add_form">
<form id="add_post" method="post">
<fieldset>
<legend>Create post</legend>
<label for="post_title">Title:
<input id="title" type="text" name="title" value="<?php if (isset($title)) { echo htmlentities ($title); } ?>" >
</label>
<label for="message">Message:
<textarea id="message" name="message" rows="20" cols="30" maxlength="50" value="<?php if (isset($message)) { echo htmlentities ($message); } ?>" ></textarea>
</label>
</fieldset>
<input id="send" type="submit" value="Send">
</form>
</div>
</body>
</html>
If you haven't thrown the computer out the window already, you should've checked whether $_POST vars were set or not before passing them to a PDO execute statement.
<?php
require 'connect.inc.php';
if( isset($_POST['title'], $_POST['message']) ) {
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message, time) VALUES (:title, :message, :time)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$stmt->bindParam(':time', $time);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
}
?>
PS
I have no idea what $time would do there.

PDO insert with $_POST?

I am trying to insert data from a simple html form with $_POST into the database with PHP and PDO. I am not getting any errors, there is just nothing going into the database. If I type the values manually in the code it works but nothing happens when typing into the html form. At some point I had "Array" typed out.
UPDATE:
The error I am getting is:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null' in ...
Why is Column title null?
The database is just a table with 4 fields (id, title, message and time/timestamp field.
The id field is primary AI and the timestamp field is picking up the time automatically.
Here is the connect.inc.php file:
<?php
class DB extends PDO
{
public function __construct($dbname = "blogdata")
{
try {
parent::__construct("mysql:host=localhost;dbname=$dbname;charset=utf8",
"root", "");
} catch (Exception $e) {
var_dump($e);
}
}
}
?>
And here is the post.php file:
<?php
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message, time) VALUES (:title, :message, :time)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$stmt->bindParam(':time', $time);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
?>
<!DOCTYPE html>
<html>
<head>
<title>Create blog post</title>
<meta charset="utf-8" />
</head>
<body>
<!--- Add blog post --->
<div class="add_form">
<form id="add_post" method="post" action="index.php" enctype="text/plain">
<fieldset>
<legend>Create post</legend>
<label for="post_title">Title:
<input id="title" type="text" name="title" value="<?php if (isset($title)) { echo htmlentities ($title); } ?>" >
</label>
<label for="message">Message:
<textarea id="message" name="message" rows="20" cols="30" maxlength="50" value="<?php if (isset($message)) { echo htmlentities ($message); } ?>" ></textarea>
</label>
</fieldset>
<input id="send" type="submit" value="Send">
</form>
</div>
</body>
</html>
ANSWER
You need to wrap everything up and check if $_POST is not empty. Also the problem was action="index.php" in the form. It needed to be set to post.php.
Here is the correct code in post.php:
<?php
if (!empty($_POST)) {
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message) VALUES (:title, :message)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
header ('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Create blog post</title>
<meta charset="utf-8" />
<link rel="stylesheet" href="reset.css" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<!--- Add blog post --->
<div class="add_form">
<form id="add_post" method="post" action="post.php">
<fieldset>
<legend>Create post</legend>
<label for="post_title">Title:
<input id="title" type="text" name="title" value="<?php if (isset($title)) { echo htmlentities ($title); } ?>" >
</label>
<label for="message">Message:
<textarea id="message" name="message" rows="20" cols="30" maxlength="50" value="<?php if (isset($message)) { echo htmlentities ($message); } ?>" ></textarea>
</label>
</fieldset>
<input id="send" type="submit" value="Send">
</form>
</div>
</body>
</html>
Here is the proper connect.inc.php file:
<?php
class DB extends PDO
{
public function __construct($dbname = "blogdata")
{
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
$dsn = "mysql:host=localhost;dbname=$dbname;charset=utf8";
parent::__construct($dsn, "root", "", $opt);
}
}
Dunno if it caused error but
And here is the post.php file:
<form id="add_post" method="post" action="index.php"
Anyway, the real cause of the problem is similar to that. Some silly typo somewhere
Awser for your last comment :
#Corum Hi, I´m calling index.php in the form because index.php are
displaying all the posts and after sending the form the user should be
directed to index.php and be able to see the results... I really can´t
seem to solve this:(
If you call index.php with <form action="index.php"> your form data will never be processed.
You have to call post.php instead and after redirect to index.php.
Corrected code (replace top PHP block in your file post.php) :
<?php
if (!empty($_POST) {
// Only process if form is submitted (when page is launched, it use GET method)
require 'connect.inc.php';
$db = new DB('blogdata');
$stmt = $db->prepare("INSERT INTO blogposts (title, message, time) VALUES (:title, :message, :time)");
$stmt->bindParam(':title', $_POST['title']);
$stmt->bindParam(':message', $_POST['message']);
$stmt->bindParam(':time', $time);
$title = $_POST['title'];
$message = $_POST['message'];
$stmt->execute();
// Redirect to index.php
header('Location : index.php');
exit;
}
?>
And change your html form for : <form action="post.php" ...>

Categories