Editing HTML then posting via PHP - php

I have a scenario. Let's say someone is on my website and there is a form which adds an event for example and there is a field as follows:
<input type="text" name="title" id="title">
Let's say that person used F12 developer tools and changes the id="title" to id="whatever", or even remove the id attribute, then how would I make my PHP script stop running so that nothing is posted to MySQL?
Here's an example for a Bookmarks feature I have: (front-end form)
<form action="bookmarks.php" method="post" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label" for="input-mini">Title*</label>
<div class="controls">
<input class="span12" id="title" name="title" type="text" placeholder="e.g. Oliver's pet cat...">
</div>
</div><!-- /control-group -->
<div class="control-group">
<label class="control-label" for="input-mini">Link*</label>
<div class="controls">
<input class="span12" id="link" name="link" type="text" placeholder="e.g. http://boopeo.com">
<input type="hidden" name="parse_var" id="parse_var" value="addbookmark" />
<br /><input name="submit" type="submit" class="btn btn-success span12" value="Bookmark" /></form>
Back-end PHP:
if (isset($_POST['parse_var'])){
$parser = $_POST['parse_var'];
$parser = htmlspecialchars($parser);
if ($parser == "addbookmark"){
$title = $_POST['title'];
$title = htmlspecialchars($title);
$linkurl = $_POST['link'];
$linkurl = htmlspecialchars($linkurl);
$sqlrecentmark = $db->query("SELECT link_url FROM tablenamehere WHERE mem_id='$id' ORDER BY id DESC LIMIT 20");
while($row = $sqlrecentmark->fetch(PDO::FETCH_ASSOC)) {
$recent_link = $row["link_url"];
}
if ( $linkurl != $recent_link ){
$dataact = array( 'mem_id' => $id, 'title' => $title, 'link_url' => $linkurl );
$sqlactivity = $db->prepare("INSERT INTO tablenamehere (mem_id, title, link_url) value (:mem_id, :title, :link_url)");
$sqlactivity->execute($dataact);
} else {
$not_msg = '<br /><br /><div class="alert alert-error">Oops! You have added that bookmark before. Just look and you shall find!</div>';
}
}
}

Never trust data from the user. Always sanitize and validate. You are using prepared statements which is good, so you'll be mostly protected from injection. The other thing you'll want to do is determine if the data the user has sent you matches up with what you were expecting, if it does then proceed to use it with the database. (Which you are for the most part doing, so in all honesty there should be no bad effects from a malicious user)

The id of input field doesn't get passed as posted data, so there's no way to tell in the back-end php code. Maybe you're talking about the name attribute.
<input type="text" name="theTitle" id="aTitle">
In my above example, the input field will be posted as $_POST["theTitle"]
You could use javascript to check these elements before the form is submitted, but if you're worried about the user manipulating the DOM, that probably won't help much.
After reading your concern about the Undefined index error, you simply need to check if the variable is set before you use it:
if(isset($_POST["title"])) {
$title = $_POST['title'];
} else {
//output error
}

Related

PHP: MSSQL Query for multiple fields on one page

I am new to PHP, and have a web form, that I am using PHP to get data from the database. What I have currently done, as I havent been able to find out another solution to do so (despite my searching - probably dont know the correct terms to look for), is individually executing a SQL Query for each input field on my form.
As below:
<div class="search-line">
<div class="search-option">
<label>Asset Tag:<i title=""></i></label>
<?php
$asset_tag_sql = "SELECT HardwareAsset.HardwareAssetAssetTag FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";
$asset_tag = sqlsrv_query($database_connection, $asset_tag_sql);
?>
<input type="text" id="AssetTag" disabled value="<?php while ($asset_tag_option = sqlsrv_fetch_object($asset_tag)){echo $asset_tag_option->HardwareAssetAssetTag;} ?>" />
</div>
<div class="search-option">
<label>Serial Number:<i title=""></i></label>
<?php
$serial_number_sql = "SELECT HardwareAsset.HardwareAssetSerialNumber FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";
$serial_number = sqlsrv_query($database_connection, $serial_number_sql);
?>
<input type="text" id="SerialNumber" disabled value="<?php while ($serial_number_option = sqlsrv_fetch_object($serial_number)){echo $serial_number_option->HardwareAssetSerialNumber;} ?>" />
</div>
</div>
Is there anyway to have one PHP piece of code to do one SQL query and then use that to fetch and echo the value for both input fields, as opposed to the two above?
Try it like this?
<?php
$asset_sql = "SELECT HardwareAsset.HardwareAssetAssetTag,HardwareAsset.HardwareAssetSerialNumber FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'"
$asset_result = sqlsrv_query($database_connection, $asset_sql);
$asset_data = sqlsrv_fetch_object($asset_result);
?>
<div class="search-line">
<div class="search-option">
<label>Asset Tag:<i title=""></i></label>
<input type="text" id="AssetTag" disabled value="<?php echo $asset_data->HardwareAssetAssetTag; ?>" />
</div>
<div class="search-option">
<label>Serial Number:<i title=""></i></label>
<input type="text" id="SerialNumber" disabled value="<?php echo $asset_data->HardwareAssetSerialNumber; ?>" />
</div>
</div>
Why not just select two fields from the initial query like this:
$serial_number_sql = "SELECT HardwareAsset.HardwareAssetSerialNumber,
HardwareAsset.HardwareAssetAssetTag FROM HardwareAsset WHERE
HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";

PHP - Insert elemens into an array

I'm working on a formular, but for the moment I just want to insert into an array my elements (I have books and authors).
I can display my books with author (name + surname) with the foreach, but I can't add more elements.
Here is the code with the form.
<H1>Exercice 2</H1>
<form method="POST">
<label for"code" >Number :</label>
<input id="code" name="code" type="number" />
<label for"title">Title :</label>
<input id="title" name="title" type="text" />
<label for"author" >Author :</label>
<input id="author" name="author" type="text" />
<button type="input" type="submit">Ok</button>
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = array();
$book['code'] = 123;
$book['title'] = "Legendes";
$book['author'] = array("David", "Gemmel");
foreach($book as $value){
$book['key'] = $value;
var_dump($book);
if (is_array($value)) {
foreach($value as $otherValue) {
echo($otherValue);
}
} else {
echo($value);
}
}
I did some searcch, but I don't think it works, it's using the array_push() method with the POST, but I don't know where I can manipulate my form into the array.
If you want some details, I'll be happy to do that =) I'm working on it, if i have some news, you will know =)
Have a nice day =)
1) Assignments are in reverse. Correct way:
$myVar = $myValue
2) You need to set the name attribute in your inputs in order to be sent:
<input id="code" type="number" name="code" />
Then you can access them like:
$_POST['code']
3) To add an element by key in an array, use:
$array['key'] = $value;
Your Exercise 2 have some mistakes :
First, your HTML inputs must have the name attribute to be retrieved by post:
<h1>Exercice 2</h1>
<form method="post">
<label>
<input name="code" type="number" />
</label>
<button type="submit">Ok</button>
</form>
With PHP, you can access to any input value using the name:
$code = $_POST['code'];
Now, I think you want to "add" several books using this HTML form without a storage system. The problem is you can not do this if for every a new request since all the elements you have in your array will be deleted each time you run a new post request. To keep this information you need to use some persistent storage system as a database or others.
Since you seem to want to keep the information for each book together, you need to use a multidimensional array - hence, you'll need to redo the whole thing. Here's a suggestion:
Form:
<h2>Exercice 2</h2>
<form method="post">
<label for"code">Number :</label>
<input id="code" name="code" type="number">
<label for"title">Title :</label>
<input id="title" name="title" type="text">
<label for"author-firstname">Author First Name:</label>
<input id="author-firstname" name="author-firstname" type="text">
<label for "author-lastname">Author Last Name:</label>
<input id="author-lastname" name="author-lastname" type="text">
<input type="submit" name="submit_book" value="Ok">
</form>
Fixed the name-problems, changed the heading (you never, ever use H1 for a form, H1 is strictly used for the site-wide heading/logo/name of site). Also changed the button into a simple input type="submit".
$title = $_POST['title'];
$code = $_POST['code'];
$author = $_POST['author'];
$book = []; // changed this to modern PHP version array assignment
$book[0]['code'] = 123;
$book[0]['title'] = "Legendes";
$book[0]['author-firstname'] = "David";
$book[0]['author-lastname'] = "Gemmel"; // no reason to assign a separate array for first and last name, just use two array-keys
for ($c = 0; $c <= count($book); $c++) { //changed this to a for, counting the amount of entries in the $book array
echo 'Title: '.$book[$c]['title'];
echo 'Author: '.$book[$c]['author-firstname'].' '.$book[$c]['author-lastname'];
} // the content should probably be wrapped in a container of some sort, probably a <li> (and then a <ul>-list declared before the for-loop)
Now. None of this has anything to do with putting stuff INTO the array. That would be something like this (there isn't even a point of assigning the $_POST-variables for the code you posted. But, you can do something like this:
if (isset($_POST['submit_book'])) {
$title = $_POST['title'];
$code = $_POST['code'];
$author-firstname = $_POST['author-firstname'];
$author-lastname = $_POST['author-lastname'];
// however, if all you're doing is putting this into the array, no need to assigne the $_POST to variables, you can just do this:
$temp_array = ['code'=>$_POST['code'],'title'=>$_POST['title'],'author-firstname'=>$_POST['author-firstname'],'author-lastname'=>$_POST['author-lastname']];
$book[] = $temp_array;
}
So, that would replace the assigned variables at the beginning of your code.

How to insert mutliple records into mysql using foreach output?

I have a small app where the user adds 3-4 ticket in a single Form via the 'Add Another Ticket' button. These text boxes are generated via Jquery .append() and each ticket has 5 input boxes in it. Code Below
<form action="ticket-addcode.php" method="post" enctype="multipart/form-data" class="my-form">
<span id="tixmegaform">
<input type="hidden" name="Eventid" value="<?php echo $eventid; ?>" />
<div class="AddRow">
<label>Package Name</label>
<input class="requierd" type="text" name="ticketgroup" placeholder="Enter the Package Name. Most Preferably Event name" id="EN" value="<?php echo $ticketgroup; ?>">
</div>
<h5>Ticket 1</h5>
<div class="AddRow">
<label>Ticket Title</label>
<input class="requierd" type="text" name="tname[]" placeholder="Enter the Package Name. Most Preferably Event name" id="EN">
</div>
<div class="AddRow">
<label>Ticket Desc</label>
<input class="requierd" type="text" name="tdesc[]" placeholder="Enter the Details" id="EN">
</div>
<div class="AddRow">
<label>Ticket Cost</label>
<input class="requierd" type="text" name="tprice[]" placeholder="Enter the ticket Cost in Numbers. No Currency" id="EN">
</div>
<div class="AddRow">
<label>Ticket Book URL</label>
<input class="requierd" type="text" name="turl[]" placeholder="Enter the URL without http" id="EN">
</div>
<div class="AddRow">
<label>Time</label>
<input type="text" class="left requierd" name="eventTime[]" id="timeformatExample1" placeholder="Start">
</div>
<div class="AddRow">
<label>Date</label>
<input class="requierd" type="text" name="tdate[]" placeholder="Enter the Package Name. Most Preferably Event name" id="from">
</div>
</span>
<input type="submit" name="submit" class="add_field_button_submit">
</form>
</div>
</div>
</div>
<div class="add_field_button">Add Another Ticket</div>
</div>
So, when I hit the Submit button, a nested foreach runs through an array generated by the submit button. I'm able to fetch the values out of the array but somehow the output is not useful to me. Below is the foreach & the output
foreach ($_POST as $pos => $newarr) {
foreach($newarr as $res => $final){
echo $pos.'-----'.$final.'<br>';
}
}
Output
**tname-----VIP tix
tdesc-----Early Bird Desc
tdesc-----VIP Desc Tix
tprice-----5000
tprice-----10000
turl-----google.com
turl-----yahoo.com
eventTime-----00:30:00
eventTime-----00:00:45
tdate-----2-2-2016
tdate-----3-3-2016**
I tried to use an Insert Statement, but it just won't work. It seems that my foreach is resolving the sub array (tname array) and the outer array. If my foreach could just fetch values of different key and not the entire subarray, I would be able to insert the record into db.
Can you guide me on how to achieve this and where to put the INSERT Statement?
I don't think looping over $_POST as you have done will do you any good. Notice how the order of your information coming out makes it difficult?
Instead pick any of your array fields to determine first the number of tickets you have. Then use the number of tickets for iterating over each ticket. This way you can get the index of each group (ticket) of related information together. With the index, you can get all the information related for the group.
Once you have the necessary information, you can either store each information by doing one insert at a time or by doing one big insert. For simplicity, we shall use the former approach (using PDO).
Below is a rough and untested sketch of how it might look:
try {
$dbh = new PDO($dsn, $user, $password);
// prepare your SQL statement
$sth = $dbh->prepare("INSERT INTO table (title, desc, price, url) VALUES(?, ?, ?, ?)");
// loop over each ticket information
for ($i = 0, $numTickets = count($_POST['tname']); $i < $numTickets; $i++) {
$title = $_POST['tname'][$i];
$desc = $_POST['tdesc'][$i];
$price = $_POST['tprice'][$i];
$url = $_POST['turl'][$i];
// insert information into database
$sth->execute(array($title, $desc, $price, $url));
}
} catch (PDOException $e) {
// if something goes wrong, add some logic
}
For more information on PDO, read the documentation.
Use below format of SQL for insertion:
Example:
INSERT INTO tbl_name
(a,b,c)
VALUE (7,8,9);
As per your code:
$sql01 = "INSERT INTO tbl_name (tname,tdesc,tprice, turl) VALUES ";
foreach ($_POST as $pos => $newarr) {
$sql01 .= "(";
$sql01 .= isset($_POST['tname'])?array_merge($_POST['tname'],","):"";
$sql01 .= isset($_POST['tdesc'])?array_merge($_POST['tdesc'],","):"";
$sql01 .= isset($_POST['tprice'])?array_merge($_POST['tprice'],","):"";
$sql01 .= isset($_POST['turl'])?array_merge($_POST['turl'],","):"";
$sql01 .= ")";
}
mysql_query($sql01);

Add Update And Delete Button In Retrieved Data From SQL Using PHP

I am retrieving data from SQL using PHP on a page and showing many records at a time using below code.
<?php
//Database Connection File
require_once("config.php");
//Everything Is Okay So Let's Garb This User Contacts Data
$garb = mysqli_query($connection, "SELECT * FROM contacts WHERE A_Id = '$A_Id'");
if(!$garb){
$error = "<div class='error'>There's Little Problem: ".mysql_error()."</div>";
} else {
//Data Is Collected
//Showing The User Data
$idNo = 0;
while($row = mysqli_fetch_array($garb)) {
$C_FullName = $row['C_FullName'];
$C_Gender = $row['C_Gender'];
$C_ContactPhone = $row['C_ContactPhone'];
$C_ContactCell = $row['C_ContactCell'];
$C_Email = $row['C_Email'];
$C_Address = $row['C_Address'];
$C_Group = $row['C_Group'];
$C_Notes = $row['C_Notes'];
echo '
<div class="accordionItem close">
<h3 class="accordionItemHeading">'.$C_FullName.'</h3>
<div class="accordionItemContent">
<div id="contactDetailes">
<form id="updateAllContact'.$idNo.'" method="post" action="">
<p><label>Full Name:* </label><input type="text" name="C_FullName" value="'.$C_FullName.'"></input></p>
<p><label>Gender:* </label><input type="text" name="C_Gender" value="'.$C_Gender.'"></input></p>
<p><label>Contact No(Phone): </label><input type="text" name="C_ContactPhone" value="'.$C_ContactPhone.'"></input></p>
<p><label>Contact No(Cell): </label><input type="text" name="C_ContactCell" value="'.$C_ContactCell.'"></input></p>
<p><label>Email Address:* </label><input type="text" name="C_Email" value="'.$C_Email.'"></input></p>
<p><label>Address: </label><input type="text" name="C_Address" value="'.$C_Address.'"></input></p>
<p><label>Group: </label><input type="text" name="C_Group" value="'.$C_Group.'"></input></p>
<p><label>Notes: </label><textarea type="text" name="C_Notes">'.$C_Notes.'</textarea></p>
<span>
<a class="updateButton">Update</a>
<a class="deleteButton">Delete</a>
</span>
</form>
</div>
</div>
</div>
';
$idNo++;
}
}
?>
Now the problem is that I want to add Update and Delete function for every row retrieved from database. What I want is something like HTML5 Web SQL Databases And Usage or something like HTML5 Address Book using PHP and SQL. So how can I add functions of Update and Delete in my every row data...???

populating text fields from the sql using dropdown list Jquery

Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.

Categories