I am trying to insert into my table (courses) in my sql database. But when I run my code (by clicking submit) I get this error:
I am no longer getting an error, I get the message:
New course created successfully
But when I check the database, the course has not been added
This is my code:
<?php
if (isset($_POST['submit'])) {
try {
require "../config.php";
require "../common.php";
$connection = new PDO($dsn, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO course (courseName, cDescription, programID, programYear, credit)
VALUES (:courseName, :cDescription, :programID, :programYear, :credit)";
$courseName = $_POST['courseName'];
$cDescription = $_POST['cDescription'];
$programID = $_POST['programID'];
$programYear = $_POST['programYear'];
$credit = $_POST['credit'];
$statement = $connection->prepare($sql);
$statement->bindParam(':courseName', $courseName, PDO::PARAM_STR);
$statement->bindParam(':cDescription', $cDescription, PDO::PARAM_STR);
$statement->bindParam(':programID', $programID, PDO::PARAM_STR);
$statement->bindParam(':programYear', $programYear, PDO::PARAM_STR);
$statement->bindParam(':credit', $credit, PDO::PARAM_STR);
$connection->exec($statement);
echo "New course created successfully";
} catch(PDOException $error) {
echo $statement. "<br>" . $error->getMessage();
}
}
?>
<?php include "templates/header.php"; ?>
<h2>Add a course</h2>
<form method="post">
<label for="courseName">Course Name:</label>
<input type="text" name="courseName" id="courseName" required>
<label for="cDescription">Course Description:</label>
<input type="text" name="cDescription" id="cDescription" size="40" required>
<label for="programID">Program ID:</label>
<input type="number" name="programID" id="programID" required>
<label for="programYear">Program Year:</label>
<input type="number" name="programYear" id="programYear" required>
<label for="credit">credit:</label>
<input type="number" name="credit" id="credit" required>
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
To try and see what was wrong, I tried simplifying this to, which works
<?php
if (isset($_POST['submit'])) {
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "courseselector";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO course (courseName, cDescription, programID, programYear, credit)
VALUES ('courseName', 'cDescription', 1, 4, 1)";
// 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;
}
?>
<?php include "templates/header.php"; ?>
<h2>Add a course</h2>
<form method="post">
<input type="submit" name="submit" value="Submit">
</form>
Back to home
<?php include "templates/footer.php"; ?>
I was missing
$statement->execute();
Above
$connection->exec($statement);
Related
I am trying to pinpoint the problem in these form scripts.
I would like to create a line in the SQL server with the data that will be inserted into the HTML form, but each time only the empty line is created without also inserting the form inputs.
HTML
<form action="insert2.php" method="post">
<label for="First_name">First_name:</label>
<input type="text" name="First_name" id="First_name">
<label for="PASSWORD">PASSWORD:</label>
<input type="text" name=value name="pass" id="pass">
<label for="Emailaddress">Emailaddress:</label>
<input type="text" name=value name="email" id="email">
<input name="submit" type="submit" value="Submit">
</form>
PHP
<?php
if(isset($_POST['submit'])){
$First_name = $_REQUEST['First_name'];
$pass = $_REQUEST['password'];
$email = $_REQUEST['Emailaddress'];
}
$servername = "host";
$username = "user";
$password = "";
$dbname = "dbname";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(First_name, PASSWORD, Emailaddress)
VALUES ('$First_name', '$pass', '$email')";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
The posted values should be set as $_POST['ExampleField'] not just a variable with that name.
Ex: $First_name should be $_POST['First_name']
If you look in your error logs you are likely getting undefined variable errors with the code as it is now, because $First_name, $PASSWORD and $Emailaddress are never defined.
Also you should avoid directly putting variables into queries like that, it opens you up to large security risks. I would recommend reading up on SQL Injection (https://www.w3schools.com/sql/sql_injection.asp) and binding parameters (https://www.php.net/manual/en/pdostatement.bindparam.php) to see how to avoid those risks.
You need to retrieve the values after a submit of some sort. You have a submit button but you'll want to give it a name (I named it submit). This code should work but you'll be vulnerable to injection attacks.
PHP
<?php
if(isset($_POST['submit'])){
$First_name = $_REQUEST['First_name'];
$pass = $_REQUEST['PASSWORD'];
$email = $_REQUEST['Emailaddress'];
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO users(First_name, PASSWORD, Emailaddress)
VALUES('$First_name','$pass','$email')";
$conn->exec($sql);
echo "New record created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
HTML
<form action="insert2.php" method="post">
<label for="First_name">First_name:</label>
<input type="text" name="First_name" id="First_name">
<label for="PASSWORD">PASSWORD:</label>
<input type="text" name="PASSWORD" id="PASSWORD">
<label for="Emailaddress">Emailaddress:</label>
<input type="text" name="Emailaddress" id="Emailaddress">
<input name="submit" type="submit" value="Submit">
</form>
I want to do simple CRUD operations. I created a form for this and I am doing data entry. but when I refresh the page it automatically registers itself. I tried to solve this logic error with the "isset" function, but it did not. where can the error be?
$ad = isset($_POST['ad']) ? $_POST['ad'] : '';
$soyad = isset($_POST['soyad']) ? $_POST['soyad'] : '';
$adres = isset($_POST['adres']) ? $_POST['adres'] : '';
$tur = isset($_POST['tur']) ? $_POST['tur'] : '';
if(isset($_POST["submit"])){
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// bağlantı özelliklerinden hata modunu aktifleştirdik
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO `kisiler` (`ad`, `soyad`, `adres`, `tur`) VALUES ('$ad', '$soyad', '$adres', '$tur')";
// use exec() because no results are returned
$conn->exec($sql);
echo "işte şimdi oldu";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
<html>
<body>
<form action="" method="POST">
<p>
Ad: <input type="text" name="ad"/>
Soyad: <input type="text" name="soyad"/>
Adres:<input type="text" name="adres"/>
Tur: <input type="text" name="tur"/>
<input type="submit"name="submit"/>
</p>
</form>
</body>
<div class = "login">
<?php
$lusername=$_POST['lusername'];
$lpassword=$_POST['lpassword'];
$mysql = new mysqli("localhost", "root", null, "webdb");
$stmt = $mysql ->prepare("select username, password from webdb.user where username=?");
$stmt->bind_param("s", $lusername);
$stmt->execute();
$stmt->bind_result($u, $p);
$stmt->fetch();
$stmt->close();
$mysql->close();
if($lusername == $u && $lpassword == $p) {
echo "the log in is successful";
}
else {
echo "<b><font color='red'>Login unsuccessful. Please go back and try again </font></b>";
}
?>
<form action="sign in.php" method="post">
<div class = "details">
<br>
 <input type="text" name="lusername" placeholder="Username" required>
<br>
<br>
<br>
<input type="password" name="lpassword" placeholder ="Password" required>
</div>
<div class = "enter">
<br>
<br>
<input type="submit" name="submit" value="Enter">
</div>
I've been working on my login page for a day but I cannot seem to find the error in my codes. Currently, when I click on login, it automatically activates the if statement "the log in is successful" without even having to key in the username and password.
<div class = "login">
<?php
if(isset($_POST['submit'])){
$lusername=$_POST['lusername'];
$lpassword=$_POST['lpassword'];
$mysql = new mysqli("localhost", "root",'', "webdb");
$stmt = $mysql ->prepare("select username, password from webdb.user where username=?");
$stmt->bind_param("s", $lusername);
$stmt->execute();
$stmt->bind_result($u, $p);
$stmt->fetch();
$stmt->close();
$mysql->close();
if($lusername == $u && $lpassword == $p) {
echo "the log in is successful";
}
else {
echo "<b><font color='red'>Login unsuccessful. Please go back and try again </font></b>";
}
}
?>
<form action="sign in.php" method="post">
<div class = "details">
<br>
 <input type="text" name="lusername" placeholder="Username" required>
<br>
<br>
<br>
<input type="password" name="lpassword" placeholder ="Password" required>
</div>
<div class = "enter">
<br>
<br>
<input type="submit" name="submit" value="Enter">
</div>
try this as you are first checking the GET request, and it will always give the login successful, for that you need to check whether the submit button has been pressed, and remove the null from the database password as for blank password you keep '' and not null
1st : use isset to avoid undefined index error on page load for the first time .
if(isset($_POST['submit'])){ //all you php code here }
2nd : Don't save the password as plain text in database .Try to use password_hash() and password_verify()
3rd : On the error debugging mode. On top of page add these two lines
ini_set('display_errors','On'); ini_set('error_reporting', E_ALL);
1) Do no store password as a plain text use password_hash() to store it correclty. And use password_verify() to verify if the password is correct. Link: http://www.phptherightway.com/#password_hashing. I hope it is not a live app.
2)Use this to escape : htmlentities( $slusername, ENT_QUOTES | ENT_HTML5, $encoding = 'UTF-8' )
--------------------SOLUTION-------------------------------------------
The problem is that you don't submit the data with if ( $_SERVER['REQUEST_METHOD'] == "POST" ) and sign in.php should be sign_in.php. There is a space. AND REMOVE THE NULL on your mysqli database put ''.
2)In your your sign_in.php. Use this code.
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
try {
$conn = new PDO("mysql:host=$servername;dbname=webdb", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
/*if submission button */
if ( $_SERVER['REQUEST_METHOD'] == "POST" ) {
/*There is no protection here*/
/*use $lusername=$htmlentities( $slusername, ENT_QUOTES |
ENT_HTML5, $encoding = 'UTF-8' );*/
$lusername=$_POST['lusername'];
$lpassword=$_POST['lpassword'];
/*Query*/
$query = 'SELECT password, username FROM user WHERE username
=:username';
$stmt = $conn->prepare($query);
$stmt -> bindParam(':username', $lusername);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt->execute();
$stmt->CloseCursor();
/*Arranging query*/
function returnArray( $rows, $string )
{
foreach( $rows as $row )
{
return $row[ $string ];
}
}
/*Verification of the user*/
if( returnArray( $rows, 'password') == $lpassword)
{
echo "the log in is successful";
}
else
{
echo "<b><font color='red'>Login unsuccessful. Please
go back and try again </font></b>";
}
}
?>
In your login.php
<div class = "login">
<form action="sign_in.php" method="post">
<div class = "details">
<br>
 <input type="text" name="lusername"
placeholder="Username" required>
<br>
<br>
<br>
<input type="password" name="lpassword" placeholder
="Password" required>
</div>
<div class = "enter">
<br>
<br>
<input type="submit" name="submit" value="Enter">
</div>
</form>
</div>
I have this PHP that basically is being used for inserting an email and password into an SQL database:
<?php
error_reporting(E_ALL ^ E_STRICT);
require "database.php";
$message = '';
if (!empty($_POST["email"]) &&!empty($_POST["password"])):
//Enter the new user in the database
$sql = "INSERT INTO users (email, password) VALUES (:email, :password)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":email", $_POST['email']);
$stmt->bindParam(":password", password_hash($_POST['password'], PASSWORD_BCRYPT));
if ($stmt->execute() ):
$message = 'Successfully created a new user';
else:
$message = 'Sorry there must have been an issue whilst registering';
endif;
endif;
?>
Here is the form:
<div class="jumbotron" id="jumbotron-6">
<div class="container text-center">
<?php if (!empty($message)):
?>
<h3 id="h3message"><?= $message ?> </h3>
<?php endif; ?>
<form action="signup.php" method="POST">
<input type="text" placeholder="enter your email" name="email">
<input type="password" placeholder="and password" name="password">
<input type="password" placeholder="confirm password" name="confirm_password">
<input type="submit">
</form>
</div>
</div>
It doesn't insert into the database (all the fields, variables are correct i think - just email and password) and it comes back with the error message that I created that says 'Sorry there must have been an issue whilst registering'
Here is the database.php file
<?php
$server = 'localhost';
$username = "root";
$password = "";
$database = "auth";
try{
$conn = new PDO ("mysql:host={$server};dbname={$database};" , $username, $password);
}
catch (PDOException $e) {
die ( "Connection failed; " . $e->getMessage());
}
?>
Hash the password before you bind it:
$UserPWHash = password_hash($_POST['password'], PASSWORD_BCRYPT);
$stmt->bindParam(":password", $UserPWHash));
I have a form (add_company_form.php) in my submit_form_company.php that takes the values from POST and sends them to mysql trough a pdo connection. But I cant get my validation.php to validate the input. I want the user to stay on the same page which is why I dont have a action in the form. The code itself is not complete and there is alot of improvements that can be done, but Im stuck on the validation for now.. Am I on the right track by adding the validation.php before like my db.php?
Submit_form_company.php
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
try {
include('db.php');
include('validation.php');
if(empty($_SESSION["error_message"]) && $_POST['submit_company']) {
$STH = $conn->prepare("
INSERT INTO companies (Name,Notes,OrganizationNumber)
VALUES (:Name,:Notes,:OrganizationNumber)");
$STH->bindParam(':Name', $_POST['Name'], PDO::PARAM_STR);
$STH->bindParam(':Notes', $_POST['Notes'], PDO::PARAM_STR);
$STH->bindParam(':OrganizationNumber', $_POST['OrganizationNumber'], PDO::PARAM_INT);
$STH->execute();
} elseif ($_SESSION["error_message"] && $_POST['submit_edit']) {
foreach ($_POST['company'] as $i => $value) {
$STH = $conn->prepare("
UPDATE companies
SET Name = :Name,Notes = :Notes,OrganizationNumber = :OrganizationNumber
WHERE Id = :Id");
$STH->bindParam(':Id', $value['Id'], PDO::PARAM_INT);
$STH->bindParam(':Name', $value['Name'], PDO::PARAM_STR);
$STH->bindParam(':Notes', $value['Notes'], PDO::PARAM_STR);
$STH->bindParam(':OrganizationNumber', $value['OrganizationNumber'], PDO::PARAM_INT);
$STH->execute();
}
}
if(empty($_SESSION["error_message"])){
echo "<meta http-equiv='refresh' content='0'>";
}
}
catch (PDOException $e) {
echo $e->getMessage();
}
}
require("add_company_form.php");
$DBH = null;
?>
add_company_form.php
<div class="row">
<form class="col-md-4 navbar-form" method="POST" action="" enctype="multipart/form-data">
<div class="form-group">
<label class="sr-only" for="Name">Name:</label> <input type="text" class="form-control" name="Name" placeholder="Name"><br />
<label class="sr-only" for="Notes">Notes:</label> <input type="text" class="form-control" name="Notes" placeholder="Notes"><br />
<label class="sr-only" for="OrganizationNumber">OrganizationNumber:</label> <input type="text" class="form-control" name="OrganizationNumber" placeholder="OrganizationNumber"><br />
<input type="submit" name="submit_company" class="btn btn-default" value="Submit">
</div>
</form>
<?php
if(!empty($_SESSION["error_message"])){
echo'<div id="error_message" class="col-md-8">';
print_alert_error($_SESSION["error_message"]);
$_SESSION["error_message"] = "";
echo'</div>';
} ?>-
Validation.php
<?
$error = "";
if(isset($_POST['submit_company'])) {
$name = $_POST['Name'];
$notes = $_POST['Notes'];
$organization_number = $_POST['OrganizationNumber'];
if (!ctype_alpha(str_replace(array("'", "-"), "",$name))) {
$error .= '<p class="error">Name should be alpha characters only.</p>';
}
}
//Add error message to session
if (!empty($error)){
$_SESSION["error_message"] = $error;
}
?>
DB.php
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "test";
$conn = new PDO("mysql:host=$servername;dbname=$dbname;charset=utf8", $username, $password,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
?>
A silly suggestion but try using the full <?php opening tag in your validation.php file.