Apostrophe in HTML textarea causing PHP error [duplicate] - php

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
This is my first ever post on Stack Overflow. I have had a good try with this and a good search for answers, but to no avail. So here goes:
I have made a basic messaging app just for coding practice. Obviously, I want it to be safe from xss so have used "HTMLspecialchars".
The problem:
The app works fine as long as no one puts an apostrophe in the message. So the message "Let's go" throws an error:
let's go Error:INSERT INTO chat (msg) VALUES ('Hello let's go')
You have an error in your SQL syntax; check the manual that corresponds to your >MariaDB server version for the right syntax to use near 's go')' at line 2
Here's my code for inputting and sending to mysql:
<!DOCTYPE html>
<!-- input -->
<html>
<body>
<?php
// define variables and set to empty values
$name = $msg = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$msg = test_input($_POST["msg"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<h2>Messaging Appq</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value ="<?php echo htmlspecialchars($_POST['name']); ?> ">
<br><br>
Message: <textarea name="msg" rows="5" cols="40"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
<!-- enter on DB -->
<?php
$servername = "localhost";
$username = "*********";
$password = "*********";
$dbname = "***********";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$name=$_POST['name'];
$msg=$_POST['msg'];
$bothd = $name . $msg;
$sql = "INSERT INTO chat (msg)
VALUES ('$bothd')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully<br><br>";
} else {
echo "Error:" . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
So, I know i need to use "ent_quotes". But where should it go? I see the normal syntax is
<?php echo htmlspecialchars($str, ENT_QUOTES); ?>
and I have tried putting "ent_quotes" in the following positions, obviously not all at the same time:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"], ENT_QUOTES);?>">
Name: <input type="text" name="name" value ="<?php echo htmlspecialchars($_POST['name'], ENT_QUOTES); ?> ">
<br><br>
Message: <textarea name="msg" rows="5" cols="40" value ="<?php echo htmlspecialchars($msg, ENT_QUOTES); ?>"></textarea>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
I also tried adding it to the function:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data, ENT_QUOTES);
return $data;
}
Apologies if I am missing something obvious! I am relatively new to this!

SELECT 'A ''quoted'' word.' AS text FROM DUAL;
TEXT
A 'quoted' word.
you have to edit the query string and add another ' to your string

Related

how to fix error of empty $_POST['name']

I want to have a form with php. but for many hours I'm involved an error and the error is when $_POST=['name'] wants to be checked empty or not it is empty.
When I check the database the row is white and nothing is there.
for checking if the $_POST is empty or not I print word 'empty' to be determined it's empty and it will be printed 'empty';
where is my mistake is it related to database mysql or not just in code?
please help me I got confused and bored.
this is whole of my codes:
<!doctype html>
<html lang="fa">
<head>
<meta charset="utf-8">
<title>form</title>
<link href="addContact.css" rel="stylesheet"/>
<link href="main.css" rel="stylesheet"/>
<link href="table.css" rel="stylesheet"/>
</head>
<body>
<?php
$name = "";
$nameErr = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
echo 'empty';
$nameErr = "Name is required";
} else {
echo 'full';
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Only letters and white space allowed";
}
}
$servername = "localhost";
$username = "abc";
$password = "abc";
$dbname = "abc";
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 abc (firstname)
VALUES ('$name')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
echo "New record created successfully. Last inserted ID is: " . $last_id;
} catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<form method="post" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name" value="<?php echo $name;?>">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
thank you in advance
The problem is in use of empty()
You can use it on variables not on values.
See here for PHP documentation page.
To check this, first save it in another variable and then check:
$tempVal = $_POST["name"];
if (empty($tempVal))
you can use this simple example
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User Has submitted the form and entered this name : <b> $name </b>";
echo "<br>You can use the following form again to enter a new name.";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
i suggest this:
Understanding $_SERVER['PHP_SELF']

Insert multiple email to mysql using single textarea

I want to insert multiple emails into the database using single text area.
This is my code :
PHP
error_reporting(E_ERROR | E_WARNING | E_PARSE);
$dbhost = "localhost";
$dbname = "emails_test";
$dbuser = "root";
$dbpass = "";
$conn = mysql_connect($dbhost,$dbuser,$dbpass);
if (!$conn) { die('Could not connect: ' . mysql_error()); }
mysql_select_db($dbname, $conn);
if(isset($_POST['submit'])) {
//$email = nl2br($_POST['email']);
$email = explode("\r\n", $_POST['email']);
foreach($email as $emails) {
$query = mysql_query("INSERT INTO emails (email) VALUES ('$emails')");
if($query) { echo "Inserted into the database"; } else { echo"Fail, please try again"; }
}
}
HTML
<body>
<form name="form1" method="POST">
<textarea rows="5" name="email" cols="50" ></textarea><br>
<input type="submit" name="submit" value="submit">
</form>
</body>
I want table to be like this :
Use explode to get string into array by "\r\n"
don't use single quotes you need to use double quotes to explode the string by \r\n I just got to know that.
<?php
if(isset($_POST['submit'])) {
//$email = nl2br($_POST['email']);
$email = explode("\r\n", $_POST['email']);
foreach($email as $emails) {
$query = mysql_query("INSERT INTO emails (email) VALUES ('$emails')");
if($query) {
echo "Inserted into the database";
} else {
echo "Fail, please try again";
}
}
}
?>
<body>
<form name="form1" method="POST">
<textarea rows="5" name="email" cols="50" ></textarea>
<br />
<input type="submit" name="submit" value="submit">
</form>
</body>
You may try this way
<body>
<form name="form1" method="POST">
<textarea rows="5" name="email" cols="50" ></textarea>
<br />
<input type="submit" name="submit" value="submit">
</form>
</body>
Note :- use "Enter" to put all email (one by one)
Insert into database
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
if(isset($_POST["submit"])) {
$str = $_POST["email"];
$email = preg_split('/\r\n|\n|\r/', $str);
foreach($email as $emails) {
$query = mysqli_query($conn, "INSERT INTO emails (email) VALUES ('".$emails."')");
if($query) { ?>
<script>alert("Inserted into the database");</script>
<?php } else { ?>
<script>alert("Fail, please try again");</script>
<?php } } }
mysqli_close($conn);
?>
Example :-
Your code will work as intended if you will just replace this
$email = nl2br($_POST['email']);
with this
$email = preg_split('/\r\n|\n|\r/', $_POST['email']);
The problem is, you just have replaced all \n\r with <br>\n\r. The nl2br returns a string with replacements, but you need an array for using it inside the foreach loop.
As an additional note, you're iterating through an array and every time you are adding this instruction:
<script>alert("Inserted into the database");</script>
If you will iterate through 10 emails, you will be alerted ten times in a row.
Also, mysql_query is deprecated. It's time to learn either PDO, or MySQLi, which will give you ability to use placeholders instead of unsafe direct injecting $_POST data into SQL query. Placehiolders are pretty easy to learn, and they can help you to build more reliable applications.
Do this in your code...
HTML
<body>
<form name="form1" method="POST">
<textarea rows="5" name="email" cols="50" ></textarea><br>
<small>Enter email IDs separated by comma(,)</small>
<input type="submit" name="submit" value="submit"><br>
</form>
</body>
PHP
if(isset($_POST['submit'])) {
$email = explode(',',$_POST['email']);//convert into $email array
$value = '';
foreach($email as $r) $value .= '("'.$r.'"),';//concatenate email for insert
$value = rtrim($value,',').';' //remove the last comma ;
$query = mysqli_query('INSERT INTO emails (email) VALUES '.$value);// insert all email in database in single query in different rows
if($query) echo 'Inserted into the database';
else echo 'Fail, please try again";
}
You will get your output...

How to validate if a checkbox is checked in PHP [duplicate]

This question already has answers here:
How to validate a single checkbox using PHP & MySQL
(2 answers)
How to validate checkbox group in PHP [closed]
(2 answers)
PHP Checkbox array validating
(4 answers)
How to validate a checkbox input using PHP?
(4 answers)
Closed 5 years ago.
I the following code, I have a form that consists of three fields and two buttons. In the Review button, I would like to show any word in Arabic randomly and let the user show its translation in English by ticking the Show translation checkbox.
<html>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$english = $_POST["english"];
$arabic = $_POST["arabic"];
$example = $_POST["example"];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<textarea name="english" rows="4" cols="70" placeholder="English">English</textarea>
<br>
<textarea name="arabic" rows="4" cols="70" placeholder="Arabic">Arabic</textarea>
<br>
<textarea name="example" rows="4" cols="70" placeholder="Example">Example</textarea>
<br><br>
<input type="submit" name="add" value="Add new">
<input type="submit" name="review" value="Review">
</form>
<?php
$servername = "localhost";
$username = "xxx";
$password = "yyy";
$dbname = "vdb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST['add'])) {
$sql = "INSERT INTO Vocabulary (English, Arabic, Example)
VALUES ('$english', '$arabic', '$example')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
elseif (isset($_POST['review'])) {
$sql = "SELECT COUNT(ID) as total FROM Vocabulary";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
#echo $row['total'];
$generated = rand(1,$row['total']);
$sql1 = "SELECT * FROM Vocabulary where ID = $generated";
$result1 = $conn->query($sql1);
$row1 = $result1->fetch_assoc();
echo "<br>";
echo $row1['Arabic'];
echo "<br><br>";
echo "<input type='checkbox' name='feeling' value='good'>Show translation";
echo "<br><br>";
}
$conn->close();
?>
</body>
</html>
Everything works fine except that I don't know how to show the translation of the word when the checkbox is checked.
Do you have any suggestions of how to let that work?
Thanks

How to update user input of a form when i am using header that links to other file?

I am writing a form using php and mysql. The main goal is to make the form
(1) detect missing field.
(2) update user input after successful submit and
(3) most importantly to avoid re-submission on reload/refresh.
I am able to manage the first and the third one but doesn't have any idea on the second one.
Here's my code (able to achieve first and third)
form1.php
<!DOCTYPE html>
<html>
<head></head>
<body>
<?php
$name = "";
$class = "";
$school = "";
if(isset($_POST["submit"])){
$name = $_POST["name"];
$class = $_POST["class"];
$school = $_POST["school"];
$output = false;
if(empty($_POST["name"]) || empty($_POST["class"]) || empty($_POST["school"])){
echo 'field cannot be empty';
$output_form = true;
}
if(!empty($_POST["name"]) && !empty($_POST["class"]) && !empty($_POST["school"])){
$hostname = "localhost";
$admin = "root";
$password = "";
$database = "testdatabase";
$dbc = mysqli_connect($hostname, $admin, $password, $database) or die("database connection error");
$insert_query = "INSERT INTO `sorty` (`name`, `class`, `school`) VALUES ('$name', '$class', '$school')";
$insert_result = mysqli_query($dbc, $insert_query) or die("error");
if($insert_result == 1)
echo "data inserted";
else
echo "insert query failed";
mysqli_close($dbc);
header('Location: form2.php');
}
}
else
$output = true;
if($output){
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Name: <input type="text" name="name" value="<?php echo $name?>"/><br/>
Class: <input type="text" name="class" value="<?php echo $class?>"/><br/>
School: <input type="text" name="school" value="<?php echo $school?>"/><br/>
<input type="submit" value="submit" name="submit"/>
</form>
<?php
}
?>
</body>
</html>
My second file form2.php(succesful page after form submission)
<body>
Name: /*user input here*/<br/>
Class: /*user input here*/<br/>
School: /*user input here*/<br/>
As I can't access the variable $name, $class, $school of form.php I am having problem updating the user input data. So is there anyway to access the variable across file or is it not possible to do in this way.
user_name you may check this out. and read the code. i hope you will get the answer. You may add session for showing the message that the specified operation is done. thank you :)

Php form value not matching [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I have reviewed the code and everything appears right so I am not sure what is wrong. I keep getting the following error s1s01 1136 column count does match.
I believe I used all the correct security codes please note if I did not thank you.
<?php
include ('wording/en-translation.php');
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
</head>
<body>
<?php
// define variables and set to empty values
$user_nameErr = $user_emailErr = "";
$user_name = $user_email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["user_name"])) {
$user_nameErr = "Name is required";
} else {
$user_name = mysql_real_escape_string($_POST["user_name"]);
//check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z]*$/",$user_name)) {
$user_nameErr="Only letters and white spaces allowed";
}
}
if (empty($_POST["user_email"])) {
$user_emailErr = "Email is required";
} else {
$user_email = mysql_real_escape_string($_POST["user_email"]);
//check if email is well-formed
if (!filter_var($user_email, FILTER_VALIDATE_EMAIL)) {
$user_emailErr = "Invalid Email Format";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$user_name = mysql_real_escape_string($_POST["user_name"]);
$user_email = mysql_real_escape_string($_POST["user_email"]);
}
function mysql_real_escape_string($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<label for="user_name"><?php echo WORDING_REGISTRATION_USERNAME; ?></label>
<input id="user_name" type="text" pattern="[a-zA-Z0-9]{2,64}" value="<?php echo $user_name; ?>" name="user_name" required />
<span class="error">* <?php echo $user_nameErr;?></span><br>
<label for="user_email"><?php echo WORDING_REGISTRATION_EMAIL; ?></label>
<input id="user_email" type="email" name="user_email" value="<?php echo $user_email; ?>" required />
<span class="error">* <?php echo $user_emailErr;?></span>
<input type="submit" name="register" value="<?php echo WORDING_REGISTER; ?>" />
</form>
<?php
echo $user_name;
echo "<br>";
echo $user_email;
echo "<br>";
?>
<?php
$servername = "localhost";
$username = "admin";
$password = "";
$dbname = "login";
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 users(user_name, user_email)
VALUES(
". mysql_real_escape_string($user_name) ."',
". mysql_real_escape_string($user_email) ."'
)";
// 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;
?>
</
You're generating broken SQL, by having completely WRONG quoting on your values:
$sql = "INSERT INTO users(user_name, user_email)
VALUES(
". mysql_real_escape_string($user_name) ."',
^---start sql string
". mysql_real_escape_string($user_email) ."'
^---end of sql string
)";
That means you're generating
INSERT INTO users (user_name, user_email) VALUES (Bob, 'bob#example.com')
^--unknown field
you're also mixing mysql libraries, which is flat out IMPOSSIBLE, and you're vulnerable to sql injection attacks.
In short, this code is totally cargo-cult programming, and you really need to sit back and learn PHP properly.

Categories