I am trying to save a form data into my database but I get just empty records.
I tryied many solutions but I really don't know where's the bug. I am getting crazy!
This is my form:
<head>
<form action="uploadall.php" method="post">
Name: <input type="text" name="name"><br>
Autore: <input type="text" name="author"><br>
Descrizione: <textarea id="editordescription" name="description" cols="45" rows="15">
</textarea>
<script>
CKEDITOR.replace( 'editordescription' );
</script>
<br>Misure: <input type="text" name="misure"><br>
Data: <input type="text" name="date"><br>
<input type="hidden" name="status" value="Disattivo" size="20">
<input type="submit">
</form>
And this is my PHP script to save records:
<?php
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysqli_real_escape_string(htmlspecialchars($_POST['name']));
$author = mysqli_real_escape_string(htmlspecialchars($_POST['author']));
$description = mysqli_real_escape_string(htmlspecialchars($_POST['description']));
$misure = mysqli_real_escape_string(htmlspecialchars($_POST['misure']));
$date = mysqli_real_escape_string(htmlspecialchars($_POST['date']));
$status = mysqli_real_escape_string(htmlspecialchars($_POST['status']));
}
$servername = "xxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxxx";
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 exposition (name, author, description, misure, date, status)
VALUES ('$name', '$author', '$description', '$misure', '$date', '$status')";
// 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;
?>
And this is what I get in my database at the moment:
First, you are mixing the mysql api's at somepoint you are using mysqli_* at some point u using mysql_* They don't mix. And mysql_* functions are depreciated they no longer supported by later versions of php. better use mysqli or pdo. this mysql_real_escape_string() or mysqlo_real_escape_string() is not safe enough to prevent you against sql injections. solution is simple better start using mysqli prepared statements or pdo prepared statements.
another error : <input type="text" name="name"> <input type="text" name="name"> these two inputs fields have the same name attribute php will only read one. and you will get an undefined index here $misure = $_POST['misure']; You need to activate error reporting while you are still developing so you can see your errors and notices:
add this at the top of every php page : ini_set('display_errors', 1);
error_reporting(E_ALL);
also date date is a reserved word for mysql so you better use something else for your column name or add backslashes date
Oh and your code never execute here :
if (isset($_POST['submit']))
{
// get form data, making sure it is valid
$name = mysql_real_escape_string(htmlspecialchars($_POST['name']));
$author = mysql_real_escape_string(htmlspecialchars($_POST['author']));
$description = mysql_real_escape_string(htmlspecialchars($_POST['description']));
$misure = mysql_real_escape_string(htmlspecialchars($_POST['misure']));
$date = mysql_real_escape_string(htmlspecialchars($_POST['date']));
$status = mysql_real_escape_string(htmlspecialchars($_POST['status']));
}
Why is that? because you do not have POST value with the submit attribute name. <input type="submit"> see? your submit does not have a name attribute. therefore. This means
all this :
VALUES ('$name', '$author', '$description', '$misure', '$date', '$status')"; These are all undefined variables. I'm surprised why doesn't your server tell you that, with that error reporting enable you will get all those.
This is what u need to do to solve that :
Your html side.
<form action="uploadall.php" method="post">
Name: <input type="text" name="name"><br>
Autore: <input type="text" name="author"><br>
Descrizione: <textarea id="editordescription" name="description" cols="45" rows="15">
</textarea>
<script>
CKEDITOR.replace( 'editordescription' );
</script>
<br>Misure: <input type="text" name="misure"><br>
Data: <input type="text" name="date"><br>
<input type="hidden" name="status" value="Disattivo" size="20">
<input type="submit" name="submit">
</form>
uploadall.php
<?php
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
$servername = "xxxxxxx";
$username = "xxxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//check your inputs are set and validate,filter and sanitize
$name = $_POST['name'];
$author = $_POST['author'];
$description = $_POST['description'];
$misure = $_POST['misure'];
$date = $_POST['date'];
$status = $_POST['status'];
//prepare and bind
$sql = $conn->prepare("INSERT INTO exposition (name, author, description, misure, date, status)
VALUES (?,?,?,?,?,?)");
$sql->bind_param("ssssss", $name, $author, $description, $misure, $date);
if ($sql->execute()) {
echo "New record created successfully";
} else {
//you have an error
}
$conn->close();
}
?>
That's all good luck.
Update :
I corrected errors you told me and I am using PDO now but it still
doesn't work
I read that from your comments above, but you not telling us what the errors are, but I believe they are the ones I highlighted above.
with PDO this is how u will achieve your goal :
<?php
//connection
$servername = 'XXXXXXXXXXXXX';
$dbname = 'XXXXXXXXXXXXX';
$username = 'XXXXXXXXXXXXXX';
$password = 'XXXXXXXXX';
$charset = 'utf8';
$dsn = "mysql:host=$servername;dbname=$dbname;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $username, $password, $opt);
// check if the form has been submitted. If it has, start to process the form and save it to the database
if (isset($_POST['submit'])) {
//check your inputs are set and validate,filter and sanitize
$name = $_POST['name'];
$author = $_POST['author'];
$description = $_POST['description'];
$misure = $_POST['misure'];
$date = $_POST['date'];
$status = $_POST['status'];
//prepare and bind
$stmt = $dbh->prepare("INSERT INTO exposition (name, author, description, misure, date, status)VALUES (?,?,?,?,?,?)");
if ($stmt->execute(array($name,$author,$description,$misure,$date,$status))) {
echo "New Record inserted success";
}
}
?>
Variable name problem E.g
Name: <input name="name">
and :
Misure: <input name="name">.This must be different.
Again, <input type="submit"> should be <input type="submit" name="submit">.
Hope, it will be helpful.
The variables you are using inside your INSERT Query are out of scope from the first if block where you are getting the data from your form. If the variables are initialized before the first if block it might work. like below..
$name = ""; $author = "";$description = "";$misure = "";$date = "";$status=";
if (isset($_POST['submit'])){ // as is}
Related
I have a form field for an update - where I have given the administrators the ability to make changes to comments:
<form method="post" action="form_action.php?job_numb=<?=$job_numb;?>" enctype="multipart/form-data">
<textarea class="form-control"
rows="10"
name="comments"
maxlength="5000">
<!--This is grabbing the previous $comments from the database-->
<?php echo html_entity_decode($comments);?>
</textarea>
</form>
I was wondering why text seemed truncated or cut-off, thinking it had to do with character limit it did not. How do you make sure the special characters don't stop the SQL from breaking?
The SQL row is set to text.
I have since learned that I just needed prepared statements, and that "cleaning" the data was not necessary at all.
See code below
<?php
$servername = "localhost";
$username = "XXXXX";
$password = "XXXXX";
try {
$conn = new PDO("mysql:host=$servername;dbname=**YOURDATABASE**", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
if(isset($_POST['submit']) && !empty($_POST['submit'])) {
$job_name = htmlspecialchars($_POST['job_name'], ENT_QUOTES, 'UTF-8');
$comments = htmlspecialchars($_POST['comments'], ENT_QUOTES, 'UTF-8');
}
$conn->exec($sql);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
$conn = null;
$sql = "UPDATE `jobs_canjobs` SET
`job_name`='$job_name',
`comments`='$comments'
WHERE job_numb = '$job_numb'";
?>
There is no need for a second variable, and although the previous method worked - it was just an extra step.
I am new to PHP and trying to learn OOP PHP.
I am creating a registration form (a simple one) to learn OOP PHP, when I submit data the success message shows up but data is not inserted in data base.
Below is my code:
connection.php
<?php
class DBConnection extends PDO
{
public function __construct()
{
$host='mysql:host=localhost;dbname=OOP';
$user='root';
$password='';
parent::__construct($host,$user,$password);
$this->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// always disable emulated prepared statement when using the MySQL driver
$this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
}
?>
Index.php
<?php
session_start();
/*include 'classes.php';
//$dbHandle = new DBConnection();
$ins=new basic_operation();
$ins->Insert_Data();*/
?>
<div class="col-lg-12">
<div class="col-lg-1"></div>
<div class="col-lg-7">
<form action="user_data.php" method="post" >
<input type="text" name="username" id="username" class="form-control"><br>
<input type="email" name="email" id="email" class="form-control"><br>
<input type="password" name="password" class="form-control" id="password"><br>
<input type="submit" name="submit" id="submit" value="submit">
</form>
</div>
</div>
<div>
<?php if (isset($_SESSION['insert']))
{
echo $_SESSION['insert'];
unset($_SESSION['insert']);
}
?></div>
</div>
</div>
User_data.php
<?php
session_start();
include 'classes.php';
$insert=new basic_operation();
$usr=$insert->Insert_Data();
//return $insert;
$_SESSION['insert']='data inserted successfuly';
header('location:index.php');
?>
Classes.php
<?php
include 'connection.php';
class basic_operation
{
public function Insert_Data()
{
if (isset($_POST['submit'])) {
$user = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['password'];
$smt = new DBConnection();
$qry = $smt->prepare("insert into student(User_Name,Email,Password) VALUES ('" . $user . "','" . $email . "','" . $pass . "')");
$qry->execute();
}
}
}
?>
If any one knows how to perform basic CRUD (insert, update, delete, select) operation in PHP using OOP PHP and PDO Then please provide the link, source, Example, so i can learn from it
I searched on the internet but bearly able to find the connection code... Looking for a descriptive answer, as I think this question will also help a lot of people who try/want to learn OOP PHP.
Any help will appreciated.
Use try-catch in your connection script to get errors.
try {
$pdo = new PDO(
'mysql:host=localhost;port=3306;dbname=your_db;charset=utf8mb4',
'user',
'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4")
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Database connection has failed. Contact system administrator to resolve this issue!<br>';
$e->getMessage();
die();
}
Enable error reporting in php (add this on top of your php script).
error_reporting(E_ALL);
Since you want to use prepared statements then you will have to bind your parameters in order to get escaped properly.
$qry = $smt->prepare("INSERT INTO `student` (`User_Name`,`Email`,`Password`)
VALUES (:user,:email,:pass);");
$qry->bindParam(':user', $user, PDO::PARAM_STR, 255);
$qry->bindParam(':email', $email, PDO::PARAM_STR, 255);
$qry->bindParam(':pass', $pass, PDO::PARAM_STR, 255);
$qry->execute();
Prepared statements with bound parameters are not only more portable,
more convenient, immune to SQL injection, but are often much faster to
execute than interpolated queries, as both the server and client side
can cache a compiled form of the query.
source: Description of PDO::quote in php.net
And last but not least... Always use backticks “`” in your MySQL queries to properly quote MySQL Keywords and Reserved Words such as PASSWORD. You use it in your query as a field but you don't quote it.
Actually the code is working fine, when i try to run it directly using localhost without using phpstorm then it works.. mean the issue is in my IDE.
Thanks for your efforts.
`if (isset($_POST['submit'])) {
$user = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['password'];
$smt = new DBConnection();
$qry = $smt->prepare("insert into student(User_Name,Email,Password) VALUES ('" . $user . "','" . $email . "','" . $pass . "')");
$qry->execute();
}`
Try this
if (isset($_POST['submit'])) {
$user = $_POST['username'];
$email = $_POST['email'];
$pass = $_POST['password'];
$smt = new DBConnection();
$qry = $smt->prepare("INSERT INTO student(User_Name,Email,Password) VALUES (:user,:email,:pass)");
$qry->execute(array(':user'=>$user,':email'=>$email,':pass'=>$pass));
}
I have a slight problem here with my PHP page. I have difficulties getting the filled in data in a database.
Let me show you the code of the index;
<form action="aanmelden.php" method="post">
Naam: <input type="text" name="naam"><br>
Achternaam: <input type="text" name="achternaam"><br>
<input type="submit">
</form>
<php
$nm = $_POST['naam;];
$anm = $_POST['achternaam'];
?>
Now I thought I had obtained the variabled and sent to the 'aanmelden.php' file.
The contents of the aanmelden.php file are:
<?php
$nm = $_GET['naam'];
$anm = $_GET['achternaam'];
$connect = mysql_connect('localhost', 'root', 'usbw');
mysql_select_db ('kantine');
$sql = "INSERT into kantine (naam, achternaam)
VALUES ('$nm', '$anm')";
$res = mysql_query($sql);
mysql_close ($connect); ?>
Looks all quite good to me, but when I press the submit button I get the following errors.
Notice: Undefined index: naam in I:\USBWebserver v8.6\root\aanmelden.php on line 2
Notice: Undefined index: achternaam in I:\USBWebserver
v8.6\root\aanmelden.php on line 3
Please help me out if you can.
Regards,
Demiën
Since your form is configured to use method="post", you should be using the $_POST array rather than $_GET.
$name = $_POST['name'];
$lname = $_POST['lastname'];
See The Method Attribute.
Also, to avoid potential undefined indexes, I'd advise setting these variables with the ternary operator. That way, you can check for the existence of particular indexes before trying to access them.
$name = isset($_POST['name']) ? $_POST['name'] : false;
$lname = isset($_POST['lastname']) ? $_POST['lastname'] : false;
Edit
Other potential issues (or typos) with your code are:
// invalid, should be <?php
<php
// semi-colon instead of a closing quote, should be $_POST['name']
$name = $_POST['name;];
Note the mismatch:
<form action="register.php" method="post">
^^^^
$name = $_GET['name'];
^^^^
You probably want $_POST instead.
And note that you are vulnerable to sql injection attacks
You are using method POST when you submit the form; however you are using the GET method to retrieve the information.
Change $_GET to $_POST on register.php and that should do the trick.
You probably don't want SQL Injection vulnerabilites, so I coded you a nice example of connecting to a DB and writing some values in it from POST.
<?php
$DB_SERVER = 'server_adress';
$DB_USER = 'mysql_server';
$DB_PASSWORD = 'myPassword';
$DB_NAME = 'myFancyDB';
try {
$db = new PDO("mysql:host=" . $DB_SERVER . ";dbname=" . $DB_NAME, $DB_USER, $DB_PASSWORD, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_PERSISTENT => true, PDO::MYSQL_ATTR_INIT_COMMAND => 'set names utf8mb4'));
} catch (PDOException $e) {
//Remove this Errormessage in Production as it leaks dbname + password
echo $e->getMessage();
}
//Now the DB has been initialized.
try {
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$sql = "INSERT INTO `registrierung` (Name, Lastname) VALUES (:name, :lastname);";
$query = $db->prepare($sql);
$query->execute(array(
':name' => $name,
':lastname' => $lastname));
if (!$query) {
echo 'Fail when executing query';
exit;
}
} catch (PDOException $e) {
//Remove this Errormessage in Production!! Leaks DB info. Replace with generic Errormessage
echo $e->getMessage();
exit;
}
echo "Success!";
I am trying to display a Website Title on my Home Page. This website title is stored in the database named mywebsite and in table settings. I want to update this with an input type text's value. The title is displayed perfectly but when I write something in the text field and submit it, the database doesn't update. I think I am doing everything right and there isn't any error displaying on my page, but still it is not working. Can anyone figure out the error?
Here's my code:
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
// Making connection
$con = mysqli_connect($host, $username, $password, $database);
// Making a sql query for "Website Title" and saving it in variable $query
$query = "SELECT * FROM settings WHERE NameOfSetting='Website Title'";
// Applying query
$result = mysqli_query($con, $query);
// Fetching data from database
$row = mysqli_fetch_array($result);
if (isset($_POST['submit'])) {
$title = $_POST['text'];
mysqli_query($con, "UPDATE settings SET TheSetting=$title WHERE NameOfSetting='Website Title'");
}
?>
<h1><?php echo $row['TheSetting']; ?></h1>
<form method="POST">
<input type="text" placeholder="Change the title" name="text">
<input type="submit" name="submit">
</form>
EDIT: When I enter any numbers in the field and then submit and refresh it works fine but it's only working with numbers not with alphabets. I don't know why?
This line:
SET TheSetting=$title
$title needs to be wrapped in quotes:
SET TheSetting='$title'
Sidenote: You may also want to change this line (as a security precaution):
$title = $_POST['text'];
to:
$title = mysqli_real_escape_string($con,$_POST['text']);
Try with
mysqli_query($con, "UPDATE settings SET TheSetting='$title' WHERE NameOfSetting='Website Title'");
Well you can always do some sort of error checking. I.e. using or die(mysqli_error);
$con = mysqli_connect($host, $username, $password, $database)or die(mysqli_error);
This will atleast give you an idea of what your proplem is. Use this error checking method every time you connect, query, or close a database.
use this code it will solve your problem.
<?php
// Some database detail
$host = 'localhost';
$username = 'root';
$password = '';
$database = 'mywebsite';
// Making connection
$con = mysqli_connect($host, $username, $password, $database)or die(mysqli_error());
// Making a sql query for "Website Title" and saving it in variable $query
$query = "SELECT * FROM settings WHERE NameOfSetting='Website Title'";
// Applying query
$result = mysqli_query($con, $query);
// Fetching data from database
$row = mysqli_fetch_array($result);
if (isset($_POST['submit'])) {
$title = $_POST['text'];
mysqli_query($con, "UPDATE settings SET TheSetting='".$title."' WHERE NameOfSetting='Website Title'");
}
?>
<h1><?php echo $row['TheSetting']; ?></h1>
<form method="POST">
<input type="text" placeholder="Change the title" name="text">
<input type="submit" name="submit">
</form>
Code that Generates the HTML Form:
<form action='inc/q/prof.php' method='post'>
<input type='text' id='addComment' name='addComment' tabindex='3' value='Enter comment' />
</form>
*Php Code that is referenced in <form action = *
<?php
// Insert Comments into Database that user provides
$comm = mysql_real_escape_string($_POST['addComment']);
// following line has changed:
$pID4 = filter_input(INPUT_POST, 'pID', FILTER_SANITIZE_NUMBER_INT);
$cID = mysql_real_escape_string($_POST['courseInfoDD']);
$username = "####";
$password = "####";
$pdo4 = new PDO('mysql:host=localhost;dbname=####', $username, $password);
$pdo4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth4 = $pdo4->prepare('INSERT INTO Comment (info, pID, cID) VALUES(?,?,?);');
$sth4->execute(array($comm, $pID4, $cID ));
?>
Edit 2:
I assume you call prof.php?pID=120 and then you display the given form? And when you click the form the action references your PHP code? If so, then change the php file which prints your form to this:
<?
$pID = filter_input(INPUT_GET, 'pID', FILTER_SANITIZE_NUMBER_INT);
?>
<form action='inc/q/prof.php' method='post'>
<input type='text' id='addComment' name='addComment' tabindex='3' value='Enter comment' />
<input type="hidden" name="pID" value="<? echo $pID; ?>" />
</form>
Then, in the script handling your form submission, you can access the pID value via
$_POST["pID"]
as seen in my first edit, below:
Edit: Your PHP script would then look like this:
// Insert Comments into Database that user provides
$comm = mysql_real_escape_string($_POST['addComment']);
// following line has changed:
$pID4 = filter_input(INPUT_POST, 'pID', FILTER_SANITIZE_NUMBER_INT);
$cID = mysql_real_escape_string($_POST['courseInfoDD']);
$username = "###";
$password = "####";
$pdo4 = new PDO('mysql:host=localhost;dbname=####', $username, $password);
$pdo4->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sth4 = $pdo4->prepare('INSERT INTO Comment (info, pID, cID) VALUES(?,?,?);');
$sth4->execute(array($comm, $pID4, $cID ));
The hidden input field is the best way to pass the variables, since you can access it like a normal submitted POST variable (compare it with your $_POST['courseInfoDD']).
But remember to never use this for security relevant information, since this data can be viewed and changed (e.g. by javascript injection).