MSSQL: multiple INSERTs with PHP arrays and echoing back the data - php

I have a form with the following structure:
<input type="text" name="projNo[1]" id="projNo[1]" value="<?php echo $row['ProjNo'
[1];>"
/>
<input type="text" name="projBudget[1]" id="projBudget[1]" value="<?php echo
$row['ProjBudget'][1]; ?>" />
<input type="text" name="projDateFrom[1]" id="projDateFrom[1]" value="<?php echo
$row['ProjDateFrom'][1]; ?>" />
<input type="text" name="projDateTo[1]" id="projDateTo[1]" value="<?php echo
$row['ProjDateTo'][1]; ?>" />
<input type="text" name="projNo[2]" id="projNo[2]" value="<?php echo $row['ProjNo'
[2];>"
/>
<input type="text" name="projBudget[2]" id="projBudget[2]" value="<?php echo
$row['ProjBudget'][2]; ?>" />
<input type="text" name="projDateFrom[2]" id="projDateFrom[2]" value="<?php echo
$row['ProjDateFrom'][2]; ?>" />
<input type="text" name="projDateTo[2]" id="projDateTo[2]" value="<?php echo
$row['ProjDateTo'][2]; ?>" />
There are two more groups like this with indexes 3 and 4. Upon submit, four separate records must be created in the DB if the user has filled in all four lines. My question is twofold: How would I structure my query to accomplish this? And: Have I set up my code correctly? When the form is loaded, I would like the correct output to be displayed. I've never been confronted with a request like this before, so I'm flying a bit blind.

Use PDO and prepared statements. Prepare a statement like this:
$s = $db->prepare('INSERT INTO PROJECT (no, budget, from, to) VALUES (?,?,?,?)')
Execute the statement for each set like this:
for ($i = 1; $i<=4; $i++) {
$s->execute(array($projNo[$i], $projBudget[$i], $projDateFrom[$i], $projDateTo[$i]));
}
(You need to add error checking and validation. This includes something that loads the stuff from $_POST to the arrays I used in the above example.)
Currently, you have a XSS security issue in your code. You cannot just echo stuff that comes from the user - you need to escape it. If you are putting it inside HTML, including double-quoted attribute values like in your case, use echo htmlspecialchars($_GET[...]);.
You may want to create a "htmlout" function that does nothing else than echo htmlspecialchars, just to have a nicer, easier-to-write name for it, and use it everywhere. That way, you can search your code for instances of "echo", and unless you have protected them otherwise, this indicates you probably need to add some escaping.

Related

if isset breaking my php

I'm trying to build a SQL statement using variables that were posted on a previous page (show the SQL statement for copy-pasting in a div using echo), however, the one statement is preventing me from doing it.
<?php
if (isset($_POST['locationName'])) {
echo $_POST['locationName'];
}
?>
As soon as I've put that in, the page refuses to load. It doesn't make any sense to me as I've got similar code throughout the page for the other input fields (to repopulate them after form submission).
As an exmaple: this works perfectly:
<input type="checkbox" name="lead" value="1" <?php if(isset($_POST['lead'])) echo "checked='checked'"; ?> />Lead Required<br>
I've been trying to change the quote types, and tried using htmlspecialchars as well as htmlentities in the echo, but each time I leave the in statement in, it breaks the page.
As soon as I comment that if statement out, the page loads again.
Here's the input field for the $_POST['locationName'] value:
<input required autofocus type="text" pattern="[a-zA-Z0-9-'\s\!\#\*]+" name="locationName" maxlength="100" size="67" placeholder="Place Name" value="<?php echo isset($_POST['locationName']) ? $_POST['locationName'] : '' ?>" />
<input type="checkbox" name="lead" value="1" <?php if(isset($_POST['lead'])){echo "checked='checked'";} ?> />Lead Required<br>
try to use braces and check

Insert a value (which you don't type but is echo'ed) into database through php?

I am inserting a car mileage and car color into a database, on the same page I am displaying that cars ID and the cars owner.
So I have two input fields where the user types the mileage and color and beneath that I am just displaying that cars ID and the cars owner.
The insert works fine, I can insert the mileage and color but it leaves two columns where the cars ID and cars owner (which are displayed on the page where I enter mileage/color) should be...
Does anyone know of a way to put them into the DB too as im not actually typing them, simply echoing them there. Code is shown below, thanks.
Mileage:<input type="text" name="mileage"><br />
Color:<input type="text" name="Color"><br />
carID:<?php echo $cID; ?>
carOwner: <?php echo $cOwner; ?>
The insert page is just a simple sql statement which only has the mileage/color values . I have tried adding carID and carOwner as extras but it throws errors.......any ideas?
Try using hidden inputs. They act just like a normal input tag but the user never sees them.
<input type="hidden" name="cID" value="<?php echo $cID; ?>">
<input type="hidden" name="cOwner" value="<?php echo $cOwner; ?>">
Mileage:<input type="text" name="mileage"><br />
Color:<input type="text" name="Color"><br />
carID:<?php echo $cID; ?>
carOwner: <?php echo $cOwner; ?>
Now you will receive 4 fields in your $_POST or $_GET whichever you are using
$_POST['cID']
$_POST['cOwner']
$_POST['mileage']
$_POST['Color']
Crude but easiest method and will match the style of the other data:
Show the carID and carOwner but prevent them from being edited:
Mileage:<input type="text" name="mileage"><br />
Color:<input type="text" name="Color"><br />
carID:<input type="text" name="cID" value="<?php echo $cID; ?>" readonly="readonly"><br />
carOwner:<input type="text" name="cOwner" value="<?php echo $cOwner; ?>" readonly="readonly"><br />
Forgot to add, the data will be posted just the same as "mileage" or "Color" for you to process however you like.
This is how to make Your input type hidden:
Mileage:<input type="text" name="mileage"><br />
Color:<input type="text" name="Color"><br />
carID:<?php echo $cID; ?><input type="hidden" name="cid" value="<?php echo $cID; ?>" /><br />
carOwner: <?php echo $cOwner; ?><input type="hidden" name="cowner" value="<?php echo $cOwner; ?>" /><br />
You should both echo $cID and $cOwner and include them as hidden values.
Then on the page where You've sent this form You can get the values cid and cowner the same as mileage, Color to insert into the database.
For post and get methods this would be respectively:
$_POST['mileage']
$_POST['Color']
$_POST['cid']
$_POST['cowner']
or
$_GET['mileage']
$_GET['Color']
$_GET['cid']
$_GET['cowner']
Here is a not so safe way to insert those values into the database:
INSERT INTO table_name (column_name1,column_name2,column_name3,column_name4) VALUES (`$_POST['mileage']`,$_POST`['Color']`,`$_POST['cid']`,`$_POST['cowner']`);
The safer way would be to use:
$st = $db->prepare('INSERT INTO table_name (...fields...) VALUES (?,?,?,?)');
$st->execute($values);
where $values is an array of values You want to insert.
You can form the $values array from $_POST like that:
$values[] = $_POST['mileage'];
$values[] = $_POST['Color'];
...
Reference:
PDO::prepare, PDO with INSERT INTO through prepared statements.
Not so bad tutorial is located here. It will help You to get the idea, but it has some little errors, that are fixed in the comments of that post.

$_POST unknown amount of elements

My idea is like an basket on a webshop.
I have a list of items filled into a form by php like:
<?php while($info=msqli_fetch_array($query)){ ?>
<Input type="text" id="someid1" value="<?php echo $info['info']; ?>">
<Input type="Checkbox" id="checkid1" value="1">
<Input type="Checkbox" id="checkid2" value="2">
<?php } ?>
I want to use POST for submitting.
on the next page for each line should be done this:
MYSQLI query
INSERT into booking (text,variable1,variable2)
VALUES ('$_POST['someid1']','$_POST['checkid1']','$_POST['checkid2']';
Is there a solution for this?
You can setup named inputs with brackets to get the results as an array server-side. For example:
<input type="text" name="fruits[1]" value="apple" />
<input type="text" name="fruits[2]" value="orange" />
on server side:
<?php
print_r($_POST['fruits']);
?>
array(
1 => 'apple',
2 => 'orange',
)
That solves the question. But your code suggests something else that should really be addressed.
You're asking for SQL injection if you just dump $_POST variables into a query. Use PHP's PDO functionality and parameterize your input. Look at the 2nd example in the answer at PHP PDO prepared statements for more info.
You could use a foreach but IMHO isn't a very secure thing what you want to do.
You should use arrays in your html, then you get the corresponding arrays in your $_POST array. Note that you need the name attribute:
<input name="someid[<?php echo $info['id']; ?>]" id="someid1" value="<?php echo $info['info']; ?>">
<input name="checkid[<?php echo $info['id']; ?>]" id="checkid1" value="1">
// etc.
Now $_POST['someid'], etc. will be arrays you can loop over.
Note that you need to use prepared statements to store the information in your database.

Trying to echo a string in a search box

I am trying to echo a string in a search box. However so far it only echos the first word of the string.
require 'search.php';
$searchQuery = $_GET['searchText'] ;
echo $searchQuery;//prints "this is a test"
$search = new Search();
$search->run($searchQuery);
.
.
<input name="searchText" type="text" id="searchText" size=70 value = <?php echo $searchQuery; // prints "this"?> />
Try adding quotes:
<input name="searchText" type="text" id="searchText" size="70" value="<?php echo htmlspecialchars($searchQuery); ?>"/>
As Esailija pointed out, escaping properly with htmlspecialchars() is a better solution and will ensure it prints the value correctly whatever the search may be.
You need to add quotes around the value of the 'value' attribute, as such:
<input name="searchText" type="text" id="searchText" size=70 value="<?php echo $searchQuery; // prints "this"?>" />
Otherwise this is what will render:
<input name="searchText" type="text" id="searchText" size=70 value = this is some sentent />
which defines value of the attribute named 'value' to be "this", and then creates more (meaningless) attributes "is", "some" and "sentence" which have no values. Quotes are important! You should also probably quote your size variable although it's not important in this case.
Also note that not inspecting and/or sanitizing the GET variable leaves you open to HTML/Javascript injection attacks -- if I provided the value word onClick='doSomething();' as the GET variable value, I could execute javascript on the client. If this were rendered as part of a comments section of a website as such, I could potentially inject other client's machines with arbitrary javascript.
[EDIT]
You can accomplish this by using htmlspecialchars as pointed out by Esailija. For more information about common web vulnerabilities and the reason for sanitizing GET variables, perhaps you should check out OWASP
It's happening because you don't have quotes around it, so what you're actually outputting is
<input ... value = this is a test />
So it's assigning the first token as the "value" property.
Try this:
<input ... value="<?php echo $searchQuery; ?>" />
Try this:
<input name="searchText" type="text" id="searchText" size="70" value="<?php echo $searchQuery; ?>" />

Using a PHP variable in a text input value = statement

I retrieve three pieces of information from the database, one integer, one string, and one date.
I echo them out to verify the variables contain the data.
When I then use the variables to populate three input boxes on the page, they do not populate correctly.
The following do not work:
id: <input type="text" name="idtest" value=$idtest>
Yes, the variable must be inside <?php var ?> for it to be visible.
So:
id: <input type="text" name="idtest" value=<?php $idtest ?> />
The field displays /.
When I escape the quotes,
id: <input type="text" name="idtest" value=\"<?php $idtest ?>\" />
the field then displays \"\".
With single quotes
id: <input type="text" name="idtest" value='<?php $idtest ?>' />
the field displays nothing or blank.
With single quotes escaped,
id: <input type="text" name="idtest" value=\'<?php $name ?>\' />
the field displays \'\'.
With a forward slash (I know that's not correct, but to eliminate it from the discussion),
id: <input type="text" name="idtest" value=/"<?php $name ?>/" />
the field displays /"/".
Double quotes, escape double quotes, escape double quotes on left side only, etc. do not work.
I can set an input box to a string. I have not tried using a session variable as I prefer to avoid do that.
What am I missing here?
Try something like this:
<input type="text" name="idtest" value="<?php echo htmlspecialchars($name); ?>" />
That is, the same as what thirtydot suggested, except preventing XSS attacks as well.
You could also use the <?= syntax (see the note), although that might not work on all servers. (It's enabled by a configuration option.)
You need, for example:
<input type="text" name="idtest" value="<?php echo $idtest; ?>" />
The echo function is what actually outputs the value of the variable.
Solution
You are missing an echo. Each time that you want to show the value of a variable to HTML you need to echo it.
<input type="text" name="idtest" value="<?php echo $idtest; ?>" >
Note: Depending on the value, your echo is the function you use to escape it like htmlspecialchars.
From the HTML point of view everything's been said, but to correct the PHP-side approach a little and taking thirtydot's and icktoofay's advice into account:
<?php echo '<input type="text" name="idtest" value="' . htmlspecialchars($idtest) . '">'; ?>
If you want to read any created function, this how we do it:
<input type="button" value="sports" onClick="window.open('<?php sports();?>', '_self');">
I have been doing PHP for my project, and I can say that the following code works for me. You should try it.
echo '<input type = "text" value = '.$idtest.'>';

Categories