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.
Related
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})";
I have created a form in html and I would like that the dataentered in the form is sent to a mysql database in XAMMP. I created the database, the table and the connectivity.php file that manages the connection to the database and data entry, but when I try I get the following error:
"Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\example\connectivity.php:8 Stack trace: #0 {main} thrown in C:\xampp\htdocs\example\connectivity.php on line 8"
I post all the code that I wrote. Does anyone know where I'm wrong?
here is the form index.html
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" type="text/css" href="style.css">
<?php include("connectivity.php"); ?>
</head>
<body>
<div id="contact">
<h3>Contact Us For Any Query</h3>
<form method="POST" action="connectivity.php">
Name
<br>
<input type="text" name="name">
<br> Email
<br>
<input type="text" name="email">
<br> Message
<br>
<textarea rows="10" cols="50" maxlength="100" name="message"></textarea>
<br>
<input type="submit" value="Send Message">
</form>
</div>
</body>
</html>
Then the code used to define database and the table:
CREATE DATABASE practice;
USE practice;
CREATE TABLE contact
(
contactID INT(9) NOT NULL auto_increment,
contactName VARCHAR(40) NOT NULL,
contactEmail VARCHAR(40) NOT NULL,
message VARCHAR(250) NOT NULL,
PRIMARY KEY(contactID)
);
Finally the connectivity.php file:
<?php
//connecting to the database
define('DB_HOST', 'localhost');
define('DB_NAME', 'practice');
define('DB_USER','root');
define('DB_PASSWORD','');
$con=mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
//inserting Record to the database
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$query = "INSERT INTO contact(contactName,contactEmail,message)VALUES('$name','$email','$message')";
$result = mysql_query($query);
if($result)
{
echo "Successfully updated database";
}
else
{
die('Error: '.mysql_error($con));
}
mysql_close($con);
?>
P.S: I installed the latest version of XAMMP (5.6.15)
$con=mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD,##TABLE NAME##) or die("Failed to connect to MySQL: " . mysql_error());
$query = "INSERT INTO contact(contactName,contactEmail,message)VALUES('$name','$email','$message')";
$result = mysqli_query($con,$query);
If you are using one of the latest version of xampp therefore you have to use PDO or MySQLi .
Your have to change your codes to something like this.
Your connectivity page
<?php
$db = new PDO('mysql:host=localhost;dbname=practice;charset=utf8',
'root',
'',
array(PDO::ATTR_EMULATE_PREPARES => false,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
?>
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$stmt = $db->prepare("INSERT INTO `contact` (contactName,contactEmail,message)
VALUES (:name, :email, :message)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':email', $email);
$stmt->bindParam(':message', $message);
$stmt->execute();
echo 'added';
}
?>
Your home page
<!DOCTYPE HTML>
<html>
<head>
<title>Contact Us</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="contact">
<h3>Contact Us For Any Query</h3>
<form method="POST" action="connectivity.php">
Name
<br>
<input type="text" name="name">
<br> Email
<br>
<input type="text" name="email">
<br> Message
<br>
<textarea rows="10" cols="50" maxlength="100" name="message"></textarea>
<br>
<input type="submit" value="Send Message">
</form>
</div>
</body>
</html>
Hope this helps
Firts you see your phpinfo:
<?php
phpinfo();
?>
Then see in here , php_mysql is enabled or disabled?
If there not php_mysql, change php.ini file:
Uncomment extension=php_mysql.dll
First here is my code:
database.php (established connection so I can use with require)
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$port = 8889;
$database = "oopdb";
try{
$conn = new PDO("mysql:host=$servername; dbname=$database; port=$port", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->exec("SET NAMES 'utf8'");
}catch(Exception $e){
echo "Error: " . $e->getMessage();
exit;
}
?>
Then my main PHP file with the form:
<!DOCTYPE html>
<html>
<head>
<title>Forms with PDO</title>
</head>
<body>
<?php
require("database.php");
if(isset($_POST['submit'])){
//trying to insert data into the database
try{
// prepare and bind
$stmt = $conn->prepare("INSERT INTO clients (phonenumber, firstname, lastname, address, note) VALUES (?, ?, ?, ?, ?)");
$stmt->bind_param('sssss', $phonenumber, $firstname, $lastname, $address, $note);
// set parameters and execute
$phonenumber = $_POST['number'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$address = $_POST['address'];
$note = $_POST['note'];
$stmt->execute();
}catch (Exception $e) {
echo "Data could not be retrieved from the database.";
exit;
}
}
?>
<h2>The Form</h2>
<hr />
<br />
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="POST">
Number: <input type="text" name="number" value="" />
<br /><br />
First Name: <input type="text" name="firstname" value="" />
<br /><br />
Last Name: <input type="text" name="lastname" value="" />
<br /><br />
Address: <input type="text" name="address" value="" />
<br /><br />
Notes: <input type="text" name="notes" value="" />
<br /><br />
<input type="submit" name="submit" value="Submit">
</form>
<br />
<hr />
</body>
</html>
So now for some reason I am not able to insert the data from the form into my database when I click submit. I keep getting this error:
Fatal error: Call to undefined method PDOStatement::bind_param() in /Users/lucasantos/Sites/oop_testing/stack.php on line 19
I have seen multiple ways of using bind_param and inserting data into the database. This method in specific I got from W3schools HERE
I have went over the entire code multiple times, tried many times and still not working. I even looked at the bind_param documentation and I believe I am using it correctly. Someone please help.
Some additional information:
- I am doing this on local host through MAMP if that matters.
- I also have a column for the id of the row but I did not include it because it is set to auto increment.
Thank you!
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';
}
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" ...>