Why I am unable to pass a variable in PHP - php

I got a function.php which is in inc/function. This function contains a table. This table is generated in an MySQL statement.
My idea is quite easy - the user is able to go through the table with a next button and a back button.
Here is my code:
<div class="container-fluid">
<form action="fda.php" method="post">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<p>Bitte beantworten Sie die folgenden Fragen:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Nr.</th>
<th width="250">Frage</th>
<?php tbl_description() ?>
</tr>
</thead>
<tbody>
<?php tbl_showPage() ?>
</tbody>
</table>
</div>
<div class="col-md-6 col-md-offset-3 text-center">
<form action="functions.php" method="post">
<input type="submit" name="back" value="Zurück" id="back" class="btn btn-default">
<input type="submit" name="go" value="Weiter" id="go" class="btn btn-default">
<!--<input type="submit" value="FDA auswerten" class="btn btn-default">-->
</div>
</div>
</form>
</div>
this is the part from the fda.php file! Everything is working cool except the increase of the mysql statement which is in the function.php.
While clicking on next the statement should be "refreshed" and show me the 2nd page of the table. Its like an questionaire.
This is the code of the function php.
function tbl_showPage(){
global $mysqlhost, $mysqluser, $mysqlpwd, $mysqldb;
$connection=mysqli_connect($mysqlhost, $mysqluser, $mysqlpwd) or die ("Verbindungsversuch fehlgeschlagen");
mysqli_select_db($connection, $mysqldb) or die("Konnte die Datenbank nicht waehlen.");
if(isset($_POST['go']))
{
$page++;
}
elseif($_POST['back'])
{
$page--;
}
//if(isset($page)){
if($page<1)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='1'";
}
elseif($page>9)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='9'";
}
else
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension=$page";
}
//}
$quest_query = mysqli_query($connection, $sql_tbl_questions) or die("Anfrage nicht erfolgreich");
$i = 0;
while ($question = mysqli_fetch_array($quest_query)) {
$i++;
echo '<tr>';
echo '<th>'.$i.'</th>';
echo '<th>'.$question['question'].'</th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="0" required></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="2.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="7.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="10"></th>';
echo '</tr>';
$dimensions = $question['dimension'];
}
echo '<tr>';
echo '<th></th>';
echo '<th>Kommentar/Ihre Anmerkung</th>';
echo '<th class="text-center" colspan=5><textarea rows=3 cols=50 name="Kommentar"></textarea></th>';
echo '</tr>';
echo '<input type="hidden" name="gesamt" value="'.$i.'">';
echo '<input type="hidden" name="dimensions" value="'.$dimensions.'">';
echo '<input type="hidden" name="size" value="'.$_POST['size'].'">';
echo '<input type="hidden" name="branche" value="'.$_POST['branche'].'">';
}
Maybe I am missing something? I really hope someone can help me!

I see two problems here:
The form is submitting both 'back' and 'go' variables, regardless of which one was clicked.
The PHP script is not tracking the $page variable across page loads. (If it is not tracked, it will re-initialize to 0 every time the page is loaded.)
Try having your form tell the PHP script which page to load:
<form action="functions.php" method="post">
<button type="submit" name="page" value="<?php echo $page - 1; ?>">Zurück</button>
<button type="submit" name="page value="<?php echo $page + 1; ?>">Weiter</button>
</form>
Then in your PHP, you would just check for the value of $_POST['page']
if(!empty($_POST['page'])) {
$page = intval($_POST['page']);
} else {
$page = 1;
}
You will also need to make the $page variable visible from the fda.php script into the function.php script. You could do that using global $page; next to your mysql variables. (That's not an optimal or clean way of doing things, but it would be the easiest addition to your code.)

Related

How to insert HTML Form array into database rows in mySQL with PHP

Insert HTML Form array into database rows in mySQL with PHP
i am inserting html array into database using for and foreach
problem inserting data in to database using for loop its inserting blank data
please help. please give advice on it or give solution thank you in advance
i have tried the below code or any different method using for it.
php file
if(isset($_POST['submitmultiple']))
{
$course_id = $_POST['course_id'];
$topic_name = $_POST['topic_name'];
$topic_description = $_POST['topic_description'];
$parent_id = $_POST['parent_id'];
echo count($course_id);
if(!empty($course_id))
{
for($i = 0; $i < count($course_id); $i++)
{
/*if(!empty($course_id[$i]))
{*/
foreach ($_POST['course_id'] as $value)
{
$course_id = $course_id[$i];
$topic_name = $topic_name[$i];
$topic_description = $topic_description[$i];
$parent_id = $parent_id[$i];
$sql = "INSERT INTO syllabus (course_id,topic_name,topic_description,parent_id) VALUES ('$course_id','$topic_name','$course_description','$parent_id')";
if($connect->query($sql) === TRUE)
{
$valid[1] = "Added Successfully";
}
else
{
$valid[2] = "Error while Inserting";
}
}
/*}*/
}
}
}
html code
<form id="submitMultipleData" class="submitMultipleData" role="form" name="hl_form" method="post" >
<div class="box-body">
<div class="row">
</div>
<!-- /.row -->
<table class="table table-bordered table-striped table-condensed table-hover" id="dynamic_field">
<th>Course Name</th>
<th>Topic Name</th>
<th>Description</th>
<th>Parent Topic Name</th>
<th>Action</th>
<tr id="id" class="trrow">
<td class="col-md-4">
<select class="form-control select2 selectCourse" data-id="1" id="course_id_1" name="course_id[]" data-live-search="true" >
<option value="" selected="selected"> Select Course Name</option>
<?php
$sql = "SELECT * from course_master";
$result = $connect->query($sql);
while($row_pt = $result->fetch_array())
{
?>
<option value="<?php echo $row_pt['course_id']; ?>"><?php echo $row_pt['course_name']; ?></option>
<?php
}
?>
</select >
</td>
<td class="col-md-2"> <input class="form-control topic_name" id="topic_name1" name="topic_name[]" maxlength="250" value="" placeholder="Enter Topic Name" type="text" ></td>
<td class="col-md-4"><textarea class="form-control" style="resize: none;" id="topic_description1" name="topic_description[]" rows="3" placeholder="Enter Description"></textarea></td>
<td class="col-md-2"><select class="form-control select2" id="parent_id_1" name="parent_id[]" data-live-search="true" ></select></td>
<td class="col-md-2"><input type="button" name="add" value="Add Row" class="btn btn-success"></td>
</tr>
</table>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="submitmultiple" id="button" class="btn btn-primary btn-form-action btn-submit">Save</button>
</div>
</form>
Assuming the value at indexes is related for course/topic/parent, etc.
You can skip one of the for loops too.
if(isset($_POST['submitmultiple']))
{
$course_id = $_POST['course_id'];
$topic_name = $_POST['topic_name'];
$topic_description = $_POST['topic_description'];
$parent_id = $_POST['parent_id'];
echo count($course_id);
if(!empty($course_id))
{
foreach ($_POST['course_id'] as $key => $value)
{
$tempcourse_id = $course_id[$key];
$temptopic_name = $topic_name[$key];
$temptopic_description = $topic_description[$key];
$tempparent_id = $parent_id[$key];
$sql = "INSERT INTO syllabus (course_id,topic_name,topic_description,parent_id) VALUES ('$tempcourse_id','$temptopic_name','$temptopic_description','$tempparent_id')";
//Verify the query formed
echo $sql."\n";
if($connect->query($sql) === TRUE)
{
$valid[1] = "Added Successfully";
}
else
{
$valid[2] = "Error while Inserting";
}
}
}
}
1) your question is not clear - dont understand how sending multiple cources
add multiple here
select
to
select multiple
2) add single quotes along fields
(course_id,topic_name,topic_description,parent_id)
to
('course_id','topic_name','topic_description','parent_id')
after changing these few changes i can see this query by submitting form
INSERT INTO syllabus ('course_id','topic_name','topic_description','parent_id') VALUES ('c2','asd','','1')
query seems fine - should insert data

Need to Insert Multiple Data by selecting Checkboxes

I need to Insert data to the DB using the form given below
<form action="OtherEventPayment.php" id="frmSignIn" method="post">
<input type="hidden" name="online_id" value="<?php echo $lid; ?>" >
<table class="table">
<thead>
<tr>
<th>#</th>
<th>Item</th>
<th>No. of Participants</th>
<th>Tick the Items</th>
</tr>
</thead>
<tbody>
<tbody>
<?php
$sn ="1";
$id = $oth_event_id;
$stmt1 = $DB_con->prepare('SELECT * FROM oth_events_details
LEFT JOIN oth_event_category ON (oth_events_details.oth_evcat_id=oth_event_category.oth_evcat_id)
WHERE oth_event_id =:uid ORDER BY oth_event_det_id DESC');
$stmt1->execute(array(':uid'=>$id));
$stmt1->execute();
if($stmt1->rowCount() > 0)
{
while($row1=$stmt1->fetch(PDO::FETCH_ASSOC))
{
extract($row1);
?>
<tr>
<td><?php echo $sn; ?></td>
<td>
<?php echo $row1['oth_category'];?> -
<?php
$group =$row1['oth_catgroup_type'];
if ($group=="S")
{
echo "Single";
}
elseif ($group=="D")
{
echo "Doubles";
}
else{
echo "Group";
}
?>
</td>
<td><?php echo $row1['participntno']; ?></td>
<td>
<b>
</b>
<input type="checkbox" name="chk[<?php echo $row1['oth_event_det_id'];?>]" value="<?php echo $row1['oth_event_det_id'];?>" id="chk[<?php echo $row1['oth_event_det_id'];?>]" />
Fees:- <?php echo $row1['oth_ev_fee'];?>
</td>
</tr>
<?php $sn++; ?>
<?php
}
}
else
{
?>
<div class="col-xs-12">
<div class="alert alert-warning">
<span class="glyphicon glyphicon-info-sign"></span> No Data Found ...
</div>
</div>
<?php
}
?>
</tbody>
</table>
<div class="col-md-6">
<input type="submit" name="selectItems" value="Submit & Proceed" class="btn btn-primary pull-right mb-xl" data-loading-text="Loading...">
</div>
</div>
<?php echo $sn1=$sn-1; ?>
</form>
in the OtherEventPayment.php i have written the code. But not working . How to Insert data correctly to DB
<?php
require_once 'dbconfig.php';
if(isset($_POST['selectItems']))
{
echo array[] = $_POST['chk[]'];
echo $oth_online_id= $_POST['online_id'];
if($oth_event_detid != ""){
for($i=0;$i<sizeof($oth_event_detid);$i++)
{
// oth_event_det_id,oth_online_id
$stmt = $DB_con->prepare('INSERT INTO othevents_itemsonline(oth_event_det_id,oth_online_id) VALUES( :oth_event_det_id, :oth_online_id)');
$stmt->bindParam(':oth_event_det_id',$oth_event_det_id);
$stmt->bindParam(':oth_online_id',$oth_online_id);
if($stmt->execute())
{
$lastonlineid= $DB_con->lastInsertId();
$successMSG = "Thank you For Registering with us . Please select the items to be participating...";
// header("refresh:0;OtherEventsOnlineRegistrationThankyou.php"); /
}
else
{
$errMSG = "error while registering....";
} } }
}
?>
Name should be same for input field. Use following code:
<input type="checkbox" name="chk[]" value="<?php echo $row1['oth_event_det_id'];?>" id="chk[<?php echo $row1['oth_event_det_id'];?>]" />
Fees:- <?php echo $row1['oth_ev_fee'];?>
You can see name. Hopefully it will be clear enough
Just change the value of you checkboxes and the value it represents but keep the name same with the others, yet it should have a name with []
<input type="checkbox" id="chk<?php echo $row1['oth_event_det_id'];?>" name="chk[]" value="<?php echo $row1['oth_event_det_id'];?>">
<label for="chk<?php echo $row1['oth_event_det_id'];?>"><?php echo $row1['oth_event_det_id'];?></label>
having a name chk[] like this will send and serve as an array in your get or post-function so loop it on controller or function that will add it in the DB
upon inserting it,
$data = $_GET['chk']; //this is in array form
foreach($data as $chk){
//insert code here
}

How can I Copy the value of textbox to my query In PHP

I have my textbox named Title here!
The Title is the upper most Textbox!
I have a query where i should copy the value of that textbox which is 'A' to my query here
$sql_query="SELECT * FROM tblpost WHERE Page = 'A' ";
this is exactly my code! Hope everyone can guide me because I am Actually new in PHP this is my whole code
<form method="post">
<div class="form-group">
<label>Page Title</label>
<input name="title" type="text" value="<?php echo $fetched_row['Title']; ?>" required class="form-control" placeholder="Page Title">
</div>
<div class="form-group">
<select class="form-control" name="active" id="active">
<option value="">~~SELECT~~</option>
<option value="Actived">Activated</option>
<option value="Deactivated">Deactivated</option>
</select>
</div>
<div class="form-group">
<label>Meta Tags</label>
<input type="text" value="<?php echo $fetched_row['Tags']; ?>" name="tags" required class="form-control" placeholder="Add Some Tags...">
</div>
<div class="form-group">
<label>Category</label>
<input type="text" name="description" value="<?php echo $fetched_row['Description']; ?>" class="form-control" required placeholder="Add Category...">
</div>
<table class="table table-striped table-hover" id="myTable">
<tr>
<th>Page Title</th>
<th>Status</th>
<th>Date Created</th>
<th></th>
</tr>
<?php
$sql_query="SELECT * FROM tblpost WHERE Page = //I think it's right here ";
$result_set=mysql_query($sql_query);
while($row=mysql_fetch_row($result_set))
{
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td><?php echo $row[3]; ?></td>
<td><?php echo $row[6]; ?></td>
<td><a class="btn btn-primary" href="javascript:edt_id('<?php echo $row[0]; ?>')">Edit</a> <a class="btn btn-danger" href="javascript:delete_id('<?php echo $row[0]; ?>')">Delete</a></td>
</tr>
<?php
}
?>
<script>
function myFunction() {
var input, filter, table, tr, td, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
</table>
<center> <button type="submit" class="btn btn-primary" name="btn-update"><strong>UPDATE</strong></button> <button type="submit" class="btn btn-default" name="btn-cancel"><strong>Cancel</strong></button></center>
</form>
If I understand your code snippet correctly, at page load time the "title" is carries in a array variable: $fetched_row['Title']
So essentially your code should be something like:
$sql_query="SELECT * FROM tblpost WHERE Page = '".mysql_real_escape_string($fetched_row['Title'])."';";
If this is new code, you really should use mysqli instead of the deprecated mysql, if at all possible.
You should first check, if the form was sent and then just use the $_POST variable in your sql query, by doing something like this:
if (isset($_POST['btn-update'])) {
$sql_query="SELECT * FROM tblpost WHERE Page = '".$_POST['title']."'";
// ... more code
}
This, however, is a really unsafe approach and you shouldn't use the standard mysql_ functions and instead have a look at for example mysqli and prepared statements
In php include connection code and get the input box value
<?php
include("connection.php"); //INCLUDE CONNECTION STRING
$textbox1=$_REQUEST['title']; // It's for both post/get methods
if (isset($_REQUEST['btn-update'])) { //check the button click by button name
$sql="SELECT * FROM tblpost WHERE Page = '.$textbox1'";
}
?>
Suggestion:Change the name of the button
Use the name attribute to get the value of the textbox like this:
$textTitle = $_POST['title'];
$textTitle is a variable that returns the value of the textbox.
We use $_POST[] variable because you are using post method in your form.
title is the name attribute of the input type text.

Php Shopping Cart Add button isn't working

I have here a sample of shopping cart using php. I tried to modify it to what I need. What I add here is a search function using ajax/jquery. The search engine working but the problem is the add button isn't working. Why I can't add a item in the list? What I does here is separate the table in index.php into search.php so when I try to search only the item what I need is going to display in table. Any help will appreciate.
Search.php
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
if(isset($_POST['bid'])) {
$search = $mysqli->real_escape_string($_POST['bid']);
$search = preg_replace("/[^A-Za-z0-9 ]/", '', $search);
$search = $_POST['bid'];
$results = $mysqli->query("SELECT * from app WHERE item_name LIKE '%$search%' ORDER BY item_name ASC");
echo'<table id="tfhover" cellspacing="0" class="table-list" style="text-transform:uppercase;" border="1">
<thead>
<tr>
<th></th>
</tr>
</thead>';
echo'<tbody>';
if(($results->num_rows)>= 1){
while($obj = $results->fetch_object())
{
echo '<form method="post" action="cart_update.php">';
echo '<tr>
<td style="text-align:left;">'.$obj->item_name.'</td>
<td><button class="add_to_cart" style="font-size:9px;">Add</button></td>
</tr>';
echo '<input type="hidden" name="product_code" value="'.$obj->counter.'" />';
echo '<input type="hidden" name="type" value="add" />';
echo '<input type="hidden" name="return_url" value="'.$current_url.'" />';
echo '</form>';
}
echo "</tbody></table>";
}
if(($results->num_rows)<= 0){
echo '<div style="margin-left:360px;">No Results</div>';
}
}
?>
Index.php
<?php
session_start();
include_once("config.php");
//current URL of the Page. cart_update.php redirects back to this URL
$current_url = base64_encode($url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
?>
<input type="text" name="bid" id="bid" placeholder="Search" style="text-transform:uppercase;width:300px;text-align:center;"/>
<div id="bid_result"></div>
<script type="text/javascript">
$(document).ready(function () {
function load(query) {
$.post('search.php', {
bid: query
}, function (search_bid) {
$('#bid_result').stop(true, true).fadeIn(200).html(search_bid);
}); //End ajax call
}
load($("#bid").val());
//Live search
$("#bid").on('keyup', function () {
//Input field value
load($(this).val());
}); //End on function
}); //End document.ready state
</script>
Cart_update.php
Here's my complete code of cart_update.php http://pastebin.com/1iDENLa0
<?php
session_start();
include_once("config.php");
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$product_code = filter_var($_POST["product_code"], FILTER_SANITIZE_STRING); // product code
$return_url = base64_decode($_POST["return_url"]); //return url
}
?>
Ok, i changed some parts of your code, can you check this code? It should submit.
<?php
echo '
<table id="tfhover" cellspacing="0" class="table-list" style="text-transform:uppercase;" border="1">
<thead>
<tr>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>';
if(($results->num_rows)>= 1) {
while($obj = $results->fetch_object()) {
echo '
<form method="post" action="cart_update.php">
<input type="hidden" name="product_code" value="'.$obj->counter.'" />
<input type="hidden" name="type" value="add" />
<input type="hidden" name="return_url" value="'.$current_url.'" />
<input type="submit" class="add_to_cart" value="Add" style="font-size:9px;"/>
</form>';
}
echo '</tr></td>';
}
echo "</tbody></table>";
?>

Pagination of records from MySQL Database

I have a script that counts how many records it sees on the page :
<script>
document.write(document.getElementById('moon').rows.length-1);
document.write (' ');
document.write (' of ');
document.write (' ');
document.write(document.getElementById('moon').rows.length-1);
document.write (' pages');
</script>
How would I use this to paginate 10 records at a time?
Perhaps using a styling such as display:none or something and then linking to these hidden divs on the "page" count.
Thanks
Edit:
I have tried to use a PHP Mysql Query to do this with num_rows, but it always throws out errors even when I am getting data!
2nd EDIT
Ok, I am pulling the information and displaying it with:
<table class="std" id="moon" border="0" cellpadding="0" cellspacing="0">
<tr>
<?php
$pcounter = 1;
$userID = LedDB::getInstance()->get_user_id_by_name($_SESSION['user']);
$presult = LedDB::getInstance()->get_page_by_campaign_id($campaignID);
$i=0;
while ($row = mysqli_fetch_array($presult)):
$style = "";
if($i%2==0)
{
$style = 'style="background-color: #EFEFEF"';
}
echo "<tr ".$style.">";
echo "<td class='camp' style='padding-left:10px;'><b><a href='editPage.php?pageID=" .htmlentities($row['pid']) ."&campaignID=" .htmlentities($row['campaignid']) ."' class='camp'> Page" . $pcounter . "</a></b></td>";
echo "<td style='padding-left:10px;'></td>";
echo "<td style='padding-left:10px;'></td>";
echo "<td></td>";
echo "<td></td>";
$pageID = $row['pid'];
//The loop is left open
?>
<td>
<div class="buttons">
<form name="editPage" action="editPage.php" method="GET">
<input type="hidden" name="campaignID" value="<?php echo $campaignID ?>"/>
<input type="hidden" name="pageID" value="<?php echo $pageID ?>"/>
<button type="submit" name="editPage" value="Edit" class="blue" >
<img src="images/edit.png" width="20" height="20"></button>
</form>
</div>
</td>
<td>
<form name="deletePage" action="deletePage.php" method="POST">
<input type="hidden" name="pageID" value="<?php echo $pageID; ?>"/>
<div class="buttons">
<button type="submit" name="deletePage" value="Delete" class="negative">
<img src="images/delete_x.png" width="20" height="20"></button>
</div>
</form>
</td>
<?php
echo "</tr>\n";
$pcounter++;
$i++;
endwhile;
mysqli_free_result($presult);
?>
</table>
Where $presult = LedDB::getInstance()->get_page_by_campaign_id($campaignID); is this:
public function get_page_by_campaign_id($campaignID) {
$campaignID = $this->real_escape_string($campaignID);
return $this->query("SELECT pid,campaignid,message_text,message FROM pages WHERE campaignid =" . $campaignID );
}
Whenever I try to wrap this in a pagination class, it either returns a 0 value or just bombs out my entire script with sql_num_rows() errors...
That is the reason I thought javascript pagination would be the best solution in this case.
There are several examples on the web to get you started, thats where I'd start:
http://www.phpclasses.org/search.html?words=pagination&x=0&y=0&go_search=1
http://www.phpsnaps.com/snaps/view/php-pagination-class/
http://www.phpbuilder.com/board/showthread.php?t=10283679
http://phpsense.com/2007/php-pagination-script/

Categories