Php form value not matching [duplicate] - php

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.

Related

MED Schularberit

I have made a form which collets data form user and sendes them to the database,I wanted to add an addtional option to delete records that user choose.Im having trouble doing that and I would be very thankful i you cound help me.I am new in PHP so sorry that maybe I have done some "stupid" mistakes
The error I get:Notice: Undefined index: name in /var/customers/webs/harlac17/med3/shopping/delete.php on line 27
Code list.php Here are the POST data sent to Database and than showed in Web
<!DOCTYPE html>
<html>
<head>
<title>Shoppinglist</title>
<meta charset="utf-8">
</head>
<body>
<header>
<h1>Shoppinglist</h1>
Neue Produkt anlegen
</header>
<br>
<?php
error_reporting(0);
$database="****";
$username="****";
$password="****";
//Create a database connection with PDO(PHP Data Objects)
$connection=new PDO("mysql:host=localhost;dbname={$database}",$username,$password);
$name = $_POST['name'];
$description = $_POST['description'];
$image_url = $_POST['image_url'];
$count = $_POST['count'];
$sql = "INSERT INTO items(name,description,image_url,count) VALUES (?, ?, ?, ?)";
$statement=$connection->prepare($sql);
$statement->execute([$name, $description, $image_url, $count]);
$items=$connection->query("SELECT * FROM items");
while ($row = $items->fetch()) {
echo "<article>"." ".
"<button>"." ".
"<p>✖</p>"." ".
"</button>"." ".
"<h1>"." ".
$row['name']." ".
"</h1>"." ".
"<br>"." ".
"</p>"." ".
$row["description"]." ".
"</p>"." ".
"<br>"." ".
"<p>"." ".
"<img src='" . $row['image_url'] . "'>"." ".
"</p>"." ".
"<br>"." ".
"<p>"." ".
"Menge:" .$row['count']." ".
"</p>"." ".
"<br>"." ".
""." ".
"</article>"."".
"<a href='delete.php?id=". $row['name']. "'>DELETE</a>";
}
?>
</body>
Code delete.php
<?php
$database="";
$username="";
$password="";
//Create a database connection with PDO(PHP Data Objects)
$connection=new PDO("mysql:host=localhost;dbname={$database}",$username,$password);
$name = $_POST['name'];
$sql = "DELETE FROM items WHERE name='".$name."'";
$statement=$connection->prepare($sql);
$statement->execute();
?>
new.php Form with POST data
<!DOCTYPE html>
<html>
<head>
<title>Einkafsliste Formular</title>
</head>
<body>
<header>
<h1>        Produkte anlegen</h1>
</header>
<div class="form">
<form action="list.php" method="POST">
<label>Name:</label>
<br>
<input type="text" name="name" placeholder="Lebensmittelname" >
<br>
<label>Description:</label>
<br>
<input type="text" name="description" placeholder="Das ist..." >
<br>
<label>Bild URL:</label>
<br>
<input type="text" name="image_url" placeholder="Das URL von Lebensmittelbild" >
<br>
<label>Count:</label>
<br>
<input type="text" name="count" placeholder="Wie viel?" >
<br>
<input type="submit" name="submit" id="submit">
</form>
</div>
</body>
</html>
Firstly, don't include your SQL passwords on Stack Overflow :D
You will want to take a look at a couple of things here, note the try/catch (exceptions) usage, this is a good way of catching errors using PDO to show you where you are going wrong (read: https://www.php.net/manual/en/language.exceptions.php)
Also note how my sql string doesn't have the variable directly entered. This is bad practice and can leave your application open to sql injection vulnerabilities. Always escape your SQL commands using PDO->execute(). (read: https://doc.bccnsoft.com/docs/php-docs-7-en/pdostatement.execute.html)
For the 'Undefined index: name' error, you want to check if $_POST['name'] actually exists before you use it.
if (!#$_POST['name']) {
echo 'Missing POST: name';
die();
}
$name = $_POST['name'];
$username = "";
$password = "";
$database_name = "";
$database_host = "localhost";
$port = 3306;
try {
$con = new PDO("mysql:host=$database_host;port=$port;dbname=$database_name;charset=utf8mb4", $username, $password);
} catch (Exception $e) {
echo($e->getMessage());
die();
}
$statement = $con->prepare("DELETE FROM items WHERE name = :name");
try {
$statement->execute([
':name' => $name,
]);
} catch (PDOException $e) {
echo($e->getMessage());
die();
}
I believe the problem is with this line in delete.php, where PHP is unable to convert the PDO object to a string:
echo ("$connection");
Try removing it and test if it works fine.

PHP mysql Pdo search exact match using Email and date as input

hi i found a code on internet and edited a bit but i stuck on showing the correct result i want.. when i type the email address i get the correct result but if i have more than 1 entry i always get the last one is it possible to make it show the result based on the email and the date?
here is my code so far
<?php
// php search data in mysql database using PDO`enter code here`
// set data in input text
$id = "";
$reservation_name = "";
$persons = "";
$date = "";
$time = "";
$email = "";
$status= "";
if(isset($_POST['Find']))
{
// connect to mysql
try {
$pdoConnect = new PDO("mysql:host=localhost;dbname=multi_edit","root","");
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
// id to search
$email = $_POST['email'];
// mysql search query
$pdoQuery = "SELECT * FROM member WHERE email = :email";
$pdoResult = $pdoConnect->prepare($pdoQuery);
//set your id to the query id
$pdoExec = $pdoResult->execute(array(":email"=>$email));
if($pdoExec)
{
// if id exist
// show data in inputs
if($pdoResult->rowCount()>0)
{
foreach($pdoResult as $row)
{
$id = $row['id'];
$reservation_name = $row['reservation_name'];
$persons = $row['persons'];
$date = $row['date'];
$time = $row['time'];
$status = $row['status'];
}
}
// if the id not exist
// show a message and clear inputs
else{
echo 'No Reservation Found On This Email';
}
}else{
echo 'ERROR Something Is Wrong Try Again';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Search Your Reservation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="search.php" method="post">
<center>
Please Enter Your Email Address : <br><br><br><input type="text" name="email" value="<?php echo $email;?>"><br><br>
Reservation Name : <br><input type="text" readonly name="reservation_name" value="<?php echo $reservation_name;?>"><br><br>
Persons : <br><input type="text" readonly name="persons" value="<?php echo $persons;?>"><br><br>
Date Y-M-D : <br><input type="text" name="date" value="<?php echo $date;?>"><br><br>
Time : <br><input type="text" readonly name="time" value="<?php echo $time;?>"><br><br>
Status : <br><input type="text" readonly name="status" value="<?php echo $status;?>"><br><br>
<input type="submit" name="Find" value="Find Data">
</center>
</form>
</body>
</html>
I have work out what you need, it require email (like foobar#gmail.com) and date (like 2018-09-23) in the form input field, if you submit it return the Reservation Name.
Notice for simplicity reason I removed these 3 columns "persons", "time" and "status", but you can add it back, it doesn't change the logic because the finding/query don't need those fields for input
This is my code:
<?php
// php search data in mysql database using PDO`enter code here`
// set data in input text
function sqlInitConn ($args) {
// Initialze connection.
$serverName = $args["serverName"];
$userName = $args["userName"];
$password = $args["password"];
$dbName = $args["dbName"];
$conn = new PDO("mysql:host=$serverName;dbname=$dbName", $userName, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $conn;
}
// Those variables are for input to mysql.
$idIpt = "";
$reservation_nameIpt = "";
$emailIpt = "";
$dateIpt = "";
// Those variables are for output to front-end.
$idOpt = "";
$reservation_nameOpt = "";
$emailOpt = "";
$dateOpt = "";
if(isset($_POST['find']))
{
try {
// Connect to mysql.
$pdoConnect = sqlInitConn([
"serverName" => "localhost",
// Change it to your server name.
"userName" => "root",
"password" => "change_it_to__your_password_here_if_your_mysql_need_password",
"dbName" => "multi_edit",
]);
} catch (PDOException $exc) {
echo $exc->getMessage();
exit();
}
$emailIpt = $_POST['email'];
$dateIpt = $_POST['date'];
$pdoQuery = "SELECT * FROM member WHERE email = :email AND date = :date";
// Mysql search query
$pdoResult = $pdoConnect->prepare($pdoQuery);
$pdoResult->bindValue(":email", $emailIpt);
$pdoResult->bindValue(":date", $dateIpt);
$pdoExec = $pdoResult->execute();
if($pdoExec) {
// If record exist, show data in inputs
if($pdoResult->rowCount() > 0) {
foreach($pdoResult as $row) {
$idOpt = $row['id'];
$reservation_nameOpt = $row['reservation_name'];
$emailOpt = $row['email'];
$dateOpt = $row['date'];
break;
// only get first occurrences (get first matching record) to prevent corrupted data
// , because same email might wrongly log twice in same day (= same date), like morning and afternoon.).
}
}
else {
echo 'No Reservation Found On This Email';
// If the id not exist, show a message and clear inputs
}
} else {
echo 'ERROR Something Is Wrong Try Again';
// If the id not exist, show a message and clear inputs
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Search Your Reservation </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="" method="post">
<center>
<div>
<p>Please Enter Your Email Address :</p>
<input type="text" name="email" value="<?php echo $emailOpt;?>">
</div>
<div>
<p>Reservation Name :</p>
<input type="text" readonly name="reservation_name" value="<?php echo $reservation_nameOpt;?>">
</div>
<div>
<p>Date Y-M-D :</p>
<input type="text" name="date" value="<?php echo $dateOpt;?>">
</div>
<div>
<input type="submit" name="find" value="Find Data">
</div>
</center>
</form>
</body>
</html>

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']

Apostrophe in HTML textarea causing PHP error [duplicate]

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

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 :)

Categories