PHP button click - value / id to pass over - php

Hey I'm currently having a problem with trying to make my input button have a value of the id / server that I need and it showing a different value this is how my code currently looks I know the HTML and forms are invalid I will be refactoring it however I'm trying to get a server identifier and a id identifier to cross to another page
<?php
$propertyType = $xmlDom1->getElementsByTagName('PropertyType');
$rent = $xmlDom1->getElementsByTagName('rates');
$rooms = $xmlDom1->getElementsByTagName('rooms');
//$server = $xmlDom1->getElementsByTagName('server');
$propertyServer = $xmlDom1->getElementsByTagName('Property');
$propertyID = $xmlDom1->getElementsByTagName('Property');
$imageURL = $xmlDom1->getElementsByTagName('url');
$imageAlt = $xmlDom1->getElementsByTagName('altText');
$server = $propertyID->item($i)->getAttribute('server');
echo '<form action="level5Details.php" method="get" enctype="application/x-www-form-urlencoded">';
echo '<table><th>Type:</th><th>Rent:</th><th>Rooms:</th><th>Server</th>';
$records = $xmlDom1->documentElement->childNodes;
for ($i = 0; $i < $records->length; $i++) {
echo "<tr><td>".$propertyType->item($i)->nodeValue."</td>";
echo "<td>".$rent->item($i)->nodeValue."</td>";
echo "<td>".$rooms->item($i)->nodeValue."</td>";
echo "<td>".$propertyServer->item($i)->getAttribute('Server')."</td>";
echo '<td><img src="data:image/jpeg;base64,'.$imageURL->item($i)->nodeValue.'" alt="'.$imageAlt->item($i)->nodeValue.'"></img></td>';
?>
<td>
<button class="submit" type="submit" value="<?php echo $propertyID->item($i)->getAttribute('pid'); ?>" name="submit22">something </button>
</td>
</tr>
<?php
}
?>
</form>

If you are trying to generate lots of form each with just a button then you need to put the form in a table cell like this
It might also be useful to place the data items you want to pass in hidden fields rather than try and put 2 data items in the button value
<?php
$propertyType = $xmlDom1->getElementsByTagName('PropertyType');
$rent = $xmlDom1->getElementsByTagName('rates');
$rooms = $xmlDom1->getElementsByTagName('rooms');
//$server = $xmlDom1->getElementsByTagName('server');
$propertyServer = $xmlDom1->getElementsByTagName('Property');
$propertyID = $xmlDom1->getElementsByTagName('Property');
$imageURL = $xmlDom1->getElementsByTagName('url');
$imageAlt = $xmlDom1->getElementsByTagName('altText');
$server = $propertyID->item($i)->getAttribute('server');
echo '<table><th>Type:</th><th>Rent:</th><th>Rooms:</th><th>Server</th>';
$records = $xmlDom1->documentElement->childNodes;
for ($i = 0; $i < $records->length; $i++) {
echo "<tr><td>".$propertyType->item($i)->nodeValue."</td>";
echo "<td>".$rent->item($i)->nodeValue."</td>";
echo "<td>".$rooms->item($i)->nodeValue."</td>";
echo "<td>".$propertyServer->item($i)->getAttribute('Server')."</td>";
echo '<td><img src="data:image/jpeg;base64,'.$imageURL->item($i)->nodeValue.'" alt="'.$imageAlt->item($i)->nodeValue.'"></img></td>';
$pid = $propertyID->item($i)->getAttribute('pid');
?>
<td>
<form action="level5Details.php" method="get" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="pid" value="<?php echo $pid;?>">
<input type="hidden" name="server" value="<?php echo $server;?>">
<button class="submit" type="submit" value="submit" name="submit22">something</button>
</form>
</td>
</tr>
<?php
}
?>
If you just want the button to carry all the data and have only one form you will have to package the 2 data items into one string and sent it as the value of the button
<?php
$propertyType = $xmlDom1->getElementsByTagName('PropertyType');
$rent = $xmlDom1->getElementsByTagName('rates');
$rooms = $xmlDom1->getElementsByTagName('rooms');
//$server = $xmlDom1->getElementsByTagName('server');
$propertyServer = $xmlDom1->getElementsByTagName('Property');
$propertyID = $xmlDom1->getElementsByTagName('Property');
$imageURL = $xmlDom1->getElementsByTagName('url');
$imageAlt = $xmlDom1->getElementsByTagName('altText');
$server = $propertyID->item($i)->getAttribute('server');
echo '<form action="level5Details.php" method="get" enctype="application/x-www-form-urlencoded">';
echo '<table><th>Type:</th><th>Rent:</th><th>Rooms:</th><th>Server</th>';
$records = $xmlDom1->documentElement->childNodes;
for ($i = 0; $i < $records->length; $i++) {
echo "<tr><td>".$propertyType->item($i)->nodeValue."</td>";
echo "<td>".$rent->item($i)->nodeValue."</td>";
echo "<td>".$rooms->item($i)->nodeValue."</td>";
echo "<td>".$propertyServer->item($i)->getAttribute('Server')."</td>";
echo '<td><img src="data:image/jpeg;base64,'.$imageURL->item($i)->nodeValue.'" alt="'.$imageAlt->item($i)->nodeValue.'"></img></td>';
$dataPackage = $propertyID->item($i)->getAttribute('pid') . ':' . $server;
?>
<td>
<button class="submit" type="submit" value="<?php echo $dataPackage;?>" name="submit22">something</button>
</td>
</tr>
<?php
}
</table>
</form>
?>
Now in the receiving form unpack the data for use
<?php
// usual checks for things existing
list($pid, $server) = explode(':', $_GET['submit22'];

Related

Unable to insert multiple checkbox data in the database

UPDATED. I'm having problem about inserting multiple checkbox data in the database.
Here is my view
<?php
$i = 0;
$qArr = array();
$qArrc = 0;
$qArr1 = array();
$qArrc1 = 0;
$uArr = array();
$u = 0;
foreach($questions->result() as $q){ ?>
<input type="checkbox" name="check[<?php echo $i; ?>]" value="<?php echo $qArr[$qArrc++] = $q -> questions; ?>"> <?php echo $q->questions; ?> <br>
<input class="form-control" value="<?php echo $uArr[$u++] = $this->session->userdata('user_id'); ?>" name="hidden[<?php echo $i; ?>]" type="hidden">
<input class="form-control" value="<?php echo $qArr1[$qArrc1] = $q->id; ?>" name="hidden1[<?php echo $i; ?>]" type="hidden">
<?php
$i++;
}?>
<button type="submit" name="submit" class="btn btn-primary">Submit</button>
Here's my controller
for($i = 0; $i<count($this->input->post('check')); $i++){
$data1 = array(
'question' => $this->input->post('check')[$i],
'speaker_id' => $this->input->post('hidden')[$i],
'question_id' => $this->input->post('hidden1')[$i]
);
$this->input->post('submit');
$this->Speaker_Model->insert_speakerfeedback($data1);
}redirect('speaker/createfeedback');
Here's my model
public function insert_speakerfeedback($data1){
$this->db->insert("speakerdata", $data1);
}
Modify your for loops :
for($i = 0; $i<count($this->input->post('check')); $i++){
to use foreach instead` :
foreach ($this->input->post('check') as $i => $value) {
So it will prevent getting undefined index if you skip some checkbox. And the redirect line should be outside of the loops.
For bulk insert, you could use insert_batch function.
Within the loop, change :
$data1 = array(
to
$data1[] = array(
So it will not overwriting on each iteration.
And on the Model, change :
$this->db->insert("speakerdata", $data1);
to :
$this->db->insert_batch("speakerdata", $data1);

how to auto increment an input name in html and save in database?

I have a table named positions. This table has the list of the different positions that the admin has added in the listOfPositions.php like President, Vice-President, etc. After adding different positions, he can now add the different people under that position. And that's where my problem is. How will I have an auto increment input name for the names of the people depending on how many positions it has in the table positions ?
I tried using javascript, but it increments only in the html and not reflecting to the php when I try to save. My current code where the adding of the names of different persons depending on the position is the ff:
<script type="text/javascript" src="http://code.jquery.com/jquery-git.js"></script>
<form action="post_officers.php" method="post"><br>
<center><select name="year">
<?php
for($i=date('Y'); $i>1999; $i=$i-2) {
$selected = '';
$year2 = $i-2;
if ($year == $i) $selected = ' selected="selected"';
echo ('<option value="'.$year2. "-" . $i .'" '.$selected.'> '.$year2.'-'.$i.'</option>'."\n");
}
?>
</select></center>
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name" /></td>
</tr>
</table>
<?php
}
?>
<input type="submit" name="submit" value="SAVE"/>
</form>
<script>
$("input[name='file']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='position']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='name']").each(function(ind) {
$(this).attr(ind + 1);
});
</script>
And this is my php code:
<?php
include ('dbcontroller.php');
date_default_timezone_set('Asia/Manila');
$year = mysqli_real_escape_string($conn,$_POST['year']);
if(isset($_POST['submit'])) {
$result = mysqli_query($conn,"SELECT * FROM officers WHERE year = '$year'");
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
echo "<script type='text/javascript'>alert('Year already exists.'); window.location.href='create_alumni_officers.php';</script>";
}
else {
for ($i = 1; $i <= 8; $i++) {
$name = mysqli_real_escape_string($conn,$_POST['name'.$i]);
$position = mysqli_real_escape_string($conn,$_POST['position'.$i]);
$file=(rand(1000,100000)."-".$_FILES['file'.$i]['name']);
$type=($_FILES['file'.$i]['type']);
$size=$_FILES['file'.$i]['size'];
$loc=($_FILES['file'.$i]['tmp_name']);
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
}
}
?>
And this doesn't work at all. Any help? I hope you guys understood what I'm trying to ask.
This is the best way to do it:
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<table id="options-table">
<tr>
<td><input type="file" name="file[<?php echo $position; ?>]" /></td>
<td><input type="hidden" name="position[<?php echo $position; ?>]" value="<?php echo $position; ?>" /><?php echo $position; ?></td>
<td><input type="text" name="name[<?php echo $position; ?>]" /></td>
</tr>
</table>
<?php
}
?>
You don't need the javascript to change input attributes. Remove it.
In php use foreach loop like:
If you are still getting errors I will need to see the output of print_r($_POST);
<?php
$files = $_FILES['file'];
$positions = $_POST['position']; //use this for the foreach loop because it will always have a value
$names = $_POST['name'];
foreach($positions as $key=>$position){
$file = #$files[$key];
$name= #$names[$key];
//Do your magic for each user here
$name = mysqli_real_escape_string($conn,$name);
$position = mysqli_real_escape_string($conn,$position);
$filename = rand(1000,100000)."-".$file['name'];
$type = $file['type'];
$size = $file['size'];
$loc = $file['tmp_name'];
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($filename);
// make file name in lower case
$final_file = str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
?>
As I indicated in the contents, removing context switches miss fide will greatly increase the readability of your code. I'll illustrate below a bit as well as answer the question.
To get what you're after, you could do this:
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name<?php echo $position; ?>" /></td>
</tr>
</table>
<?php
}
However, to illustrate a small example of removing these contextual switches mid code, see below and pardon but this is air code, if you want a more specific example, just ask.
Let's say you often use the tag thoughout your site in forms. You could drop out of php each time and just write out the straight html. Or, you could create a class, or even a simple function for the html output thusly:
Function opt($int, $parms = '') {
Return '<Option '.$parms.'>'. $int.'</option>';
}
Now your code would look more like this:
While ($r =mysqli_fetch_array ($result)) {
Extract ($r); // learn this, no sense assigning them 1 by 1
$options .= opt($databaseobject, 'name="foo" value="'. $databaseobjectid.'"');
}
Echo $options;

PHP for loop concatenation

for($i = 1; $i <= 1; $i++) {
$you_item[$i] = ucwords($_POST['you_item'.$i.'']);
$you_item[$i] = "http://steamcommunity.com/market/priceoverview/?appid=570&currency=1&market_hash_name=".$you_item[$i]."";
$you_item[$i] = str_replace(' ', '%20', $you_item[$i]);
$you_item[$i] = file_get_contents($you_item[$i]);
$you_item[$i] = json_decode($you_item[$i], true);
$you_item[$i] = $you_item[$i]['median_price'];
$you_item[$i] = preg_replace("/&#?[a-z0-9]{2,8};/i","", $you_item[$i]);
echo $you_item[$i];
}
the sample site is this http://bit.ly/1gKGoN0
I have a problem on the loop of getting the value from the textboxes
i declared the form like this
<?php for($i=1;$i<=15;$i++){ ?> <input type="text" name="<?php echo
"you_item".$i.""?>" /> <?php } ?>
but the problem now is i cant get the value from the textboxes where i forwarded to $you_item[$i].
the site that i made doesnt have a loop. i coded the $you_item1 upto 15 because i have 15 textboxes.
can someone help me out?
try to change,
<?php for($i=1;$i<=15;$i++){ ?> <input type="text" name="<?php echo
"you_item".$i.""?>" /> <?php } ?>
to
<input type="text" name="you_item[]" />

more than 1 form at one page

I've problem with multiple form at one page. At page index I include 4 forms
include('./poll_1a.php');
include('./poll_2a.php');
include('./poll_3a.php');
include('./poll_4a.php');
The form code at every poll page is the same. I include some unique markers ($poll_code) for every scripts but the effect is when I use one form - the sending variable are received in the others. But I would like to work each form individually.
The variable $poll_code is unique for every script -> 1 for poll_1, 2 for poll_2 etc.
The same situation is with $cookie_name
$cookie_name = "poll_cookie_".$poll_code;
than, as I see, cookies have different names.
$poll_code = "1"; // or 2, 3, 4
?>
<p>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" name="<?php echo $poll_code; ?>">
<input type="hidden" name="poll_cookie_<?php echo $poll_code; ?>" value="<?php echo $poll_code; ?>">
<table>
<?php
//print possible answers
for($i=0;$i<count($answers);$i++){
?><tr><td style="\text-allign: left;\"><input type="radio" name="vote_<?php echo $poll_code; ?>" value="<?php echo $i; ?>"> <?php echo $answers[$i]; ?></td></tr><?php
}
echo "</table>";
echo "<br>";
if ($_COOKIE["$cookie_name"] == $poll_code ) {
echo "<br> nie można głosować ponownie ...";
} else {
?>
<p><input type="submit" name="submit_<?php echo $poll_code; ?>" value="głosuj !" onClick="this.disabled = 'true';"></p>
<?php
}
?>
</form>
</p>
Q: how to make this forms to work individually at one page?
//------------------- EDIT
the receiving part of the script
$votes = file($file);
$total = 0;
$totale = 0;
$poll_cookie = 0;
if (isset($_POST["vote_$poll_code"]) && isset($_POST["poll_cookie_$poll_code"])) {
$vote = $_POST["vote_$poll_code"];
$poll_cookie = $_POST["poll_cookie_$poll_code"];
}
//submit vote
if(isset($vote)){
$votes[$vote] = $votes[$vote]+1;
}
//write votes
$handle = fopen($file,"w");
foreach($votes as $v){
$total += $v;
fputs($handle,chop($v)."\n");
}
fclose($handle);
Of course, the $file have the unique declaration too (at top of the script, under the $poll_code declaration).
$file = "poll_".$poll_code.".txt";
I think the issue might be that <?php echo $poll_code; ?> is outside the loop so maybe that it's always using the same value assigned to it, maybe put it inside the loop

Reflecting sub records in PHP from MySQL

I am trying to get records from my DB using 2 seperate tables. The query is
public function get_pages_by_campign_id($campaignID) {
$campaignID = $this->real_escape_string($campaignID);
return $this->query("SELECT pid, campaignid FROM pages,campaigns WHERE 'pages.campaignid = campaigns.id'");
}
And this is called into play by :
$counter = 1;
$userID = PageDB::getInstance()->get_user_id_by_name($_SESSION['user']);
$result = PageDB::getInstance()->get_pages_by_campaign_id($campaignID);
$i=0;
while ($row = mysqli_fetch_array($result)):
$style = "";
if($i%2==0)
{
$style = ' style="background-color: #EFEFEF"';
}
echo "<tr".$style.">";
echo "<td style='width:140px;'> Page " . $counter . "</td>";
echo "<td> </td>";
echo "<td></td>";
//The loop is left open
?>
<td>
<form style="display:none;"></form>
<form name="editPage" action="editPage.php" method="GET">
<input type="hidden" name="pageID" value="<?php echo $pageID = $row['pid']; ?>"/>
<input type="submit" name="editPage" value="Edit"/>
</form>
</td>
<td>
<form name="deletePage" action="deletePage.php" method="POST">
<input type="hidden" name="pageID" value="<?php echo $pageID = $row['pid']?>"/>
<input type="submit" name="deletePage" value="Delete" onclick = "javascript: return confirm('Delete Page <?php echo $counter ?> ?');"/>
</form>
</td>
<?php
$pageID = $row['pid'];
$counter++;
$i++;
echo "</tr>\n";
endwhile;
mysqli_free_result($result);
?>
This should list all "page" Records, but it is returning nothing.
I have set up the "id" column in table "campaigns" to correspond with "campaignid" in table "pages" using foreign keys.
I manged to fix it with this :
public function get_pages_by_campaign_id($campaignID) {
$campaignID = $this->real_escape_string($campaignID);
return $this->query("SELECT pid, campaignid FROM pages WHERE campaignid = 'campaigns.id'");
}
"SELECT pid, campaignid FROM pages,campaigns WHERE pages.campaignid = campaigns.id"
?

Categories