i want to ask something, i passed a value from controller to view and in database, i wonder how do i delete the "/" character. here's the code
Dashboard.php
<form action="/dashboard/post" method="post">
<input type="hidden" name="user_id" value=<?=$userid?>/>
<div class="form-group">
<label for="">Username</label>
<input type="text" name="user_name" id="" class="form-control">
</div>
<div class="form-group">
<label for="">Email</label>
<input type="text" name="user_email" id="" class="form-control">
</div>
</form>
Controller.php
public function index()
{
$model = new DataModel();
$user = $model->findAll();
$hidden_data = [
'userid' => count($user)
];
return view('dashboard', $hidden_data);
}
here's the table
honestly i just want to the user_id insert the number only without "/". i knew that sql has auto increment feature but actually i want to create a custom id.
example:
before =
user_id = 10/
after =
user_id = 10
It looks like your input field for user_id includes the slash, so I assume you get the slash in your PHP code as well.
I recommend you to go step-by-step when issues like this occurs. You know the value that is causing issues, so follow it down to where you notice the error and you can usually find the cause. Often you will notice that it's the most simplest of things that are the cause of the issue, but they are also easily overlooked.
Also, since you include the user_id in the form itself you should beware that the user that looks at the page can edit it before submit, so you shouldn't trust that the hidden input is what you set it to be unless you have some sort of validation of it.
Related
I'm currently stuck trying to insert a particular type of user input into my MySQL database. I'm creating a form that allows the user to input Title, Requirements, Description, and PowerShell Script code into a database. I need to be able to then display the new input.
I started by converting all my $_POST data into htmlentities before inserting it and everything seemed to be working perfectly. All the short PowerShell scripts were inserting into the database and then displaying appropriately. But, when I tried to insert a long PowerShell script, it just left the table column blank.
// Create Insert SQL prepared statement
$insertSql = $pdoConn->prepare('INSERT INTO scripts (ScriptID, script_name, script_requirements, script_description, script_code) VALUES (NULL, :scriptName, :scriptRequirements, :scriptDescription, :scriptCode)');
// Create htmlentity variable
$htmlName = htmlentities($_POST['scriptName']);
$htmlReq = htmlentities($_POST['scriptRequirements']);
$htmlDesc = htmlentities($_POST['scriptDescription']);
$htmlCode = htmlentities($_POST['scriptCode']);
// Execute Insert SQL prepared statement
$insertSql->execute(array(
'scriptName' => $htmlName,
'scriptRequirements' => $htmlReq,
'scriptDescription' => $htmlDesc,
'scriptCode' => $htmlCode));
// Display success message and page return
echo "New script uploaded successfully.<br>";
echo "<a href='newScript.html'>Upload another script</a><br><br>";
// Create new query to display new data
$displaySql = $pdoConn->prepare('SELECT * FROM scripts ORDER BY ScriptID DESC LIMIT 1');
// Execute SELECT query and display results
$displaySql->execute();
foreach ($displaySql as $row) {
echo "<button class='accordion'>
<h3>".$row['script_name']."</h3>
</button>
<div class='panel'>
<p class='requirements-p'>Requirements: ".$row['script_requirements']."</p>
<p id='description-p'><span>Description: </span>".$row['script_description']."</p>
<code>".$row['script_code']."</code>
</div>";
}
The form I'm using to upload data looks like this:
<article id="main-article">
<h1>Add New Script</h1>
<div id="form-envelope-div">
<div id="envelope-inner-div">
<form id="script-form" action="uploadNewScript.php" method="post" enctype="multipart/form-data">
<div id="script-div">
<label class="input_label">Title: </label>
<input class="text_input" id="title-input" type="text" placeholder="Title *" name="scriptName" required>
<label class="input_label">Requirements: </label>
<textarea class="textarea_input" id="requirements-textarea" placeholder="Requirements *" rows="10" cols="30" name="scriptRequirements" required></textarea>
<label class="input_label">Description: </label>
<textarea class="textarea_input" id="description-textarea" placeholder="Description *" rows="10" cols="30" name="scriptDescription" required></textarea>
<label class="input_label">Script: </label>
<textarea class="textarea_input" id="code-textarea" placeholder="Script *" rows="10" cols="30" name="scriptCode" required></textarea>
</div>
<div id="submit-div">
<input id="button-input" type="submit" name="submit_btn" value="Upload New Property">
</div>
</form>
</div>
</div>
</article>
Here are two examples of the user input. The first example script is short and has no problem inserting into the database. Example 1:
Name: SSL CSR Requests
Requirements: PowerShell v3 and up.
Description: This uses PS to return all CSRs generated on the server as well as the Creation Date.
Code: Get-ChildItem cert:\LocalMachine\REQUEST\ | Sort-Object -Property Subject | fl Subject,#{n='Creation Date';e={$_.'geteffectivedatestring'()}}
The second example script is much more complex and will not insert at all if I use htmlentites. If I try skipping htmlentities and insert directly from $_POST, it will only insert the beginning: $source = Also, when I inserted the script directly into the database using PhpMyAdmin, I had no problems whatsoever. It even display in HTML correctly. Example 2 Code input:
$source = “C:\inetpub\logs\LogFiles\”
$destination = "E:\IISLogBackups_$(Get-Date -format M).zip"
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($source, $destination)
$logs = ls –Path “C:\inetpub\logs\LogFiles\*” –Recurse | Where-Object{$_.LastWriteTime –lt (Get-Date).AddDays(-14)}
$logs | Remove-Item
After a LOT of debugging, I finally figured out how to solve my problem. For whatever reason, the $_POST variable for the textarea field was having a problem reading the hyphens in the user input. Once the input reached the $_POST variable, it was already too late to fix the problem using htmlentities or any equivalent PHP function. So, I created a JavaScript function that automatically replaces all the hyphens with the HTML entity ” before the user input is submitted. Here's what that JavaScript looks like:
document.getElementById('code-textarea').value.replace('-', '–');
I am having trouble thinking out a good way to update my query depending on user $_POST values. Basically I have user management search button, where site administrator can search for his sites users. In my example:
<div id="website_user_management_search_left">
<div id="website_user_management_search_left_leftside">
<p>Name:</p>
<p>Surname:</p>
<p>Telephone:</p>
<p>Group:</p>
<p>Discount group:</p>
</div>
<div id="website_user_management_search_left_rightside">
<input type="text" name="#" value="#" id="userSearch_name">
<input type="text" name="#" value="#" id="userSearch_surname">
<input type="text" name="#" value="#">
<input type="text" name="#" value="#">
<input type="text" name="#" value="#">
<input type="submit" id="button_adminUserSearch" value="Search">
</div>
Then after pressing "Search" button AJAX sends request to retrieve results, but how can I handle this dynamic query?
For example - if user just presses "Search" query would look like:
mysqli_query($dbconnect,"SELECT * FROM accounts");
For example - if user specifys $_POST["name"] value, query would look like:
mysqli_query($dbconnect,"SELECT * FROM accounts WHERE name='".$_POST["name"]."'");
Problem is - how can I efficiently handle this kind of query? It would be dumb to check which values is "isSet" and then make tons of query cases.
I hope you understood my problem and can help out with it, because it`s kinda hard to explain it.
Maybe you're looking for something like it :
if(empty($_POST['name'])) {
$name = null;
} else $name = $_POST['name'];
Then in your statement, your condition would be :
WHERE (name=:name OR :name is null)
If name isset, it will search for this name, else it will return true and query will not be affected
You could do something like that:
mysqli_query($dbconnect,"SELECT * FROM accounts WHERE name LIKE'%".$_POST["name"]."%'");
But there are two little problems:
You don't have escaped your user input data with mysqli_escape_string() and:
You shouldn't do that. A better way would be to add a where clause only, if name POST data is set:
$where = '';
if ($_POST['name']) {
$where = ' WHERE name = '".$name."'"';
}
mysqli_query($dbconnect,"SELECT * FROM accounts" . $where);
( Just a fun little experiment for my first website )
So this part works fine, it receives the information that is inputted from the form on another page. It adds to the "user" table in which consists of 'user', 'pass' (which are added from this given php code) and also 'ID' which auto increments upon adding to the table and then
'screen_name' and 'email' which I want to further add to the given table via another form.
<?
session_start();
include('dbconn.php');
$username = $_POST['user'];
$password = $_POST['pass'];
$sql = "INSERT INTO `user`(`user`, `pass`) VALUES ('".$username."','".$password."')";
$run = mysql_query($sql);
if($run){
$_SESSION['username'] = $username;
}
?>
This part of the code asks for an email address and a screen name which will be then further stored within the database, however I would like it to add to the specific user's information. As 'user' and 'pass' are already saved, the idea is to further then add 'screen_name' and 'email' to that specific user. Not sure what i've done wrong here. Also each time I refresh the page a blank user is added to a field in the database.
<form id="contact-form" method="post">
<div>
<label>
<span>Userame/Screen Name:</span>
<input placeholder="Please enter your name" name="screen_name" type="text" tabindex="1" required autofocus>
</label>
</div>
<div>
<label>
<span>Email:</span>
<input placeholder="Please enter your email address" name="email" type="email" tabindex="2" required>
</label>
</div>
<div>
<button name="submit" type="submit" id="contact-submit" data-text="...Sending">Submit</button>
</div>
<input type="hidden" name="user" value="<?php echo $_POST['user']; ?> />
</form>
Here is the code which is connected to the above form, it is on the same page and for some reason I am having trouble getting it to even add to any fields within the database let alone the one that is already active for the new user.
<?php
session_start();
include('dbconn.php');
$screen_name = $_POST['screen_name'];
$email = $_POST['email'];
$sql = "UPDATE `user` SET `screen_name` = '$screen_name', `email` = '$email' WHERE user = $username";
$run = mysql_query($sql);
?>
Any help would be more than appreciated. Not usually a guy who asks for help but as being stuck on this problem for ages and looking through multiple Stackoverflow posts, thought I'd add my own question!
It seems that in your second php script you don't initialize $username.
You should probably add $username = $_SESSION['username'];
Also you need to put quotes around it in your query.
About the blank users being inserted on page refresh, my guess would be that the first php script gets executed, but the $_POST variable isn't set.
Finally you should read up on SQL injection http://php.net/manual/en/security.database.sql-injection.php
I'm creating a php-post form, containing: Who, What, Where, Contact and date_created.
I've made a database with these rows.
Here's my HTML Form code:
<form id="contactform" action="post.php">
<p class="contact"><label for="who">Who</label></p>
<input id="who" name="who" placeholder="Who are you? (First & Second name)" required="" tabindex="1" type="text">
<p class="contact"><label for="email">What</label></p>
<input id="what" name="what" placeholder="What do you want?" required="" type="text">
<p class="contact"><label for="username">Where</label></p>
<input id="where" name="where" placeholder="Country, City, Street..." required="" tabindex="2" type="text">
<p class="contact"><label for="password">Contact</label></p>
<input type="text" id="contact" name="contact" placeholder="Phone number or email"required="">
<br><br>
<input class="buttom" name="submit" id="submit" tabindex="5" value="Submit" type="submit">
And here's the php post.php code:
<?php
// Grab our POSTed form values
// Note that whatever is enclosed by $_POST[""] matches the form input elements
$who = $_POST["who"];
$what = $_POST["what"];
$where = $_POST["where"];
$contact = $_POST["contact"];
// Connect to our DB with mysql_connect(<server>, <username>, <password>)
$sql_connection = mysql_connect("server_name", "admin", "password");
mysql_select_db("database_name", $sql_connection);
$sql = "INSERT INTO content (
who,
what,
where,
contact,
date_created
)
VALUES (
'$who',
'$what',
'$where',
'$contact',
NOW()
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
?>
When I try to post something, nothing is happening. The screen is just white, the database is empty and the url is like this:
http://my-website.com/post.php?who=Firstname+Secondname&what=Some+sentences+here-and&where=America&contact=some#website.com&submit=Submit%21
Just as HamZa DzCyberDeV said, you didn't specify which method you're using in <form> tag.
For situations when you're POSTing something in your database, just as you are now - use method="post" and for forms when you're searching for something, use method="get".
In case of using post method, your URL will change to only my-website.com/post.php and in case of using get method, your URL will change to something like my-website.com/post.php?... (where your things which you're getting are going) - just how you got URL after submitting.
The screen is just white because post.php (where you're going after clicking on submit button) doesn't contain anything to send to output, which you can easily do with echo.
For instance, you can make a new html page which will be written down with echo:
echo '
<html
<body>
This is my website!
</body>
</html>
';
Also, what you could do is to use include() php script which has already formed HTML, or you can check out here for some other redirect methods:
http://php.about.com/od/learnphp/ht/phpredirection.htm
Just remember that PHP is language which server is processing and only HTML tags (with CSS and JS) are sent to other browser to be read.
For more about POST and GET method you can read here:
http://php.net/manual/en/reserved.variables.post.php
http://php.net/manual/en/reserved.variables.get.php
why don't you try this to get an error or a clue to what is going wrong, enclose your code in try and catch blocks:
try {
// your code
} catch ( Exception $e ) {
echo $e->getMessage();
}
I am currently building a multiple pages form using $_SESSION, everything has been working fine so far. Yet, even though I am able to retrieve all the data at the end of the 6 pages, it seems that it is not possible to go back in the form if the user made a mistake.
Let's say he is at page 5 and he realizes that he needs to go back to page 3 to change something, he won't be able to do so. Firefox gives this error message :
Document Expired
This document is no longer available.
The requested document is not available in Firefox's cache.As a security precaution, Firefox does not automatically re-request sensitive documents.Click Try Again to re-request the document from the website.
This is what my forms look like, this one is Form-1.php :
<form action="Form-2.php" method="post">
<fieldset>
<legend>Information</legend>
<p>
<label for="name">Name</label>
<input id="name" type="text" name="name" required/>
</p>
<p>
<label for="age">Age</label>
<input id="age" type="number" name="age" placeholder="Ex. 1988" required/>
</p>
<p>
<input id="sex-m" type="radio" name="sex" value="Male" required/>
<label for="sex-m">Male</label>
<input id="sex-f" type="radio" name="sex" value="Female" required/>
<label for="sex-f">Female</label>
</p>
</fieldset>
<input type="submit" value="Next page"/>
</form>
I am using SESSION to retrieve data from the previous form, this one is from Form-2.php :
session_start();
$_SESSION['name'] = $_POST['name'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['sex'] = $_POST['sex'];
And so on for the six pages.
It works fine, it retrieves all the values correctly, but it is not possible to go back when filling the form.
What am I doing wrong? How can I make sure the user will be able to go back if he makes a mistake?
Thanks for your help.
EDIT :
I ended up with the following code, solving half of my problem. Still from Form-2.php :
session_start();
if (isset($_SESSION['location']) && isset($_SESSION['job'])) {
$location = $_SESSION['location'];
$job = $_SESSION['job'];
} else {
$_SESSION['name'] = $_POST['name'];
$_SESSION['age'] = $_POST['age'];
$_SESSION['sex'] = $_POST['sex'];
$location = '';
$job = '';
}
Then I simply display the values in the fields with :
If text : <?php echo $location; ?>
If radio : <?php if(isset($job) && $job == "Yes"){echo "checked=\"checked\" ";} ?>
It works quite well, the different forms - if the values have been set - are pre-populated just fine.
My problem is, as you can see, if I go back and change a value, it won't be taken into consideration as I am ignoring POST if there is a corresponding value stored in SESSION.
I can't figure out how to make this work properly... Any hint?
Not the best solution, but does the job: Do not use back buttons, provide your own forward, backwards, "step" buttons. Then populate the form with the data stored in e.g. the session.
djot is right, you need a << back >> and << forward >> button, what you can do in functionality is if back button is clicked pass the values of the page/form as hidden input fields and populate the fields using the values in the hidden..