Redundant way of getting multiple $_POST records? - php

EDIT : I might just make it a more 'step-by-step' process i.e.
Seeing as it feels more user-friendly & it's only for <5 images. I have read & appreciate all of the help that I have received so far.
I'm fairly new to PHP & I'm building a basic PHP image editor which may allow multiple image data auditing which is then inserted into a MySQL database. A limit of 5 images may be uploaded at a time for this system (implying that there will only be a low amount of records to play with), but I'll get to that further down.
GUI:
Some of the data columns used:
image id
caption
description
published
imageposition
delete button
All images are echo'd in a while loop by a previous 'SELECT *' result set. Each image will have the 'image id' echo'd inside each input name, so output will be for example:
caption-2, description-2, published-2, imageposition-2, caption-3, description-3
Also, the data values from the previous resultset are echo'd into the input value, allowing the client to edit the current data that exists in the database. There is only one submit button.
My question:
I want to be able to post all of the modified image(s) data to a processor.php form which will then allow me to insert it as an INSERT sql string into the MySQL images table. I need the PHP to be dynamic incase:
images are deleted (image id)
new images are uploaded (image id)
If there is an easier way of doing any of the above, I am welcome to new ideas/opinions. Sorry in advance for my poor understanding of PHP.

Once you get result from 'select *' statement you do foreach
foreach ($images as $image) {
?>
<img src="imagesrc">
<input type="text" name="title_<?php echo $image['image_id'] ; ?>" value="<?php echo $image['title']; ?>">
<input type="text" name="desc_<?php echo $image['image_id'] ; ?>" value="<?php echo $image['description']; ?>">
<input type="button" onclick="markDeleted('<?php echo $image['image_id'] ; ?>')">
<?php } ?>
.....
Once you receive the post value you can explode with "_" and you will get the Primary key and you can update the image table with image ID.
In the javascript function markDeleted you can set the primary key in some hidden field and sent to process.php.
Add it like comma separated 1,2,3 like this (Split by comma in action page)
function markDeleted (imageId)
{
document.getElementById('deleted_image_ids').value = imageId + ","
}

To delete the records easily :
<form action="processor.php" method="post">
<?php
foreach ($images as $img) { // assuming $images is the result set of your sql query
?>
<input type="text" name="name<?php $img['image_id'];?>" value="<?php $img['caption'];?>">
<input type="text" name="desc<?php $img['image_id'];?>" value="<?php $img['description'];?>">
...
<a href="http://yoursiteurl/deleteimg.php?id=<?php $img['image_id']?>">
<?php } ?>
</form>
In deleteimg.php :
<?php
$del = $_POST[id];
$query = $msqli->prepare("DELETE FROM imagetablename WHERE image_id=?");
$query->bind_param( 's', $del );
$query->;execute();
?>
Updating and adding new rows may involve javascript, and much more harder.

Related

Updating Images Array

I have a table named tabel_foto which has 2 fields inside it, they are
foto (which contains the image's name), and
kondisi (which contains the image's description)
foto and kondisi's field value is from an-imploded multiple image upload. In other words, i have an upload form which it can upload multiple images, and those images are imploded before they are INSERTED into the sql table, like this :
I can show the image from my table as a list like this :
Please ignore it's bad layout, it's just a prototype/experiment before i add a new feature to my site
My question is, how to update those images to my table? I only want to update the image that is changed, i.e :
foto's field value is borobudur.jpg, bromo.jpg, merapi.jpg, prambanan.jpg, if i update the second image (bromo.jpg) from the form, i only want to update the "bromo.jpg" string in the foto field, how do i detect which image is changed on the form in php since the file upload button is a single file upload (not multiple upload) :
for($i = 0; $i < count($xplode_foto); $i++) {
?>
<img src="<?php echo $xplode_foto[$i]; ?>" id="<?php echo $i; ?>">
<input type="file" id="<?php echo $i; ?>" name="foto_kondisi" onChange="previewFotoJalan(this, this.id)">
<?php
}
Thanks in advance, i appreciate any solutions and answers :)
I would strongly suggest you to use a different mysql schema, like this.
photo_id
group_id
kondisi
Also, you can send a ajax request after every picture's upload , and refresh the page (or just a div).
This will make your life easier.. believe me... been there.
Success!!
Considering you save images on table column as img1,img2,img3 and description as desc1,desc2,desc3
and considering you use explode to update image.
you can make change like that:
<?php
$id = $_POST['imgid'];
//get images string from db and save to $x;
$images_array = explode(',', $x);
unset($images_array[$id]);
$y = implode (',', $images_array);
// now save again $y to db as images
//get description string from db and save to $x;
$desc_array = explode(',', $x);
unset($desc_array [$id]);
$y = implode (',', $desc_array);
// now save again $y to db as desc
Hope this help you

How to loop through $_POST array and send data to different MySQL tables

I have a form that will send data via POST. I want that data to go to different MySQL tables based on the POST "name."
What I have so far is a while loop for the form fields that will name each input in the format: "name"{}$id. I thought that using {} as a delimiter I could then use explode() and use a conditional statement to select which table the data should go to.
Is this the best way to do this? The issue I'm having is also calling the name, since using foreach for example on POST will just return the values and not the names. I have enclosed the code below:
<?php while ($cred = mysql_fetch_array($credentials_process)) { ?>
<div class="edit-profile-background-inputs">
<span><input type="text" name="cred{}<?php echo $cred['id']; ?>" value="<?php echo $cred['credentials']; ?>" /></span>
<span style="margin-left:10px;">Remove</span>
</div>
<?php } ?>
I need those fields named cred{} to go to credentials table, those named edu{} to go to the education table, etc.
<input type="text" name="cred[<?php echo $cred['id']; ?>]"...
<input type="text" name="edu[<?php echo $edu['id']; ?>]"...
in PHP
$insert=array();
foreach ($_POST['cred'] as $k=>$v)
{
$insert[$k]=mysql_real_escape_string($v); // yes I know mysql is being depreciated
}
$sql='INSERT INTO cred ('. implode(',', array_keys($insert)).') VALUES ('. implode(',', $insert).');
repeat for $_POST['edu']
If your results set is such that you're outputting more than one row with the same key
$i=0;
while ($cred = mysql_fetch_array($credentials_process)) { ?>
<input type="text" name="cred[$i][<?php echo $cred['id']; ?>]"...
...
$i++;
}
If you print_r($_POST) from that you'll be able to figure out how to deal with them.
NB. For safety I would also make sure only the expected posted vars get used
$allowed=array('cred_id', 'cred_something', 'etc');
foreach ($_POST['cred'] as $k=>$v){
if (!in_array($k, $allowed)) continue;

Proper way to pass an array through post?

I have two pages:
Graph.php
List.php
The Graph page does exactly what it is named, graphs data. If there is no post/get data it displays all the data in a given table.
The List page is a huge table which loads around 500-600 rows of data. In the table you can sort and filter the rows using JavaScript. The table is around 14 columns wide.
After sorting the rows in the List page you can press a button 'Graph' that will take the visible rows and graph them on the graph page.
What I am having trouble with is passing these ID's over to the graph page. I started with:
<?php
if(isset($_POST['data']))
{
echo "FOUND SERIALIZED ARRAY<br>";
$afterSerializeArray = unserialize($_POST['data']);
print_r($afterSerializeArray);
}
$beforeSerializeArray = array();
$beforeSerializeArray[] = 1;
$beforeSerializeArray[] = 2;
$beforeSerializeArray[] = 3;
$serializeArray = serialize($beforeSerializeArray);
?>
<form action="" method="post">
<input type="hidden" name="data" value="<?php echo $serializeArray; ?>"/>
<input type="submit" value="Serialize"/>
</form>
I have written the small snippet to grab the ID's of the visible rows and load them into an array, serialize it and pump it into a variable to post it over to the graph.
Should I be using GET? Should I be doing this a different way?
The reason I wanted the filter and sort on a different page than the graph is because users have a lot of columns and options to filter and sort by.
Rather than trying to send array over post you should concatenate these ids with any special character (say ','). This way you will get all IDs as comma separated values in $_POST['data']. Now you can use PHP explode function to get all the values in an array and use them as you wish.
This code sample might help you
<?php
if(isset($_POST['data']))
{
echo "FOUND Ids<br>";
$IdArray = explode(',',$_POST['data']);
print_r($IdArray );
}
$idarray = array('1','2','3');
$ids = implode(',',$idarray);
?>
<form action="" method="post">
<input type="hidden" name="data" value="<?php echo $ids;?>"/>
<input type="submit" value="Serialize"/>
</form>

How to get value of edit text with jquery

Hi i want to get changed text value from JQuery but i can't select edit text with JQUERY because edit texts generated from php while loop that this php code query on database and get value of edit texts and in my program i have edit button for every edit texts and when the user changed value of edit text i select new value and when user click edit button send this value from get method to another php page with jquery $.ajax function and send new value to that php code with ajax.But i don't know how can i select edit text that it's value changed because i don't know id of that edit text!.And when i set one id for every edit text i only get first edit text value from $("#id").change().val();.I use below code but it doesn't work.I am beginner in java script and don't know how fix this problem!.
var testAnswer;
function setNewTestAnswer(id){
testAnswer = $("#id").val();
}
function sendToEdit(pID,phID,thDate,type){
var info = 'pId='+pID+'&phId='+phID+'&testAnswer='+testAnswer+'&thDate='+thDate+'&type='+type;
}
2nd function use testAnswer that user changed in edit text.
php code
<?php
include 'Connect.php';
if(match($_POST['pId'], "/^[\d]+$/") ){
$pId = $_POST['pId'];
$result = mysql_query("select pName, pID, phName, phID, testHistoryDate, type, testAnswer from patient join reception using(pID) join physician using(phID) join testHistory using(rID) join test using(tID) where pID = $pId",$connection);
}
else
die("Insert true value");
while($row=mysql_fetch_array($result)){
echo "<tr><td>";
echo $row["pName"].'</td>';
echo '<td>'.$row["phName"].'</td>';
echo '<td>'.$row["testHistoryDate"].'</td>';
echo '<td>'.$row["type"].'</td>';
$type = $row['type'];
$testHistoryDate = $row['testHistoryDate'];
?>
<td>
<span id='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer' value='<?php echo $row['testAnswer']; ?>' />
</span>
</td>
<td>
<input type='submit' value='Edit' name='edit' id='edit' onclick="sendToEdit('<?php echo $row['pID'] ?>','<?php echo $row['phID'] ?>', '<?php echo $row['testHistoryDate'] ?>', '<?php echo $row['type'] ?>')" />
</td>
</tr>
<?php } ?>
tl;dr
So it isn't completely clear what you are trying to do here but I can explain a couple things that might help.
in html ids should be unique. You dont have to obey this rule for your page to work but you have found one of the consequences if breaking it: jQuery will only find the first one.
it is a good idea to base html ids on some unique attribute of your data eg the table row id.
You can get more creative with your jQuery selectors for example
$('input[type="text"]') // gets all the text inputs
Use classes. When you want to be able to easily select all of a group of html elements you should give them all the same class name. one element can have multiple class names and many elements can share a class name. you can then select them by class name using jquery like this:
$('.myclassname')
I think you need to change your php to look more like this:
<span class='spryTanswer'>
<input type='text' name='tAnswer' id='tAnswer-<?php echo $row['id'] ?>' value='<?php echo $row['testAnswer']; ?>' />
</span>
Since you're creating elements inside a php loop, you must be sure that every element has a unique id (or no id at all). You can use either an incrementing index, or some unique value in your array. At first glance, seems that $row['pID'] is a good candidate:
<input id='edit_<?php $row['pID'] ?>' type='submit' value='Edit' ... />
After that you should be able to target individual elements.

PHP Mysql & Jquery dynamically populating multiple records

I want to above Master and child system by using PHP,MYSQL & JQuery.
I am attaching sample image link below See screenshot
Product Quantity and UOM is field which belong to MAster Table and
Code, Component, category, quantity (Also) & UOM (duplicate) is belong to Child table.
I want to add Code, Component, category, quantity etc multiple time whenever user click on add.
Just need to know how can i save all these multiple records when someone completed their works and click on Final Save Button?
I am really and very aggressively searching for this but didn't get any anwer.
If anyone who can find the way or any help or anything that will help me towards this system.
Thanks a lots pls pls Help
you'll want to use
jQuery ajax to save data
.clone() to add a record in the UI you'll have to reset the values will your at it
that should get you started
Each time your user clicks 'add' you want to take the values of your form inputs, build a new table row and show their selected values. This is easy enough, but you also need to add hidden inputs which represent what they chose in the select boxes above, so when the user clicks save, the whole form is posted and you can process the input. A simple example would be:
<script>
var count = 0;
$('#add').click(function(event)
{
var code = $('#code').val(),
component = $('#component').val()
category = $('#category').val(),
uom = $('#uom').val();
$('#table').append(
'<tr>'
+ '<td>' + code + '<input type="hidden" name="record[' + count + '][code]"></td>'
+ '<td>' + component + '<input type="hidden" name="record[' + count + '][component]"></td>'
+ '<td>' + category + '<input type="hidden" name="record[' + count + '][category]"></td>'
+ '<td>' + uom + '<input type="hidden" name="record[' + count + '][uom]"></td>'
+ '</tr>'
);
/*
EDIT: I changed this to a DECREMENTOR so our keys don't overlap and override
anything that is CURRENTLY in the database
*/
count --;
})
</script>
This would attach a click handler to the add button. Each time it is clicked, we get the values of the inputs, store them in a variable, and build + append a new table row to your "preview table" below, which shows the values they selected and creates hidden inputs which can be processed later after the user clicks Save.
Some notes about this:
- it only gets the value of the selected inputs (so for the select boxes, the value of the option not the text. you'll have to do some extra work to replace that into your table row.
- your entire table will have to be encapsulated in a <form> tag, which your save button must also be inside.
Once you get the posted data to the server, do a print_r($_POST) to see what it looks like, you should be able to figure out how to process it fairly easily.
edit
Okay, so you asked a lot of questions here, i'll try to address them as best I can, without writing a novel.
What if someone mistakenly clicks on add and wants to cancel the addition (or changes their mind, whatever).
This actually isn't that hard. If this happens, just remove the appended table row from your table using $.remove. Since all the hidden input elements are contained within the table row, they will also be removed from the form so when the user posts, the fields will not be present.
How should you sanitize the data?
Sanitize the data when the user clicks add, as you populate the form, instead of afterwards, just before you post the form. It will be easier to deal with the input errors when the user clicks add than it will be to deal with them when they click save.
How can you use this method if you want to modify existing records in the database?
There's a few different ways you can handle this. The easiest way is to pre-populate your form with table rows for each existing row in your database, and add an id (assuming you have an auto-increment primary key for each row) input value for that record on the table row. This way when you're processing the form, you'll be able to see if it's an existing record by checking for the existence of the id in the posted data and verifying that it exists in your database. If it doesn't have an id key you know that it is a new record and you need to do an INSERT, and if it does, you can do an UPDATE or leave the record be. For DELETED rows, you'll want to loop through your POSTed data before doing any INSERTs and gather the id values that have been posted and run a query something like DELETE FROM table WHERE ID IN (<list of posted ids>). This will delete any rows that the user removed, then you can loop through the POSTed data again and insert the new rows.
An example of pre-populating this table would look something like this:
<?php
$query = "SELECT * FROM bill_items WHERE bill_id = 123";
$result = mysql_query($query);
$materials = array();
while ($row = mysql_fetch_assoc($query))
{
$materials []= $row;
}
?>
<? foreach ($materials as $material): ?>
<tr>
<td>
<?= $material['code']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][code]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['component']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][component]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['category'];
<input type="hidden" name="record[<?= $material['id']; ?>][category]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['quantity']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][quantity]"
value="<?= $material['uom']; ?>">
</td>
<td>
<?= $material['uom']; ?>
<input type="hidden" name="record[<?= $material['id']; ?>][uom]"
value="<?= $material['uom']; ?>">
<input type="hidden" name="record[<?= material['id']; ?>][id]"
value="<?= $material['id']; ?>">
</td>
</tr>
<? endforeach; ?>
Also, a note. I changed the javascript example code above. I changed count++ to count-- because when you pre-populate the form with data that is currently in the database you are going to use the id of the material in the input key. When a user adds new data, there is a possibility that the key generated with javascript (with count++) will collide with the existing table data. To rectify this, we change it to count--. This key (in javascript) really isn't important, it's just keeping our data grouped together, so a negative value here does not affect anything.

Categories