Fix blank database entries on page load? - php

I have a form on an HTML webpage that sends a user's comment and name to a MySQL database table, where it is stored, and then included back onto the page. The problem is, if the user's name has an apostrophe in it, the server (I pay for hosting, it's not my server and I can't change the configuration on it) is sending them to a error page that says:
"The requested URL was rejected. If you think this is an error, please contact the webmaster.
Your support ID is: 13509873612934211694"
UPDATE:
I just completely rewrote the page using a different php format. Now the apostrophe issue and the server error is fixed. However, the page is sending blank entries to the database on every page load. Any ideas?
<?php
$servername = "my_server";
$username = "my_username";
$password = "my_password";
$dbname = "my_database";
$users_name = htmlentities($_POST['name'], ENT_QUOTES, 'UTF-8');
$users_request = $_POST['requests'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
}
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();
$conn->exec("INSERT INTO submissions (requests, name)
VALUES ('$users_request', '$users_name')");
$conn->commit();
header("Location: clv3.php");
}
catch(PDOException $e)
{
$conn->rollback();
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
<form method="POST" action="<?php echo
htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Make A Request:<br>
<textarea name='requests' id='requests'></textarea> <br>
Your Name (a-z only):<br>
<input type='text' name='name' id='name'/><br>
<input type='submit' value='Send' class='button'>
</form>

Ever heard of SQL injection? This is one you create...
Always escape your data! You are now pushing data given by user directly into database.
$name = mysqli_real_escape_string($conn, $_POST['name']);
$comments = mysqli_real_escape_string($conn, $_POST['comments']);
Also you can encode special chars before insert, and decode when showing

Did you perhaps try:
encodeURI(yourString)
Then on php side you do:
url_decode($_POST['myVariable'])

Related

PHP variable wont show in form input field

I'm trying to select a PHP variable from a database insert it into an html form input. I guess my question is how do you store the query into a variable and then call that variable in an html form? Also, the form is located on a separate page from the form action file. Why is it undefined if it's defined in the PHP file? The desired output is when I load the html page the value from the database for nickname auto-fills that field of the form.
error:
Notice: Undefined variable: Nickname in C:\xampp\htdocs\Client-Projects\Crossfire\templates\CoinSubmission.html on line 45
CoinSubmission.html
<form autocomplete="off" action="AdminCoinSub_Code.php" method="POST">
<p>
<input type="text" name="Nickname" id="Nickname" value="<?php echo htmlspecialchars($Nickname); ?>" />
</p>
</form>
AdminCoinSub_Code.php
<?php {
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "administrator_logins";
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);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO coin (ProfileID, Store, Position,
Nickname, ContactNumber, MachineCount, CutOffDate, Coins, location, LastSubmission, Rank)
VALUES (:ProfileID, :Store,:Position, :Nickname,:ContactNumber,:MachineCount,:CutOffDate, :Coins,:location,:LastSubmission,:Rank)");
$stmt->bindParam(':ProfileID', $_POST['ProfileID']);
$stmt->bindParam(':Store', $_POST['Store']);
$stmt->bindParam(':Position', $_POST['Position']);
$stmt->bindParam(':Nickname', $_POST['Nickname']);
$stmt->bindParam(':ContactNumber', $_POST['ContactNumber']);
$stmt->bindParam(':MachineCount', $_POST['MachineCount']);
$stmt->bindParam(':CutOffDate', $_POST['CutOffDate']);
$stmt->bindParam(':Coins', $_POST['Coins']);
$stmt->bindParam(':location', $_POST['location']);
$stmt->bindParam(':LastSubmission', $_POST['LastSubmission']);
$stmt->bindParam(':Rank', $_POST['Rank']);
$stmt->execute();
echo "Success";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
}
$conn=mysqli_connect($servername,$username,$password,$dbname);
if (mysqli_connect_errno($conn))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT `Nickname` FROM `adminlogin` WHERE `ProfileID` = ':ProfileID'";
$Nickname = $conn->query($query); // This is where the query is executed
$fetcher = $Nickname->fetch_assoc();
while($row = mysqli_fetch_array($Nickname))
if (mysqli_num_rows($Nickname) > 0) {
echo 'User name exists in the table.';
} else {
echo 'User name does not exist in the table.';
}
?>
First of all, your html page should have the extension .php and not .html, that way it can interpret your php code inside the html file, don't worry this wont break the html.
why is it undefined if it's defined in the php file.
It's because each php script run separately unless you hook them together.
I would recommend yo read a bit more about how php works.
For this example to work i would do it it this way.
CoinSubmission.php
<?php //This goes at the top of the file
include_once('AdminCoinSub_Code.php') //If they are in the same dir else you will need to set the path properly.
?>
<form autocomplete="off" action="AdminCoinSub_Code.php" method="POST">
<p>
<input type="text" name="Nickname" id="Nickname" value="<?php echo
htmlspecialchars($Nickname); ?>">
</p>
</form>
The include at the top will "paste" your code of AdminCoinSub_Code in the CoinSubmission file and treat it as one file. So the variable will be accesible for it.
Note: My explanation is oversimplified, it ain't exactily how it works, but should get the gist of it.
Alaa Morad answer if also valid, but remember to change the .html to .php
Happy Coding :)
That's because $Nickname will not be set if Register Globals is off witch is a normal thing !
Register Globals has been DEPRECATED as of PHP 5.3.0 and REMOVED as of PHP 5.4.0
so use $_POST
<input type="text" name="Nickname" id="Nickname" value="<?php echo htmlspecialchars($_POST['Nickname']); ?>">

PHP/MYSQL Insert is doing nothing

I have a simple form set up in HTML to pass values to PHP and put them in a MYSQL database. I just can't fathom why nothing is happening when I click the submit button. Previously it was saying 'failed' but now nothing. I have checked the values from the form - fine. I've checked the database connection - fine. I've checked the SQL statement - well, I can't see any errors.
This is my main HTML page
<p class="subtitle">Let me know what you think</p>
<form action="db_insert.php">
<input name="username" placeholder="Name">
<br>
<textarea name="comments" placeholder="Please type your comments here"
cols=120 rows=5></textarea>
<br>
<input type="button" name="submit" value="submit">
<br>
<p id="commTitle">Comments</p>
<br>
<p id="comment"></p>
This is the PHP
<?php
include 'db_connection.php';
//create database connection
$conn = OpenCon();
$username = htmlspecialchars($_POST['username']);
$comment = htmlspecialchars($_POST['comment']);
$sql = 'INSERT INTO sitecomments(username, comment) VALUES(:username,:comment)';
$stmt = $conn -> prepare($sql);
$stmt -> bindValue(':username', $username);
$stmt -> bindValue(':comment', $comment);
$q_result = $stmt -> execute();
if($q_result){
echo 'Comment Inserted Successfully';
}
else{
echo 'Failed';
}
db_connection.php looks like this (with credentials removed.
<?php
function OpenCon(){
//pass the database details to variables
$host = "localhost";
$dbuser = "*****";
$dbpass = "*****";
$dbname = "*****";
// combine host and db name in to single variable
$dbhost = "mysql:host=$host;dbname=$dbname";
//create PDO from database information
$dbconn = new PDO($dbhost, $dbuser, $dbpass);
return $dbconn;
}
?>
As I said, I've checked the database connection and all is fine so where on earth am I going wrong? My database has 3 fields but one is autoincremented so I haven't included it in the query. I tried the query in MyPHPAdmin and it passed ok.
The first thing I notice is that the input has name of "comments" rather than the $_POST variable you're accessing called comment:
<textarea name="comments" placeholder="Please type your comments here" cols=120 rows=5></textarea>
$comment = htmlspecialchars($_POST['comment']);
Try changing that and see if it fixes the issue.
It would be helpful to handle errors within your code. In your current example if something goes wrong you will have a hard time finding out where the problem is.
You can try all of the following examples from the PHP Docs on PDO error handling and PDO::errorInfo:
Assert your connection is valid:
try {
$dbh = new PDO($dsn, $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit;
}
Assert your SQL is valid
/* Provoke an error -- bogus SQL syntax */
$stmt = $dbh->prepare('bogus sql');
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
As usual the error is a pebcak error, and you need to utilize proper debugging tools to find out where your mistakes are. Good luck!

How do I post a single value to PHP MyAdmin. This code doesn't seem to work. I am trying to get a value from a form into a database

<form action="signup.php" method="POST" id="newsletter">
<h4>Join Our Newsletter</h4>
<input id="email" type="text" value="Enter Email Address Here For Updates" onBlur="javascript:if(this.value==''){this.value=this.defaultValue;}" onFocus="javascript:if(this.value==this.defaultValue){this.value='';}">
<input type="submit" value="Sign up" class="btn2">
</form>
<?php
$dsn = "mysql:dbname=test_db";
$DBusername = "test";
$DBpassword = "test";
try {
$conn = new PDO($dsn, $DBusername, $DBpassword);
}
catch(PDOException $e) {
}
$email = $_POST["email"];
$sql = "INSERT INTO contacts (email) VALUES (:email)";
$pdoQuery = $conn->prepare($sql);
$pdoQuery->bindValue(":email", $email, PDO::PARAM_STR);
$pdoQuery->execute();
setcookie("success", "You have successfully signed up for the newsletter.", 0, "/");
header("Location: index.php");
?>
These are both on separate pages, and I can't seem to figure out why they won't work. Any help would be greatly appreciated! Nothing posts to the database at all. The cookie is working though.
Your connection is probably failing. You don't have a host in your DSN
$dsn = "mysql:host=localhost;dbname=test_db";
Not sure if it is localhost, but hope this shows what it should be. It would also probably help that when you catch the exception, that you output something.
even...
catch(PDOException $e) {
echo "error - ".$e->getMessage().PHP_EOL;
exit;
}

User not being deleted on link click [duplicate]

This question already has answers here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Reference - What does this error mean in PHP?
(38 answers)
Closed 5 years ago.
I have a users table and I want to be able to delete a user when a link is clicked. $user_name is set in a session. Here is the link:
<?php echo "Delete Account" ?>
Here is the code on delete_user.php:
<?php
session_start();
session_destroy();
require "connection.php";
?>
<?php
if($_GET['id'] != ""){
$user_name = $_GET['id'];
$sql = "DELETE FROM users WHERE user_name='{$user_name}'";
$result = mysqli_query($connection, $sql);
header('Location: register.php');
}
?>
<?php include "footer.php";?>
I don't understand why it's not deleting the user from the database when this code is executed?
There's no clear reason as to why your code is not working. However, you mentioned being new to PHP, so picking up good practices with your code could (1) help solve the issue at hand, (2) make your code more efficient, and easier to debug.
I recommend you use mysqli in the object-oriented manner, it requires less code, and usually easier to follow.
Making the connection is simple:
<?php
$host = 'localhost';
$user = 'USERNAME';
$pass = 'PASS';
$data = 'DATABASE';
$mysqli = new mysqli($host, $user, $pass, $data);
// catch errors for help in troubleshooting
if ($mysqli->errno)
{
echo 'Error: ' . $mysqli->connect_error;
exit;
}
?>
Creating a safe environment for your server keep in mind these things:
Do not trust user input (ever!)
Do not perform direct queries into your database.
When developing, break your code into steps so you can easily troubleshoot each part.
With those three simple things in mind, create a delete file.
<?php
if (isset($_GET['id'])
{
// never trust any user input
$id = urlencode($_GET['id']);
$table = 'users';
// set a LIMIT of 1 record for the query
$sql = "DELETE FROM " . $table . " WHERE user_name = ? LIMIT 1";
// to run your code create a prepared statement
if ($stmt = $mysqli->prepare( $sql ))
{
// create the bind param
$stmt->bind_param('s', $id);
$stmt->execute();
$message = array(
'is_error' => 'success',
'message' => 'Success: ' . $stmt->affected_rows . ' were updated.'
);
$stmt->close();
}
else
{
$message = array(
'is_error' => 'danger',
'message' => 'Error: There was a problem with your query'
);
}
}
else
{
echo 'No user id is set...';
}
The code will help you set the query, and delete the user based on their user_name... Which I am not sure that is the best solution, unless user_name is set to be an unique field on your MySQL database.
Firstly this is a horrible way to do this, you are prone to SQL Injections and also using GET literally just tags the query to the end of the URL which is easily obtainable by a potential hacker or ANY user as a matter of fact. Use POST instead with a bit of jQuery magic, I would also recommend using Ajax so that you don't get redirected to php file and it will just run. As it is not anyone can access that URL and delete users so I recommend using PHP SESSIONS so that only people from your site can delete users. Also simply passing the id to the PHP file is very insecure as ANYONE could simply create a link to your php file on their site and delete users.
Therefore try this to fix your code (with added security):
PLEASE NOTE: I am aware that this may not be the best way nor the worst but it is a fairly secure method that works well.
Your main page, index.php:
<?php
session_start();
// Create a new random CSRF token.
if (! isset($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
// Check a POST is valid.
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
// POST data is valid.
}
?>
...
<form id="delete_user_form" action="delete_user.php" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_name; ?>" />
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>" />
<input type="submit" value="Delete User" />
</form>
In your .js file (make sure you have jQuery linked):
window.csrf = { csrf_token: $("input[name= csrf_token]").val() };
$.ajaxSetup({
data: window.csrf
});
$("#delete_user_form").submit(function(event) {
event.preventDefault(); //Stops the form from submitting
// CSRF token is now automatically merged in AJAX request data.
$.post('delete_user.php', { user_id: $("input[name=user_id]").val() }, function(data) {
//When it it's complete this is run
console.log(data); //With this you can create a success or error message element
});
});
Now for your delete_user.php file, this should fix the errors:
<?php
session_start();
require "connection.php";
// Checks if csrf_token is valid
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
if(isset($_POST['user_id']) && $_POST['user_id'] != ""){
$user_name = $_POST['user_id'];
$sql = "DELETE FROM users WHERE user_name = '$user_name' LIMIT 1"; //LIMIT 1 only allows 1 record to be deleted
if ($conn->query($sql) === TRUE) {
echo "Record deleted successfully"; //You get this in your javascript output data variable
} else {
echo "Error deleting record: " . $conn->error; //You get this in your javascript output data variable
}
$conn->close();
}
}
?>
I don't know what your connection.php contains so this is what I'd put in it:
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

Form area textarea is not updating to the database because of special characters

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.

Categories