How to process multiple html inserts? - php

I'm trying to create multiple HTML inserts in the same form so I can quickly insert multiple lines into my database to save time. However I'm not really sure how to process this.
<form action="admin1.php" method="post">
<?php
function multiform($x){
for ($x = 0; $x < 3; $x++){
echo 'Episode: <input type="number" name="Episode[]">
Date: <input type="date" name="Date[]">
Guest: <input type="text" name="Guest[]">
Type: <input type="text" name="Type[]">
Youtube:<input type="text" name="Youtube[]"> MP3: <input type="text" name="MP3[]"> iTunes:<input type="text" name="Itunes[]"><br/><br/>';
}
}
multiform(0);
?>
<input type="submit" value="Submit Form" name="submitForm">
</form>
This is what I tried to use:
$con = mysqli_connect("server","root","","database");
function multiformpost($x) {
for ($x = 0; $x < 3; $x++) {
$Episode = $_POST['Episode'][$x];
$Date = $_POST['Date'][$x];
$Guest = $_POST['Guest'][$x];
$Type = $_POST['Type'][$x];
$Youtube = $_POST['Youtube'][$x];
$MP3 = $_POST['MP3'][$x];
$Itunes = $_POST['Itunes'][$x];
$sql = "INSERT INTO podcasts(Episode, Date, Guest, Type, Youtube, MP3, Itunes) VALUES ('{$Episode}', '{$Date}', '{$Guest}', '{$Type}', '{$Youtube}', '{$MP3}', '{$Itunes}')";
}
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
if (!mysqli_query($con, $sql)) {
die ('Error: ' . mysqli_error($con));
}
echo "Added to database";
}
}
multiformpost(0);
mysqli_close($con);
Which simply returns a blank screen.. I know it's wrong but I'm not entirely sure why.

You need to be building up the VALUES section of your SQL in a loop and then executing a single query. So something like this:
$con = mysqli_connect("","","","");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
multiformpost($con);
mysqli_close($con);
function multiformpost($db) {
if(empty($db) {
throw new Exception('You need to pass a valid mysqli connection to this method');
}
$sql = "INSERT INTO podcasts(Episode, Date, Guest, Type, Youtube, MP3, Itunes) VALUES ";
$size = count($_POST['Episode']);
for ($x = 0; $x < $size; $x++) {
$Episode = mysqli_real_escape_string($db,$_POST['Episode'][$x]);
$Date = mysqli_real_escape_string($db,$_POST['Date'][$x]);
$Guest = mysqli_real_escape_string($db,$_POST['Guest'][$x]);
$Type = mysqli_real_escape_string($db,$_POST['Type'][$x]);
$Youtube = mysqli_real_escape_string($db,$_POST['Youtube'][$x]);
$MP3 = mysqli_real_escape_string($db,$_POST['MP3'][$x]);
$Itunes = mysqli_real_escape_string($db,$_POST['Itunes'][$x]);
$sql .= "('{$Episode}', '{$Date}', '{$Guest}', '{$Type}', '{$Youtube}', '{$MP3}', '{$Itunes}'),";
}
$sql = rtrim($sql,',');
if (!mysqli_query($db, $sql)) {
die ('Error: ' . mysqli_error($db));
}
echo "Added to database";
}
Note that I also made the following changes which I also suggest:
I pass in DB connection to the function. I have no idea what your original parameter was being used for, since you can detect the array size of the POST arrays directly in the function. You would be even better served moving to object-oriented mysqli usage (as you could then verify an instantiate mysqli object was passed to the function), but I didn't make that change here.
I differentiated the use of $con (for global scope) and $db (for local sope in function) so that you do not confuse the two. Previously, your code referenced $con inside function scope without declaring global so that variable would not have even been available. This dependency injection approach is highly recommended as opposed to using global.
I moved DB connection error checking outside the function
I added string escaping to mitigate against SQL injection.
I moved all your global script elements together, as functions typically should not be inserted in the middle of procedural code like you have done, as that make the code more difficult to follow.

Related

POST data not sending

UPDATE
Added all the code for the img upload as well as adding to the DB.
The output of print_r($_POST); :Array ( [prodName] => Test Product [prodPrice] => 100 [prodDescript] => Test description [submit] => UPLOAD )
Also the prodID col is auto increment.
Building off an image uploader you all so graciously helped me with, I am now trying to get the rest of this form to work. I am sending the data via POST but none of the info is being sent. I have verified the images upload, via the $_FILES array, but nothing is coming through in the $_POST data
I know my hosting service allows $_POST because I have another form that works perfectly with it. I cannot get to seem to get any errors to point me in the right direction. So once again. I come to you wonderful people.
<form action="inventory_add.php" method="POST" enctype="multipart/form-data">
<label>Product Name: </label>
<input type="text" name="prodName" id="prodName">
<br>
<label>Product Price: </label>
<input type="text" name="prodPrice" id="prodPrice">
<br>
<label>Product Description</label><br>
<textarea name="prodDescript" width="200px" id="prodDescript"></textarea>
<br>
Select Image Files to Upload:
<br>
<input type="file" name="upload[]" multiple >
<input type="submit" name="submit" value="UPLOAD">
</form>
Some of the code from inventory_add.php:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$servername = "**********";
$username = "**********";
$password = "***********";
$dbname = "************";
$prod_name = $_POST['prodName'];
$prod_price = $_POST['prodPrice'];
$prod_descript = $_POST['prodDescript'];
print_r($_POST);
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
if(isset($_FILES['upload'])){
$total = count($_FILES['upload']['name']);
for( $i=0 ; $i < $total ; $i++ ) {
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
if ($tmpFilePath != ""){
$newFilePath = "images/prod/" . $_FILES['upload']['name'][$i];
if(move_uploaded_file($tmpFilePath, $newFilePath)) {
$img_names = implode(",",$_FILES['upload']['name']);
}
}
}
$prodID = $_SESSION['curcount'] + 1;
$sql = "INSERT INTO `inventory` (`prodId`, `prodTitle`, `prodDescript`, `prodCost`, `prodImages`) VALUES (' '," . $prod_name. "," . $prod_descript . "," . $prod_price ."," .$img_names.")";
if ($conn->query($sql) === TRUE) {;
// header('location:http://nerdsforhire.pnd-productions.com/shopmgr.php');
} else {
echo 'There was an issue adding this item.';
};
}
}
} else {
echo "Failed";
}
Would hope this would update the database... yet it is not. I keep getting "There was an issue adding this item."
UPDATE based on our conversation below, and the code above, I think the issue is in your SQL not your PHP. I suggest adding mariadb to your question.
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = 'INSERT INTO `inventory` ( `prodTitle`, `prodDescript`, `prodCost`, `prodImages`) VALUES (?,?,?,?)' ;
$stmt = $conn->prepare($sql)
$stmt->bind_param("ssss", $prod_name, $prod_descript, $prod_price, $img_names);
$stmt->execute()
if($stmt->affected_rows > 0) {
//header("location:https://sample.com"); #affected_rows > 0 so row was inserted
} else {
echo 'There was an issue adding this item.'; #failed to insert;
}
That should solve the issue. It is a prepared statement that will handle the issue with unescaped commas in the string as well as prevent SQL injection. Because prodId is auto increment, you don't need it in your statement, at least in MySQL you don't. The "ssss" part of the statement is assuming you are passing string values to the Db. Possible data types to be passed are:
i - integer
d - double
s - string
b - blob
See WC3Schools for more about php and prepared statements.

Create class instances from data

I've got a PHP class, and I'd like to create instances I can update later from the data that I pull from the database. Here's what I've got so far:
<?php
$servername = "localhost";
$username = "super";
$password = "cala";
$database = "fraga";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$getTableQuery = "SELECT ani.Id, ani.Name, ani.Size, ani.Color, tbs.Name as Species, tbs.Description
FROM animals as ani INNER JOIN
animalTypes as tbs ON ani.Species = tbs.Id
ORDER BY ani.Id";
$table = $conn->query($getTableQuery);
$pageLoaded = false;
if(isset($_POST['btnInsert']) && ($_POST['txtName'] != "")){
$pageLoaded = true;
}
if ($table->num_rows > 0) {
echo "<table border='1'><tr><th>Name</th><th>Size</th><th>Color</th><th>Species</th></tr>";
// output data of each row
while($row = $table->fetch_assoc()) {
echo "<tr><td>".$row["Name"]."</td><td>".$row["Size"]."</td><td>".$row["Color"]."</td><td>".$row["Species"]."</td></tr>";
$fish[] = $row;
}
echo "</table>";
echo "</br>";
} else {
echo "0 results";
}
if(isset($_POST['btnInsert']) && ($_POST['btnInsert'] == "Insert") && $pageLoaded == true)
{
$Animal = new Animal($_POST['txtName'], $_POST['txtSize'], $_POST['txtColor'], $_POST['txtSpecies'], $_POST['txtDescription']);
$Animal->InsertAnimal($conn);
}else if(isset($_POST['btnSave']) && ($_POST['btnSave'] == "Save") && $pageLoaded == true){
$Animal->UpdateAnimal($Animal);
}
class Animal
{
private $name = "Animal Name";
private $size = 0;
private $color = "255:255:255";
private $speciesName = "Species Name";
private $speciesDescription = "Species Description";
public function Animal($name, $size, $color, $species, $description){
$this->name = $name;
$this->size = $size;
$this->color = $color;
$this->speciesName = $species;
$this->speciesDescription = $description;
}
private function ColorCheck($color){
if($color >= 256 || $color <= 0)
return false;
else
return true;
}
public function InsertAnimal($conn, $pageLoaded){
$this->speciesName = mysqli_real_escape_string($conn, $this->speciesName);
$this->speciesDescription = mysqli_real_escape_string($conn, $this->speciesName);
$this->name = mysqli_real_escape_string($conn, $this->name);
$this->size = mysqli_real_escape_string($conn, $this->size);
$this->color = mysqli_real_escape_string($conn, $this->color);
$speciesId = "SELECT Id from animalTypes WHERE Name = '$this->speciesDescription'";
$speciesInsert = "INSERT IGNORE INTO animalTypes (Name, Description)
VALUES ('$this->speciesName', '$this->speciesDescription')";
$result = mysqli_query($conn, $speciesInsert) or die("Query fail: " . mysqli_error($conn));
if($id = $conn->query($speciesId)){
$row = $id->fetch_assoc();
$intId = $row['Id'];
}
$AnimalInsert = "INSERT INTO animals (Name, Size, Color, Species)
VALUES ('$this->name', $this->size, '$this->color', $intId)";
$result2 = mysqli_query($conn, $AnimalInsert) or die("Query fail: " . mysqli_error($conn));
echo '<script type="text/javascript">window.location = window.location.href;</script>';
$_POST['txtName'] = "";
}
public function UpdateAnimal($animal, $conn){
$speciesCheck = "SELECT * FROM animalTypes WHERE Name = '$this->speciesName";
$speciesList = mysqli_query($conn, $speciesCheck) or die("Query fail: " . mysqli_error($conn));
$updateQuery = "UPDATE animals";
}
}
$conn->close();
?>
<body>
<form action="index.php" method="post">
Animal Name:<br />
<input name="txtName" type="text" /><br />
<br />
Size:<br />
<input name="txtSize" type="text" /><br />
<br />
Color:<br />
<input name="txtColor" type="text" /><br />
<br />
Species Name:<br />
<input name="txtSpecies" type="text" /><br />
<br />
Species Description:<br />
<input name="txtDescription" style="width: 419px; height: 125px" type="text" /><br />
<br />
<input name="btnInsert" type="submit" value="Insert" />
<input name="btnSave" type="submit" value="Save" />
</form>
</body>
Now, what I'd like to do is create instances of Animal from the data that loads when the page loads, and store them for update. Problem is, I'm not sure how to do it. I've googled a bit (but my fu is admittedly weak), and saw suggestion for creating an array of Animals and adding them during the while loop. Is that really the best way to do that? And then how could I load the instance back into the text boxes so that I could update them?
First of all you should learn to seperate the concerns in your code correctly.
If I started to explain how you should build your script up from scratch, this would take too long, so I will try to give you only a good direction to go. I think this will help you more in your learning process.
So, if I understand correctly, the code you posted is all set up in one file, I guess it's inside you index.php? (missing some information here)
If this is the case...
index.php
Use your index.php for displaying a list of your "Animals" from db, not more. Every list entry will have an edit and delete button/link next to it. On top of your list put a link that's called create.
Now all your index.php does is getting the animals from db and listing them.
Put this part of your code in another file, called dbconfig.php
$servername = "localhost";
$username = "super";
$password = "cala";
$database = "fraga";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
include it on top of your index.php, before you start scripting the index.php
include 'dbconfig.php'
now you can use your $conn variable inside you index.php. We put this into another file and included it, because we're going to reuse this part in the next steps.
I won't write your whole code here for index.php, I think you'll master that. Maybe you ask yourself what your create, edit, delete links should do.
The create link point to a create.php, a simple html link.
The edit link, you will have to render an html link to edit.php?id=IDOfYourAnimalInsideDB
The delete link looks like the edit one, put a link to delete.php?id=IDOfYourAnimalInsideDB.
So where I wrote "IDOfYourAnimalInsideDB" you have to output the actual id, this will be done in your while loop.
create.php
first of all, include the dbconfig.php again here, so you can use your $conn variable which has the db connection.
check if the request has some of your post variables, if true, build an instance of animal and write it to db.
outside the if you build your form. So it doesn't matter if it's post or not, you will show the create form.
delete.php
Again the dbconfig.php include first.
Then you want to check if $_GET['id'] is set and maybe if it's bigger than 0 and if its an integer value. If so, execute your delete sql to the db.
update.php
Again the dbconfig.php include first.
Then you want to check your GET Parameter again and build an sql request to get your specific database entry.
Output a form that already contains your values from db. If a post request comes, you create a new Animal instance, fill it with your data from $_POST and then use it for updating your db.
getters in Animal Class
add getter functions to you animal class, so you can access the private properties from outside. you should write you create, update, delete logic inside the create.php, update.php, delete.php or in another class which you use for database manipulation. There you want to get access to properties for example in order to build up your update sql.
So make a getter method for every property of your "Animal" model class
public function getName() {
return $this->name;
}
so from outside you can get your animals name like so
$animalName = $animal->getName();
more specific?
If you need something more specific, you should specify a little bit more your question. What I described is just a way that splits your script into parts you can understand and maintain better, because stucture and correct seperation of things is one of the most important things in programming.
What I described is far far away from a clean "CRUD" solution, but I think this is a little step for you that you can take now to come closer to a clean solution.
Kind regards

filling in form fields from previous database entry - php

I am trying to create a form where everything is filled out from the user's previous entry. Its suppose to work by the user selecting the "update" link. However the form is not being filled at all.
I've been trying to figure this out for 2 days now but i cant seem to figure it out. Some help would be greatly appreciated, thanks!
up.php
<form method="POST" action="up1.php">
<?php
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp ORDER BY primeID DESC ";
$sql_result = mysql_query($sql1) or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
}
?>
Update
</form>
up1.php
<form action="up2.php" method="post">
<?
$connection = mysql_connect("xxxxx","xxxxx","xxxxx")
or die("Could not make connection.");
$db = mysql_select_db("xxxxx")
or die("Could not select database.");
$sql1 = "SELECT * FROM emp WHERE primeID = '$up22'";
$sql_result = mysql_query($sql1)
or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($sql_result))
{
$prime = $row["primeID"];
$a1 = $row["country"];
$a2 = $row["job"];
$a3 = $row["pos_type"];
$a4 = $row["location"];
$a5 = $row["des"];
$a6 = $row["des_mess"];
$a7 = $row["blurb"];
$a8 = $row["restitle"];
$a9 = $row["res"];
$a10 = $row["knowtitle"];
$a11 = $row["know"];
$a12 = $row["mis"];
$a13 = $row["mis_des"];
}
?>
<input name="aa1" value="<? echo $a1; ?>" type="text" id="textfield" size="60">
<input name="a1" type="text" value="<? echo $a2; ?>" id="textfield" size="60">
<input name="a2" type="text" value="<? echo $a3; ?>" id="a2" size="60">
<input name="a4" type="text" value="<? echo $a5; ?>" id="a4" size="60">
</form>
Based upon the limited information I could get out of your post I think I found the problem:
Starting with up.php
Update
Actually sends a "GET request" (Loading the page with a query string). We need to rebuild that:
<a href="JavaScript: void(0)" onclick="this.parentElement.submit()" >Update</a>
Now this link is going to send the form. However we need to send the value $prime. Let's use a hidden input inside the form.
<input type="hidden" name="up22" value="<? echo $prime; ?>" />
Now when the user clicks the link it posts the form and loads up1.php with the post var up22.
Changes to up1.php
$sql1 = "SELECT * FROM emp WHERE primeID = '".$_POST['up22']".'";
PDO
To update your code even further: PDO is a safer way to do queries. mysql queries are deprecated. They shouldn't be used anymore.
Replace your database calls with the following code:
function openDBConnection()
{
$name = "xxxxxx";
$pw = "xxxxxx";
$server = "xxxxxxx";
$dbConn = new PDO("mysql:host=$server;dbname=xxx", $name, $pw, , array( PDO::ATTR_PERSISTENT => false));
}
catch( PDOException $Exception )
{
echo "120001 Unable to connect to database.";
}
return $dbConn;
}
function doPDOQuery($sql, $type, $var = array())
{
$db = openDBConnection();
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
if ($type == "prepare")
{
$queryArray = $var;
$sth = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute($queryArray);
}
else if ($type == "query")
{
$sth = $db->query($sql);
}
else
{
echo "Supplied type is not valid.";
exit;
}
if (!$sth)
{
$error = $db->errorInfo();
echo $error;
exit;
}
return $sth;
}
These functions you can use to make PDO queries to the database. The first function opens a database connection, while the second functions actually performs the query. You do not need to call the first function. It's called in the second one.
Example based upon your code:
$sql1 = "SELECT * FROM emp WHERE primeID = :id";
$sql_result = doPDOQuery($sql1, 'prepare', array(":id" => $_POST['up22']));
while ($row = $sql_result->fetchAll() )
{
//loop through the results.
}
PDO works as follows: instead of passing php variables into the SQL string (and risking SQL-injection), PDO passes the SQL string and variables to the database and let's the database's driver build the query string.
PDO variables can be declared by name or by index:
By name: use : to declare a named variable. SELECT * FROM TABLE WHERE id = :id. Each key must be unique.
By index: use ? to declare an indexed variable. SELECT * FROM TABLE WHERE id = ?
An array containing the variables needs to be passed to PDO.
named array:
array(":id" => 1);
indexed array:
array(1);
With named arrays you don't have to worry about the order of the variables.
http://php.net/manual/en/book.pdo.php

Change a variable of a variable

I'm trying to process a large form and hit a bit of a stumbling block. I've tried google for the answer, but I'm not quite sure I'm wording what I need right. My code looks like this.
<?PHP
$exchange = $_POST['exchange'];
$estimate = $_POST['estimate'];
$wp = $_POST['wp'];
$label1 = $_POST['name3'];
$result1 = $_POST['fb1'];
$result2 = $_POST['fb2'];
$username = "-----";
$password = "-----";
$hostname = "-----";
$con = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("-----", $con) or die("Could not select examples");
$query = "UPDATE btsec SET Status='$result1', TM='result2' WHERE Exchange='$exchange' AND Estimate='$estimate' AND WP='$label1' AND SectionID='$label1'";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error($con));
}
}
echo "Sections updated for WP's $wp on $estimate on the $exchange Exchange!";
mysql_close($con);
?>
What I need to do is loop through the query, but each time change the contents of the variable.
$label1 = $_POST['name3']; needs to become $label1 = $_POST['name6'];
$result1 = $_POST['fb1']; needs to become $result1 = $_POST['fb10'];
$result1 = $_POST['fb2']; needs to become $result1 = $_POST['fb11'];
As I say google isn't able to compensate for my bad wording.
The best solution would be to change the form inputs so that they work as arrays:
<input type="text" name="name[3]">
<input type="text" name="name[6]">
<input type="text" name="name[9]">
<input type="text" name="fb[1]">
<input type="text" name="fb[10]">
<input type="text" name="fb[19]">
Then when you submit the form you can iterate over the data:
foreach ($_POST['name'] as $index => $name)
{
}
foreach ($_POST['fb'] as $index => $fb)
{
}
As a side note, you also should look into using prepared statements, or at the very least escaping the data -- you're at risk of SQL injection.

My database query security

I am new to web design, and I'm using a very simple ajax method to get the id of a product from a database. Being so new to backend stuff, I was wondering if anyone wouldn't mind teaching me a little about php security.
My first area in question is the post method and the method in which i get the data for the post method.
function setupc(upc) {
var sku1 = $("#option1 option:selected").data('sku');
var sku2 = $("#option2 option:selected").data('sku');
if (sku2 !== null) {
upc = (sku1 + sku2);
} else {
upc = (sku1);
}
$('input[name="upc"]').val(upc);
$.post('getproduct.php', {upc: upc}, function(data){
$('.result').html(data);
});
}
And here is the getproduct.php
<?php
require_once("config.php");
$con=mysql_connect (MySQL, $username, $password);
if (!$con) {
die("Not connected : " . mysql_error());
}
$db = mysql_select_db($database, $con);
if (!$db) {
die ("Can\'t use db : " . mysql_error());
}
$upc = "$_POST[upc]";
$sql = "SELECT * FROM products WHERE upc = '$upc'";
$result = mysql_query($sql, $con) or die(mysql_error());
$row=mysql_fetch_array($result);
?>
<input type="hidden" id="id" name="id" value="<? echo $row['id']; ?>">
<input type="text" id="price" value="<? echo $row['price']; ?>">
<?php mysql_close($con); ?>
If this is not the place to ask these kinds of questions, please let me know and I'll gladly remove it. And, maybe even point me to a place that i can.
your code doesn't prevent so-called "SQL injection"
This means that someone can call your script with sql-statements in the
$_POST['upc'] parameter
Your query would be better using mysql_real_escape_string:
$sql = "SELECT * FROM products WHERE upc = '" . mysql_real_escape_string($upc) . "'";
any sql code would be escaped and won't be executed.
EDIT: you also may google for "SQL injection" a little bit, to learn about this security matter

Categories