How to allow user to insert hierarchical numbering like below. As for now, i'm using textbox and user will enter the number such as 1, 1.1, 2, 2.1, 2.1.1. And I can only display the data plainly, with no indent. I'm using PHP and MySql as database.
1 List item
1.1 List item
1.1.1 List item
2 List item
2.1 List item
2.1.1 List item
My form.
<form action="basicview.php?id=<?php echo $p_aid; ?>&&do=insert" method="post">
<div style="padding-bottom:5px">
<div style="float:left;width:5%;padding-top:7px"><label style="color:blue">No</label></div>
<div style="float:left;"><input class="text-input" type="text" name="t_no" size="10" value="" /></div>
<div class="clear"></div>
</div>
<div style="padding-bottom:5px">
<div style="float:left;width:15%;padding-top:7px"><label style="color:blue">Deliverables</label></div>
<div style="float:left;"><textarea class="text-input textarea" name="t_deliverables" cols="70" rows="2"></textarea></div>
<div class="clear"></div>
</div>
PHP.
if ($_GET['do'] == 'insert')
{
$t_no = $_POST['t_no'];
$t_deliverables = $_POST['t_deliverables'];
$sql = "INSERT INTO tbl_detail (p_aid,t_no,t_deliverables) ";
$sql .= "VALUES ($p_aid,'$t_no','$t_deliverables')";
mysql_query($sql);
redirect("basicview.php?id=$p_aid&type=success&msg=new+row+added");
}
If you want the users be able to post html data rather than plain text, you may use ckeditor or other similar tools. these tools convert textarea to a box like this one in stackoverflow.
But bear in mind that to prevent XSS attacks, you must verify posted data in server-side.
More importantly, the way you have scribed your sql query, it is highly vulnerable to sql injection. use prepared statements instead. For example if a malicious user post these data, you lose all data in the tbl_detail table:
$_POST['t_no']="1"
$_POST['t_deliverables']="1'); drop table tbl_detail;--"
Related
I have looked everywhere so I apologize if there's an answer to this already, I couldn't find it after hours of searching. Maybe it's not a good way to do it either...
I have a form that has "picks" of a litter, so 1st pick, 2nd pick, 3rd pick, etc. These picks also have genders (Female, Male)
I use a foreach query to grab the available pick spots. If someone isn't assigned to that pick spot, then the input field is enabled for manual typing
Within that foreach query, I need to somehow submit what pick it is and what gender, as well as the typed value, so I can find the pick and store it to the database... The other problem is, it's dynamic where someone may type in 3 input fields, or other times just 1 input field. Basically it'll show 3 input fields and the user can choose to use all 3 or just 1...
No matter what I've tried, it doesn't work. I don't even have my examples because I've tried everything I could find and had to scrap it all
The input, this is for males only but females are the same:
<?php
foreach ($malespickedquery as $pick){
$picktaken=$pick['user_id'];
$pickcustom=$pick['custom_name'];
$pickposition=$pick['pick_id'];
$suffix=ordinal($pickposition);
?>
<div class="form-row pb-3">
<div class="col-12">
<label class="control-label"><?php echo $pickposition.$suffix." Pick "; ?>Male:</label>
<?php if($pickcustom==true){ ?>
<input type="text" name="" class="form-control" value="<?php echo $pickcustom; ?>" />
<?php }elseif($picktaken!="0"){ ?>
<input type="text" name="" class="form-control" value="<?php echo $pick['public_name']; ?>" disabled />
<?php }else{ ?>
<input type="text" name="malepicks[<?php echo $pickposition; ?>][male][]" class="form-control" value="" />
<?php } ?>
</div>
</div>
<?php } ?>
I've tried foreach within foreach, but can never get all information. Most things just return the last input field as well... So if 3 of them are generated, the last input field would come through but not the others. I also did something with foreach where it returned ALL of the fields, even blank ones, which just got confusing and still didn't work right
Thank you in advance!
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('-', '–');
Hey Fellow Programmers,
I have a slight problem and I cant find the right answer online.
Basically what I need to do is, a user inserts content into a text box and then selects a check box. Whichever check box is selected is what table the text box content is supposed to insert into. **Both check boxes can be selected so the user can upload to two diff tables, before you ask no I cannot just upload to a diff row it has to be a completely diff table.
Let me know if I am not clear, and thanks in advance
HTML CODE:
<body class="login">
<div class="wrapper">
<h1><img src="img/logo-big.png" alt="" class='retina-ready' width="59" height="49">FLAT</h1>
<div class="login-body">
<form action="db_pre_panel.php" name="login" class='form-validate' id="test" method="post">
<div class="control-group">
<div class="email controls">
<h3>TEST</h3>
<input type="text" name="content" maxlength="500" placeholder="Content" />
</div>
</div>
<div class="control-group">
<input type="checkbox" name="Ck_1" /> <label>Ck_1</label>//If selected then INSERT content into tbl_connect
<input type="checkbox" name="Ck_2" /> <label>Ck_2</label>//If selected then INSERT content into tbl_share
</div>
<div class="submit">
<input type="submit" value="Simplicity" />
</div>
PHP CODE:
<?php
//Define Content, Post & Share
$content=$_POST['content'];
$post=$_POST['ck_1'];
$share=$_POST['ck_2'];
//Insert into the db
$sql_post="INSERT INTO $tbl_connect (wall) VALUES ('$connect', '$post')";
$sql_share="INSERT INTO $tbl_share (wall) VALUES ('$connect', '$share')";
//Make sure it insert into db
$result_post = mysql_query($sql_post);
$result_share = mysql_query($sql_share);
if($result_post){
header("location:alert.php");
}else{
header("location:error.html");
}
if($result_share){
header("location:http://www.google.com");
}else{
header("location:error.html");
}
?>
Just keep it simple:
//Define Content, Post & Share
$content = $_POST['content']; // you should sanitize this to prevent SQL injection
if ( !empty($_POST['ck_1']) ) {
$sql_post = "INSERT INTO `tbl_connect` (wall) VALUES ('$connect')"; // if you have more than one value, then you need to specify more than one column...
}
if ( !empty($_POST['ck_2']) ) {
$sql_share = "INSERT INTO `tbl_share` (wall) VALUES ('$connect')";
}
I am planning to develop a student progress card application using jQuery Mobile and PHP with MySQL database as the back end. This is mainly used by teachers to record the marks of the exam papers they have corrected in the database.
I have a list of students in studentlist.php and a Score Sheet with various subject mark entries in scoresheet.php (Shown Below)
The list of students is extracted from the MySQL db into studentlist.php
Clicking on a list item (say 'Student1') takes you to scoresheet.php.
All the entries made in scoresheet.php needs to be saved in the database for Student 1.
I was wondering, if I can create a value for each list item and pass that variable to scoresheet.php using sessions.
Can some one please help me with a simple example?
Student list will look something similar to this: http://jquerymobile.com/test/docs/lists/lists-divider.html
Scoresheet.php will look something like this:
Student Score Card List
<body>
<div data-role="page" id="page">
<div data-role="header">
Dashboard
<h4> Contractor's List </h4>
</div>
<div data-role="content">
<div data-role="fieldcontain">
<ul data-role="listview" data-inset="true">
<li> <label for="slider-2">Subject1</label>
<input type="range" name="subject1" id="subject1" value="0" min="1" max="10" />
</li>
<li> <label for="slider-2">Subject2</label>
<input type="range" name="subject2" id="subject1" value="0" min="1" max="10" />
</li>
</ul>
</div>
</div>
<div data-role="footer">
<h6>2012 © </h6>
</div>
</div>
</body>
A sample of what I've done by passing variables through URL:
studentlist.php:
<?Php
$sql= 'SELECT student_id, student_name FROM students';
$result=mysql_query($sql);
$num=mysql_num_rows($result);
echo $num;
?>
<div data-role="content">
<div data-role="fieldcontain" data-theme="b">
<ul data-role="listview" data-inset="true">
<li data-role="list-divider"> List of Contractors </li>
<?php
$i=0;
while ($i < $num) {
$f1=mysql_result($result,$i,"student_id");
$f2=mysql_result($result,$i,"student_name");
?>
<li>
<a href="scoresheet.php?id= <?Php echo $f1; ?> ">
<h3> <?Php echo $f2;?> </h3>
</a>
</li>
<?php
$i++;
}
?>
</div>
Now I'll use the variable 'id' in scoresheet.php to update a record in the table using a MySQL query.
Session data can also store more complex data types like multi-dimensional arrays. You could do something like:
$student_id = $_POST['student_id'];
$_SESSION['student_data'][$student_id]['subject_1'] = $_POST['subject_1'];
$_SESSION['student_data'][$student_id]['subject_2'] = $_POST['subject_2'];
Hope that helps.
If I understand your question, you have users that are assigned a Session Id. You would like to have a php script file receive Scoresheet updates that retain the Session Id information when making updates.
One easy way to handle it is to drop the session id value into the forms action url.
<form action="scoresheet.php?sessionId=<?php echo $_SESSION['sessionId']; ?>" id="formScoresheet">
However, if you are use the POST method, you may wish to doing something more elegant like placing the session id inside a hidden input.
<input type="hidden" id="sessionId" name="sessionId" value="<?php echo $_SESSION['sessionId']; ?>" />
Check out this example, maybe it will help - http://jsfiddle.net/shanabus/CbkpH/
This all seems a bit redundant though because your server should manage SESSION variables without having to pass them to the page and back. If you are looking for some basic PHP Session examples, you could start here. Basically you have to start the session on the initial request for the studenlist.php file then be sure to start session before using the values on scoresheet.php.
Ok so i have this javascript
function getpreconfigproducts(str1,str2)
{
var url="ajax_preconfig_products.php?";
url=url+"id="+str1+"&cid="+str2;
xmlHttp = GetXmlHttpObject(stateChangeHandler);
xmlHttp_Get(xmlHttp, url);
return false;
}
and it calls this php
<?php
if($_GET['id']!='')
{
$sql="SELECT * FROM productinfo WHERE ProductID=".$_GET['id']." AND Status=1";
$pro=ExecuteGetRows($sql);
?>
<p>Qty: <input type="input" name="qty[]" id="fpro[]" value="1" style="width:15px; margin-top:-3px;" /> <label><?php echo $pro[0]['ProductName'];?></label> </p>
<?php
echo "^_^";
echo ",".$pro[0]['ProductID'];
} ?>
which generates this
<div class="fields">
<h2>Final Products</h2>
<p id="finalproductsid">
<p>Qty: <input name="qty[]" id="fpro[]" value="1" style="width: 15px; margin-top: -3px;" type="input"> <label>FIREBOX S5510 15</label> </p>
<p>Qty: <input name="qty[]" id="fpro[]" value="1" style="width: 15px; margin-top: -3px;" type="input"> <label>FIREBOX S5510 15</label> </p>
</p>
</div>
The problem is that if a user changes the input qty[] to say 5 and adds another product it reverts back to 1 ...any ideas how i can address this
Aside from all the SQL injection stuff, mentioned already, I think I might know what your problem is. Tell me if I understand your script:
User clicks an 'add product' button
Button fires an AJAX request to the PHP script above
The PHP script generates some HTML
Somehow (?) the generated HTML gets displayed
The values of all of the other product fields in the form revert back to one
I'm assuming #4 is where the problem (#5) is occurring. Depending on how you append the HTML to the form, the input fields will sometimes revert. For instance:
//Reverts all form inputs to default-
myForm.innerHTML += "<input name='new_input'/>";
//Keeps current input values-
var newNode = document.createElement('input');
myForm.appendChild(newNode);
May I suggest, that instead of appending a string of HTML, you create the HTML with JavaScript, getting the product name/id through an AJAX request.
I don't quite understand how your script is working though. As far as my limited knowledge goes, the PHP isn't displaying onto the current page, but echoing to the AJAX's response text. Is there something more, or is it just me?
Re: Where is the sql injection?
This answer is in response to the OP's comment asking about the sql injection error.
Note the line:
$sql="SELECT * FROM productinfo WHERE ProductID=".$_GET['id']." AND Status=1";
The error is that the incoming HTML value for "id" is not properly escaped. You're expecting that it will contain an integer or nothing. But if a hacker sent something like
1;truncate users;select * from users where id=1 as the value of id, you'd end up with the sql statement:
$sql="SELECT * FROM productinfo WHERE ProductID=1;truncate users;select * from users where id=1 AND Status=1";
The right way is to ALWAYS ALWAYS ALWAYS properly escape or untaint any data coming in to the program. For Php MySQL dbms queries (manual):
$sql= sprintf("SELECT * FROM productinfo WHERE ProductID=%s AND Status=1",
mysql_real_escape_string($_GET['id']));
Notes:
For databases other than MySQL, there are other Php techniques. See the docs.